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.artifactory.resource.ExpiredRepoResource.java

@Override
public int getStatusCode() {
    return HttpStatus.SC_NOT_FOUND;
}

From source file:org.artifactory.resource.UnfoundRepoResource.java

public UnfoundRepoResource(RepoPath repoPath, String reason) {
    this(repoPath, reason, HttpStatus.SC_NOT_FOUND);
}

From source file:org.artifactory.resource.UnfoundRepoResource.java

public UnfoundRepoResource(RepoPath repoPath, String reason, int statusCode) {
    this.repoPath = repoPath;
    this.reason = reason;
    this.statusCode = statusCode > 0 ? statusCode : HttpStatus.SC_NOT_FOUND;
}

From source file:org.artifactory.rest.common.ArtifactoryRestExceptionMapper.java

/**
 * Handle forbidden response (403) by verifying is anonymous access is globally allowed, if so we need to send
 * an unauthorized (401) response with basic authentication challenge.
 * If the global hide unauthorized resources is set, the result will be not found (404).
 *
 * @param jerseyResponse The original response, will be returned in there is no need for a conversion.
 *///from  w ww  . ja va2 s . c  o  m
private Response interceptForbiddenStatus(Response jerseyResponse) {
    if (authorizationService.isAnonAccessEnabled() && authorizationService.isAnonymous()) {
        if (centralConfig.getDescriptor().getSecurity().isHideUnauthorizedResources()) {
            return Response.status(HttpStatus.SC_NOT_FOUND).build();
        }

        return createUnauthorizedResponseWithChallenge(jerseyResponse);
    }

    return jerseyResponse;
}

From source file:org.artifactory.rest.resource.repositories.RepoConfigurationResource.java

/**
 * Returns the remote repository descriptor of the given key, if shared
 *
 * @return Json generated descriptor/*from  w w  w . ja v a  2s. com*/
 * @throws IOException
 */
@GET
@Produces({ RepositoriesRestConstants.MT_REMOTE_REPOSITORY_CONFIGURATION, MediaType.APPLICATION_JSON })
public Response getRemoteDescriptor() throws IOException {
    List<RemoteRepoDescriptor> remoteRepoDescriptors = repositoryService.getRemoteRepoDescriptors();
    for (RemoteRepoDescriptor remoteRepoDescriptor : remoteRepoDescriptors) {
        String currentRepoKey = remoteRepoDescriptor.getKey();
        if (remoteRepoKey.equals(currentRepoKey) && remoteRepoDescriptor.isShareConfiguration()) {
            return Response.ok().entity(maskData(remoteRepoDescriptor)).build();
        }
    }
    return Response.status(HttpStatus.SC_NOT_FOUND).build();
}

From source file:org.broadleafcommerce.core.web.api.BroadleafSpringRestExceptionMapper.java

@ExceptionHandler(NoHandlerFoundException.class)
public @ResponseBody ErrorWrapper handleNoHandlerFoundException(HttpServletRequest request,
        HttpServletResponse response, Exception ex) {
    ErrorWrapper errorWrapper = (ErrorWrapper) context.getBean(ErrorWrapper.class.getName());
    Locale locale = null;// www  .j a  v  a2 s  .c om
    BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext();
    if (requestContext != null) {
        locale = requestContext.getJavaLocale();
    }

    LOG.error("An error occured invoking a REST service", ex);
    if (locale == null) {
        locale = Locale.getDefault();
    }
    errorWrapper.setHttpStatusCode(HttpStatus.SC_NOT_FOUND);
    response.setStatus(resolveResponseStatusCode(ex, errorWrapper));
    ErrorMessageWrapper errorMessageWrapper = (ErrorMessageWrapper) context
            .getBean(ErrorMessageWrapper.class.getName());
    errorMessageWrapper.setMessageKey(resolveClientMessageKey(BroadleafWebServicesException.NOT_FOUND));
    errorMessageWrapper.setMessage(messageSource.getMessage(BroadleafWebServicesException.NOT_FOUND, null,
            BroadleafWebServicesException.NOT_FOUND, locale));
    errorWrapper.getMessages().add(errorMessageWrapper);

    return errorWrapper;
}

From source file:org.collectionspace.chain.csp.webui.authorities.AuthoritiesVocabulariesInitialize.java

public int createIfMissingAuthority(Storage storage, StringBuffer tty, Record record, Instance instance)
        throws ExistException, UnimplementedException, UIException, JSONException, UnderlyingStorageException {
    int result = HttpStatus.SC_OK;

    String url = record.getID() + "/" + instance.getTitleRef();
    try {//w  ww  .ja  v a  2 s .  com
        storage.getPathsJSON(url, new JSONObject()).toString();
        if (tty != null) {
            log.debug("--- Instance " + instance.getID() + " exists.");
            tty.append("--- Instance " + instance.getID() + " exists.\n");
        }
    } catch (UnderlyingStorageException e) {
        if (e.getStatus() == HttpStatus.SC_NOT_FOUND) {
            failedPosts++; // assume we're going to fail
            log.info("Need to create instance " + fInstance.getID());
            if (tty != null) {
                tty.append("Need to create instance " + fInstance.getID() + '\n');
            }
            JSONObject fields = new JSONObject("{'displayName':'" + instance.getTitle()
                    + "', 'shortIdentifier':'" + instance.getWebURL() + "'}");
            String base = record.getID();
            storage.autocreateJSON(base, fields, null);
            failedPosts--; // We succeeded, so subtract our assumed failure
            log.info("Instance " + instance.getID() + " created.");
            if (tty != null) {
                tty.append("Instance " + instance.getID() + " created.\n");
            }
        } else if (e.getStatus() == HttpStatus.SC_FORBIDDEN) {
            result = -1; // We don't have the permissions needed to see if the instance exists.
        } else {
            throw e;
        }
    }

    return result;
}

From source file:org.collectionspace.services.client.test.ServiceLayerTest.java

@Test
public void nonexistentService() {
    if (logger.isDebugEnabled()) {
        logger.debug(BaseServiceTest.testBanner("nonexistentService", CLASS_NAME));
    }/*  ww  w.java2s . c o m*/
    String url = serviceClient.getBaseURL() + "nonexistent-service";
    GetMethod method = new GetMethod(url);
    try {
        int statusCode = httpClient.executeMethod(method);
        if (logger.isDebugEnabled()) {
            logger.debug("nonexistentService url=" + url + " status=" + statusCode);
        }
        Assert.assertEquals(statusCode, HttpStatus.SC_NOT_FOUND, "expected " + HttpStatus.SC_NOT_FOUND);
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: ", e);
    } catch (IOException e) {
        logger.error("Fatal transport error", e);
    } catch (Exception e) {
        logger.error("unknown exception ", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.dasein.persist.riak.RiakCache.java

@Override
public long count(SearchTerm... terms) throws PersistenceException {
    if (terms == null || terms.length < 1) {
        return count();
    }/*from w ww  .j  a  va2  s. com*/
    if (wire.isDebugEnabled()) {
        startCall("count");
    }
    try {
        String mapFunction = buildMapFunction(true, terms);

        HashMap<String, Object> request = new HashMap<String, Object>();
        HashMap<String, Object> inputs = new HashMap<String, Object>();

        terms = matchKeys(inputs, terms);
        if (inputs.size() < 1) {
            request.put("inputs", getBucket());
        } else {
            inputs.put("bucket", getBucket());
            request.put("inputs", inputs);
        }

        ArrayList<Map<String, Object>> query = new ArrayList<Map<String, Object>>();
        HashMap<String, Object> maps = new HashMap<String, Object>();
        HashMap<String, Object> reduces = new HashMap<String, Object>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        HashMap<String, Object> reduce = new HashMap<String, Object>();

        map.put("language", "javascript");
        map.put("source", mapFunction);
        map.put("keep", true);
        maps.put("map", map);

        reduce.put("language", "javascript");
        reduce.put("keep", true);
        reduce.put("name", "Riak.reduceSum");
        reduces.put("reduce", reduce);

        query.add(maps);
        query.add(reduces);
        request.put("query", query);

        String json = (new JSONObject(request)).toString();

        HttpClient client = getClient();
        PostMethod post = new PostMethod(getEndpoint() + "mapred");
        int code;

        try {
            post.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
            if (wire.isDebugEnabled()) {
                try {
                    wire.debug(post.getName() + " " + getEndpoint() + "mapred");
                    wire.debug("");
                    for (Header h : post.getRequestHeaders()) {
                        wire.debug(h.getName() + ": " + h.getValue());
                    }
                    wire.debug("Content-length: " + post.getRequestEntity().getContentLength());
                    wire.debug("Content-type: " + post.getRequestEntity().getContentType());
                    wire.debug("");
                    wire.debug(((StringRequestEntity) post.getRequestEntity()).getContent());
                    wire.debug("");
                } catch (Throwable ignore) {
                    // ignore
                }
            }
            code = client.executeMethod(post);
        } catch (HttpException e) {
            throw new PersistenceException("HttpException during POST: " + e.getMessage());
        } catch (IOException e) {
            throw new PersistenceException("IOException during POST: " + e.getMessage());
        }
        try {
            String body = post.getResponseBodyAsString();

            try {
                if (wire.isDebugEnabled()) {
                    wire.debug("----------------------------------------");
                    wire.debug("");
                    wire.debug(post.getStatusLine().getStatusCode() + " "
                            + post.getStatusLine().getReasonPhrase());
                    wire.debug("");
                    if (body != null) {
                        wire.debug(body);
                        wire.debug("");
                    }
                }
            } catch (Throwable ignore) {
                // ignore
            }
            if (code != HttpStatus.SC_OK) {
                if (code == HttpStatus.SC_NOT_FOUND) {
                    return 0;
                }
                throw new PersistenceException(code + ": " + body);
            }

            JSONArray results = new JSONArray(body);

            return results.getJSONArray(0).getLong(0);
        } catch (Exception e) {
            throw new PersistenceException(e);
        } catch (Throwable t) {
            throw new PersistenceException(t.getMessage());
        }
    } finally {
        endCall("count");
    }
}

From source file:org.dasein.persist.riak.RiakCache.java

@Override
public T create(Transaction xaction, Map<String, Object> state) throws PersistenceException {
    if (std.isTraceEnabled()) {
        std.trace("ENTER: " + RiakCache.class.getName() + ".create(" + xaction + "," + state + ")");
    }/*from   ww  w  .j a v a2  s  .co  m*/
    try {
        if (wire.isDebugEnabled()) {
            startCall("create");
        }
        try {
            StringBuilder url = new StringBuilder();
            String key = getPrimaryKeyField();
            Object keyValue = state.get(key);

            url.append(getEndpoint());
            url.append("buckets/");
            url.append(getBucket());
            url.append("/keys/");
            url.append(keyValue);

            HttpClient client = getClient();
            PostMethod post = new PostMethod(url.toString());
            int code;

            try {
                String json = toDataStoreJSONFromCurrentState(state);

                for (Key secondaryKey : getSecondaryKeys()) {
                    if (secondaryKey.getFields().length > 1) {
                        int len = secondaryKey.getFields().length;

                        StringBuilder n = new StringBuilder();
                        StringBuilder v = new StringBuilder();

                        for (int i = 0; i < len; i++) {
                            Object ob = toJSONValue(state.get(secondaryKey.getFields()[i]));

                            if (ob == null) {
                                v.append("=*=");
                            } else {
                                v.append(ob.toString());
                            }
                            n.append(secondaryKey.getFields()[i].toLowerCase());
                            if (i < len - 1) {
                                n.append("-");
                                v.append("\n");
                            }
                        }
                        post.addRequestHeader("x-riak-index-" + n.toString() + "_bin",
                                Base64.encodeBase64String(v.toString().getBytes("utf-8")));
                    }
                    Object ob = toJSONValue(state.get(secondaryKey.getFields()[0]));

                    if (ob != null) {
                        if (ob instanceof Integer || ob instanceof Long) {
                            post.addRequestHeader("x-riak-index-" + secondaryKey.getFields()[0] + "_int",
                                    ob.toString().trim());
                        } else if (ob.getClass().isArray()) {
                            Object[] items = (Object[]) ob;

                            for (Object item : items) {
                                if (item != null) {
                                    boolean binary = true;

                                    if (Number.class.isAssignableFrom(item.getClass())) {
                                        binary = false;
                                    } else if (item.getClass().equals(long.class)
                                            || item.getClass().equals(int.class)
                                            || item.getClass().equals(boolean.class)
                                            || item.getClass().equals(byte.class)) {
                                        binary = false;
                                    }
                                    if (binary) {
                                        try {
                                            String encoded = Base64
                                                    .encodeBase64String(item.toString().getBytes("utf-8"));

                                            post.addRequestHeader("x-riak-index-"
                                                    + secondaryKey.getFields()[0].toLowerCase() + "_bin",
                                                    encoded.trim());
                                        } catch (UnsupportedEncodingException e) {
                                            std.error("No such encoding UTF-8: " + e.getMessage(), e);
                                            throw new PersistenceException(e);
                                        }
                                    } else {
                                        post.addRequestHeader("x-riak-index-"
                                                + secondaryKey.getFields()[0].toLowerCase() + "_int",
                                                item.toString().trim());
                                    }
                                }
                            }
                        } else {
                            try {
                                String encoded = Base64.encodeBase64String(ob.toString().getBytes("utf-8"));

                                post.addRequestHeader(
                                        "x-riak-index-" + secondaryKey.getFields()[0].toLowerCase() + "_bin",
                                        encoded.trim());
                            } catch (UnsupportedEncodingException e) {
                                std.error("No such encoding UTF-8: " + e.getMessage(), e);
                                throw new PersistenceException(e);
                            }
                        }
                        Class<? extends CachedItem> link = secondaryKey.getIdentifies();

                        if (secondaryKey.getFields().length < 2 && link != null) {
                            try {
                                PersistentCache<? extends CachedItem> cache = PersistentCache.getCache(link);

                                if (cache != null && (cache instanceof RiakCache)) {
                                    RiakCache<? extends CachedItem> c = (RiakCache<? extends CachedItem>) cache;
                                    String bucket = c.getBucket();

                                    post.addRequestHeader("Link",
                                            "</buckets/" + bucket + "/keys/" + ob.toString() + ">; riaktag=\""
                                                    + secondaryKey.getFields()[0] + "\"");
                                }
                            } catch (Throwable t) {
                                std.warn("Unable to determine relationship status for "
                                        + secondaryKey.getFields()[0] + ": " + t.getMessage());
                            }
                        }
                    }
                }
                post.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
                if (wire.isDebugEnabled()) {
                    try {
                        wire.debug(post.getName() + " " + url.toString());
                        wire.debug("");
                        for (Header h : post.getRequestHeaders()) {
                            wire.debug(h.getName() + ": " + h.getValue());
                        }
                        wire.debug("Content-length: " + post.getRequestEntity().getContentLength());
                        wire.debug("Content-type: " + post.getRequestEntity().getContentType());
                        wire.debug("");
                        wire.debug(((StringRequestEntity) post.getRequestEntity()).getContent());
                        wire.debug("");
                    } catch (Throwable ignore) {
                        // ignore
                    }
                }
                code = client.executeMethod(post);
            } catch (HttpException e) {
                std.error("HTTP exception during POST: " + e.getMessage());
                throw new PersistenceException("HttpException during POST: " + e.getMessage());
            } catch (IOException e) {
                std.error("I/O exception during POST: " + e.getMessage());
                throw new PersistenceException("I/O exception during POST: " + e.getMessage());
            }
            try {
                String body = post.getResponseBodyAsString();

                try {
                    if (wire.isDebugEnabled()) {
                        wire.debug("----------------------------------------");
                        wire.debug("");
                        wire.debug(post.getStatusLine().getStatusCode() + " "
                                + post.getStatusLine().getReasonPhrase());
                        wire.debug("");
                        if (body != null) {
                            wire.debug(body);
                            wire.debug("");
                        }
                    }
                } catch (Throwable ignore) {
                    // ignore
                }
                if (code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_NOT_FOUND) {
                    std.warn("Failed attempt to create Riak object (" + code + "): " + body);
                    throw new PersistenceException(code + ": " + body);
                }
                return get(keyValue);
            } catch (IOException e) {
                std.error("Error talking to Riak server: " + e.getMessage());
                throw new PersistenceException(e);
            }
        } finally {
            endCall("create");
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("EXIT: " + RiakCache.class.getName() + ".create()");
        }
    }
}