Example usage for org.apache.commons.httpclient HttpStatus SC_NO_CONTENT

List of usage examples for org.apache.commons.httpclient HttpStatus SC_NO_CONTENT

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_NO_CONTENT.

Prototype

int SC_NO_CONTENT

To view the source code for org.apache.commons.httpclient HttpStatus SC_NO_CONTENT.

Click Source Link

Document

<tt>204 No Content</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.HopsworksRMAppSecurityActions.java

public HopsworksRMAppSecurityActions() throws MalformedURLException, GeneralSecurityException {
    ACCEPTABLE_HTTP_RESPONSES.add(HttpStatus.SC_OK);
    ACCEPTABLE_HTTP_RESPONSES.add(HttpStatus.SC_NO_CONTENT);
    authHeader = new AtomicReference<>();
    GsonBuilder parserBuilder = new GsonBuilder();
    parserBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
    parserBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    jsonParser = parserBuilder.create();

    tokenRenewer = Executors.newSingleThreadExecutor(
            new ThreadFactoryBuilder().setNameFormat("JWT renewer thread").setDaemon(true).build());
}

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 {//from w w  w.j  a v a2 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.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 v  a2 s.  co  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.webdav.lib.methods.UnlockMethod.java

protected void processResponseBody(HttpState state, HttpConnection conn) {
    if ((getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) && (state instanceof WebdavState)) {
        ((WebdavState) state).removeLock(getPath(), lockToken);
    }/*from  ww w  .  ja  v a  2  s .c  om*/
}

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

private void deleteItem(ArtifactoryResponse response, RepoPath repoPath) throws IOException {
    StatusHolder statusHolder = repoService.undeploy(repoPath);
    if (statusHolder.isError()) {
        response.sendError(statusHolder);
    } else {//from   ww  w. ja  va 2 s . c o  m
        response.setStatus(HttpStatus.SC_NO_CONTENT);
    }
}

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 av  a2 s .  c om
        response.sendError(HttpStatus.SC_NOT_FOUND, "Failed to remove properties from " + itemRepoPath, log);
    }
}

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   w w  w. j ava  2 s  .  c  o 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()");
        }
    }
}

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

@Override
public void remove(Transaction xaction, T item) throws PersistenceException {
    startCall("remove");
    try {//from   w ww . j a  v  a2s  . com
        StringBuilder url = new StringBuilder();

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

        HttpClient client = getClient();
        DeleteMethod delete = new DeleteMethod(url.toString());
        int code;

        try {
            if (wire.isDebugEnabled()) {
                try {
                    wire.debug(delete.getName() + " " + url.toString());
                    wire.debug("");
                    for (Header h : delete.getRequestHeaders()) {
                        wire.debug(h.getName() + ": " + h.getValue());
                    }
                    wire.debug("");
                } catch (Throwable ignore) {
                    // ignore
                }
            }
            code = client.executeMethod(delete);
        } catch (HttpException e) {
            throw new PersistenceException("HttpException during GET: " + e.getMessage());
        } catch (IOException e) {
            throw new PersistenceException("IOException during GET: " + e.getMessage());
        }
        try {
            String body = delete.getResponseBodyAsString();

            if (wire.isDebugEnabled()) {
                try {
                    wire.debug("----------------------------------------");
                    wire.debug("");
                    wire.debug(delete.getStatusLine().getStatusCode() + " "
                            + delete.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) {
                throw new PersistenceException(code + ": " + body);
            }
            getCache().release(item);
        } catch (IOException e) {
            throw new PersistenceException(e);
        }
    } finally {
        endCall("remove");
    }
}

From source file:org.fao.geonet.doi.client.DoiClient.java

private String retrieve(String url, String entity) throws DoiClientException {

    ClientHttpResponse httpResponse = null;
    HttpGet getMethod = null;//from w w w . java2 s  .c  o  m

    try {
        Log.debug(LOGGER_NAME, "   -- URL: " + url);

        getMethod = new HttpGet(url);

        httpResponse = requestFactory.execute(getMethod, new UsernamePasswordCredentials(username, password),
                AuthScope.ANY);
        int status = httpResponse.getRawStatusCode();

        Log.debug(LOGGER_NAME, "   -- Request status code: " + status);

        if (status == HttpStatus.SC_OK) {
            return CharStreams.toString(new InputStreamReader(httpResponse.getBody()));
        } else if (status == HttpStatus.SC_NO_CONTENT) {
            return null; // Not found
        } else if (status == HttpStatus.SC_NOT_FOUND) {
            return null; // Not found
        } else {
            Log.info(LOGGER_NAME, "Retrieve DOI metadata end -- Error: " + httpResponse.getStatusText());

            throw new DoiClientException(httpResponse.getStatusText()
                    + CharStreams.toString(new InputStreamReader(httpResponse.getBody())));
        }

    } catch (Exception ex) {
        Log.error(LOGGER_NAME, "   -- Error (exception): " + ex.getMessage());
        throw new DoiClientException(ex.getMessage());

    } finally {
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
        // Release the connection.
        IOUtils.closeQuietly(httpResponse);
    }
}

From source file:org.infoscoop.request.filter.ProxyFilterContainer.java

public final int invoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception {
    int preStatus = prepareInvoke(client, method, request);
    switch (preStatus) {
    case 0://www  .  ja v  a2s  .  co m
        break;
    case EXECUTE_POST_STATUS:
        doFilterChain(request, request.getResponseBody());
    default:
        return preStatus;
    }
    // copy headers sent target server
    List ignoreHeaderNames = request.getIgnoreHeaders();
    List allowedHeaderNames = request.getAllowedHeaders();
    boolean allowAllHeader = false;

    Proxy proxy = request.getProxy();
    if (proxy != null) {
        allowAllHeader = proxy.isAllowAllHeader();
        if (!allowAllHeader)
            allowedHeaderNames.addAll(proxy.getAllowedHeaders());
    }

    AuthenticatorUtil.doAuthentication(client, method, request);

    StringBuffer headersSb = new StringBuffer();
    for (String name : request.getRequestHeaders().keySet()) {

        String value = request.getRequestHeader(name);
        String lowname = name.toLowerCase();

        if (!allowAllHeader && !allowedHeaderNames.contains(lowname))
            continue;

        if (ignoreHeaderNames.contains(lowname))
            continue;

        if ("cookie".equalsIgnoreCase(name)) {
            if (proxy.getSendingCookies() != null) {
                value = RequestUtil.removeCookieParam(value, proxy.getSendingCookies());
            }
        }

        if ("if-modified-since".equalsIgnoreCase(name) && "Thu, 01 Jun 1970 00:00:00 GMT".equals(value))
            continue;

        method.addRequestHeader(new Header(name, value));
        headersSb.append(name + "=" + value + ",  ");
    }

    int cacheStatus = getCache(client, method, request);
    if (cacheStatus != 0)
        return cacheStatus;

    if (log.isInfoEnabled())
        log.info("RequestHeader: " + headersSb);

    // execute http method and process redirect
    method.setFollowRedirects(false);

    client.executeMethod(method);

    int statusCode = method.getStatusCode();

    for (int i = 0; statusCode == HttpStatus.SC_MOVED_TEMPORARILY
            || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_SEE_OTHER
            || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT; i++) {

        // connection release
        method.releaseConnection();

        if (i == 5) {
            log.error("The circular redirect is limited by five times.");
            return 500;
        }

        Header location = method.getResponseHeader("Location");
        String redirectUrl = location.getValue();

        // According to 2,068 1.1 rfc http spec, we cannot appoint the relative URL,
        // but microsoft.com gives back the relative URL.
        if (redirectUrl.startsWith("/")) {
            URI baseURI = method.getURI();
            baseURI.setPath(redirectUrl);

            redirectUrl = baseURI.toString();
        }

        //method.setURI(new URI(redirectUrl, false));
        Header[] headers = method.getRequestHeaders();
        method = new GetMethod(redirectUrl);
        for (int j = 0; j < headers.length; j++) {
            String headerName = headers[j].getName();
            if (!headerName.equalsIgnoreCase("content-length") && !headerName.equalsIgnoreCase("authorization"))
                method.setRequestHeader(headers[j]);
        }
        AuthenticatorUtil.doAuthentication(client, method, request);
        method.setRequestHeader("authorization", request.getRequestHeader("Authorization"));
        method.setFollowRedirects(false);
        client.executeMethod(method);
        statusCode = method.getStatusCode();
        request.setRedirectURL(redirectUrl);

        if (log.isInfoEnabled())
            log.info("Redirect " + request.getTargetURL() + " to " + location + ".");
    }

    // copy response headers to proxyReqeust
    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        request.putResponseHeader(headers[i].getName(), headers[i].getValue());
    }

    if (log.isInfoEnabled())
        log.info("Original Status:" + statusCode);

    // check response code
    if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        log.error("Proxy Authentication Required. Confirm ajax proxy setting.");
        throw new Exception(
                "Http Status 407, Proxy Authentication Required. Please contuct System Administrator.");
    }
    if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_RESET_CONTENT) {
        return statusCode;
    } else if (statusCode < 200 || statusCode >= 300) {
        request.setResponseBody(method.getResponseBodyAsStream());
        return statusCode;
    }

    // process response body
    InputStream responseStream = null;
    if (statusCode != HttpStatus.SC_NO_CONTENT) {
        if (request.allowUserPublicCache()) {
            byte[] responseBody = method.getResponseBody();

            Map<String, List<String>> responseHeaders = request.getResponseHeaders();
            if (request.getRedirectURL() != null)
                responseHeaders.put("X-IS-REDIRECTED-FROM",
                        Arrays.asList(new String[] { request.getRedirectURL() }));
            if (method instanceof GetMethod) {
                putCache(request.getOriginalURL(), new ByteArrayInputStream(responseBody), responseHeaders);
            }

            responseStream = new ByteArrayInputStream(responseBody);
        } else {
            responseStream = method.getResponseBodyAsStream();
        }
    }
    doFilterChain(request, responseStream);

    return statusCode != HttpStatus.SC_NO_CONTENT ? method.getStatusCode() : 200;
}