Example usage for javax.servlet.http HttpServletResponse SC_NO_CONTENT

List of usage examples for javax.servlet.http HttpServletResponse SC_NO_CONTENT

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_NO_CONTENT.

Prototype

int SC_NO_CONTENT

To view the source code for javax.servlet.http HttpServletResponse SC_NO_CONTENT.

Click Source Link

Document

Status code (204) indicating that the request succeeded but that there was no new information to return.

Usage

From source file:org.dasein.cloud.ibm.sce.SCEMethod.java

public @Nullable String post(@Nonnull String resource, @Nonnull List<NameValuePair> parameters)
        throws CloudException, InternalException {
    Logger std = SCE.getLogger(SCEMethod.class, "std");
    Logger wire = SCE.getLogger(SCEMethod.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + SCEMethod.class.getName() + ".post(" + resource + ")");
    }/*from www  .j a v  a2  s . c  o  m*/
    if (wire.isDebugEnabled()) {
        wire.debug("POST --------------------------------------------------------> " + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpPost post = new HttpPost(endpoint + resource);

        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        post.addHeader("Accept", "text/xml");

        if (wire.isDebugEnabled()) {
            wire.debug(post.getRequestLine().toString());
            for (Header header : post.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (parameters != null) {
                Iterator<NameValuePair> it = parameters.iterator();
                StringBuilder str = new StringBuilder();

                while (it.hasNext()) {
                    NameValuePair p = it.next();

                    str.append(p.getName()).append("=").append(p.getValue());
                    if (it.hasNext()) {
                        str.append("&");
                    }
                }
                wire.debug(str.toString());
                wire.debug("");
            }
        }
        if (parameters != null) {
            try {
                post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                throw new InternalException(e);
            }
        }
        HttpResponse response;
        StatusLine status;

        try {
            APITrace.trace(provider, resource);
            response = client.execute(post);
            status = response.getStatusLine();
        } catch (IOException e) {
            std.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (std.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
        if (std.isDebugEnabled()) {
            std.debug("post(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            std.error("post(): Expected OK for GET request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();
            String body;

            if (entity == null) {
                throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(),
                        "An error was returned without explanation");
            }
            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(),
                        e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(),
                    body);
        } else if (status.getStatusCode() == HttpServletResponse.SC_NO_CONTENT) {
            return null;
        } else {
            HttpEntity entity = response.getEntity();

            if (entity == null) {
                return null;
            }
            try {
                return EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(),
                        e.getMessage());
            }
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + SCEMethod.class.getName() + ".post()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("POST --------------------------------------------------------> " + endpoint + resource);
        }
    }
}

From source file:org.osaf.cosmo.cmp.CmpServlet.java

private void processMultiUserDelete(HttpServletRequest req, HttpServletResponse resp) {
    if (checkMultiUserDeletePreconditions(req, resp)) {
        Set<String> names = new HashSet<String>();

        for (String name : req.getParameterValues("user")) {
            names.add(name);/*  ww w.  ja  v  a2 s. c o m*/
        }

        try {
            userService.removeUsersByName(names);
        } catch (OverlordDeletionException e) {
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}

From source file:org.alfresco.repo.webdav.PutMethodTest.java

/**
 * Putting a content to a working copy file
 * <p>//from www .  j  av  a  2s .c o  m
 * Create and check out a file by user1
 * <p>
 * Try to put the content to the working copy by user2
 * 
 * See MNT-8614.
 */
@SuppressWarnings("deprecation")
@Test
public void testPutContentToWorkingCopy() throws Exception {
    FileInfo folder = fileFolderService.create(companyHomeNodeRef, "folder-" + GUID.generate(),
            ContentModel.TYPE_FOLDER);
    permissionService.setInheritParentPermissions(folder.getNodeRef(), false);
    permissionService.setPermission(folder.getNodeRef(), USER1_NAME, permissionService.getAllPermission(),
            true);

    AuthenticationUtil.setFullyAuthenticatedUser(USER1_NAME);
    FileInfo testFileInfo = fileFolderService.create(folder.getNodeRef(), "file-" + GUID.generate(),
            ContentModel.TYPE_CONTENT);
    NodeRef workingCopyNodeRef = checkOutCheckInService.checkout(testFileInfo.getNodeRef());
    String workingCopyName = fileFolderService.getFileInfo(workingCopyNodeRef).getName();
    String pathToWC = "/" + folder.getName() + "/" + workingCopyName;
    String pathToOriginal = "/" + folder.getName() + "/" + testFileInfo.getName();

    // Negative test, try to edit the WC without permissions.
    AuthenticationUtil.setFullyAuthenticatedUser(USER2_NAME);
    try {
        lockService.lock(workingCopyNodeRef, LockType.WRITE_LOCK);
    } catch (AccessDeniedException ade) {
        // expected
    }

    try {
        executeMethod(WebDAV.METHOD_LOCK, pathToWC, davLockInfoUser2File, null);

        fail("The LOCK execution should fail with a 401 error");
    } catch (WebDAVServerException wse) {
        // The execution failed and it is expected
        assertTrue(
                "The status code was " + wse.getHttpStatusCode() + ", but should be "
                        + HttpServletResponse.SC_UNAUTHORIZED,
                wse.getHttpStatusCode() == HttpServletResponse.SC_UNAUTHORIZED);
    } catch (Exception e) {
        fail("Unexpected exception occurred: "
                + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }

    // Construct IF HEADER
    String lockToken = workingCopyNodeRef.getId() + WebDAV.LOCK_TOKEN_SEPERATOR + USER2_NAME;
    String lockHeaderValue = "(<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">)";
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_IF, lockHeaderValue);
    try {
        executeMethod(WebDAV.METHOD_PUT, pathToWC, testDataFile, headers);
        fail("The PUT execution should fail with a 423 error");
    } catch (WebDAVServerException wse) {
        // The execution failed and it is expected
        assertTrue(
                "The status code was " + wse.getHttpStatusCode() + ", but should be "
                        + HttpServletResponse.SC_UNAUTHORIZED,
                wse.getHttpStatusCode() == HttpServletResponse.SC_UNAUTHORIZED);
    } catch (Exception e) {
        fail("Unexpected exception occurred: "
                + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }

    // Positive test
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    permissionService.setPermission(folder.getNodeRef(), USER2_NAME, permissionService.getAllPermission(),
            true);

    AuthenticationUtil.setFullyAuthenticatedUser(USER2_NAME);
    try {
        executeMethod(WebDAV.METHOD_LOCK, pathToWC, davLockInfoUser2File, null);

        assertEquals("File should be locked", LockStatus.LOCK_OWNER,
                lockService.getLockStatus(workingCopyNodeRef));
    } catch (Exception e) {
        fail("Failed to lock a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }

    headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_IF, lockHeaderValue);
    try {
        executeMethod(WebDAV.METHOD_PUT, pathToWC, testDataFile, headers);

        assertTrue("File does not exist.", nodeService.exists(workingCopyNodeRef));
        assertEquals("Filename is not correct", workingCopyName,
                nodeService.getProperty(workingCopyNodeRef, ContentModel.PROP_NAME));
        assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is "
                + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus());

        assertTrue("File should have NO_CONTENT aspect",
                nodeService.hasAspect(workingCopyNodeRef, ContentModel.ASPECT_NO_CONTENT));
        InputStream updatedFileIS = fileFolderService.getReader(workingCopyNodeRef).getContentInputStream();
        byte[] updatedFile = IOUtils.toByteArray(updatedFileIS);
        updatedFileIS.close();
        assertTrue("The content has to be equal", ArrayUtils.isEquals(testDataFile, updatedFile));
    } catch (Exception e) {
        fail("Failed to upload a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }

    headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_LOCK_TOKEN, "<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">");
    try {
        executeMethod(WebDAV.METHOD_UNLOCK, pathToWC, null, headers);

        assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is "
                + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus());
        assertFalse("File should not have NO_CONTENT aspect",
                nodeService.hasAspect(workingCopyNodeRef, ContentModel.ASPECT_NO_CONTENT));
        assertEquals("File should be unlocked", LockStatus.NO_LOCK,
                lockService.getLockStatus(workingCopyNodeRef));
    } catch (Exception e) {
        fail("Failed to unlock a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }

    // Negative test try to lock or edit the original file
    AuthenticationUtil.setFullyAuthenticatedUser(USER2_NAME);
    try {
        lockService.lock(testFileInfo.getNodeRef(), LockType.WRITE_LOCK);
    } catch (UnableToAquireLockException uale) {
        // expected
    }

    try {
        executeMethod(WebDAV.METHOD_LOCK, pathToOriginal, davLockInfoUser2File, null);

        fail("The LOCK execution should fail with a 423 error");
    } catch (WebDAVServerException wse) {
        // The execution failed and it is expected
        assertTrue(
                "The status code was " + wse.getHttpStatusCode() + ", but should be " + WebDAV.WEBDAV_SC_LOCKED,
                wse.getHttpStatusCode() == WebDAV.WEBDAV_SC_LOCKED);
    } catch (Exception e) {
        fail("Unexpected exception occurred: "
                + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }

    // Construct IF HEADER
    lockToken = testFileInfo.getNodeRef().getId() + WebDAV.LOCK_TOKEN_SEPERATOR + USER2_NAME;
    lockHeaderValue = "(<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">)";
    headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_IF, lockHeaderValue);
    try {
        executeMethod(WebDAV.METHOD_PUT, pathToOriginal, testDataFile, headers);
        fail("The PUT execution should fail with a 423 error");
    } catch (WebDAVServerException wse) {
        // The execution failed and it is expected
        assertTrue(
                "The status code was " + wse.getHttpStatusCode() + ", but should be " + WebDAV.WEBDAV_SC_LOCKED,
                wse.getHttpStatusCode() == WebDAV.WEBDAV_SC_LOCKED);
    } catch (Exception e) {
        fail("Unexpected exception occurred: "
                + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }

    AuthenticationUtil.setFullyAuthenticatedUser(USER1_NAME);
    checkOutCheckInService.checkin(workingCopyNodeRef, null);

    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    nodeService.deleteNode(folder.getNodeRef());
}

From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java

private LookupResult lookupLAF(HttpServletRequest request, URL targetUrl, String path, String serviceId,
        String subjectPath) {//from   w ww  .  ja va 2s. co  m
    URL fileUrl = null;

    try {
        String baseTargetPath = StringUtils.substringBefore(targetUrl.getPath(), path);
        Matcher lafm = PATTERN_LAF_PATH.matcher(path);
        if (!lafm.matches())
            return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
        String pathLaf = lafm.group(1);
        String remainingPath = lafm.group(2);

        // Try to get resource in folder related to the requested look&feel...
        // If not found, look for the default one (default)
        String[] lafs = new String[] { pathLaf, "default" };
        for (String laf : lafs) {
            fileUrl = getResURL(baseTargetPath + "laf/" + laf + "/" + remainingPath);
            if (fileUrl != null)
                break;
        }
        if (fileUrl == null)
            throw new NotFoundException();

        Resource resFile = getFile(WebTopApp.get(request), fileUrl);
        return new StaticFile(fileUrl.toString(), getMimeType(remainingPath), ClientCaching.YES, resFile);

    } catch (ForbiddenException ex) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    } catch (NotFoundException ex) {
        return new Error(HttpServletResponse.SC_NO_CONTENT, "Not Content");
    } catch (InternalServerException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } catch (ServletException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java

protected String execute(HttpRequestBase httpRequestBase)
        throws JSONWebServiceInvocationException, JSONWebServiceTransportException {

    signRequest(httpRequestBase);//from   w ww  .j  av a  2  s.com

    HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol);

    try {
        if (_closeableHttpAsyncClient == null) {
            afterPropertiesSet();
        }

        Future<HttpResponse> future = null;

        if (!isNull(_login) && !isNull(_password)) {
            HttpClientContext httpClientContext = HttpClientContext.create();

            AuthCache authCache = new BasicAuthCache();

            AuthScheme authScheme = null;

            if (!isNull(_proxyHostName)) {
                authScheme = new BasicScheme(ChallengeState.PROXY);
            } else {
                authScheme = new BasicScheme(ChallengeState.TARGET);
            }

            authCache.put(httpHost, authScheme);

            httpClientContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

            future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, httpClientContext, null);
        } else {
            future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, null);
        }

        HttpResponse httpResponse = future.get();

        StatusLine statusLine = httpResponse.getStatusLine();

        int statusCode = statusLine.getStatusCode();

        if (_logger.isTraceEnabled()) {
            _logger.trace("Server returned status " + statusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        if ((statusCode == HttpServletResponse.SC_NO_CONTENT)
                || (((httpEntity == null) || (httpEntity.getContentLength() == 0))
                        && _isStatus2XX(statusCode))) {

            return null;
        }

        String content = EntityUtils.toString(httpEntity, _CHARSET);

        if ((httpEntity.getContentType() != null) && _isApplicationJSONContentType(httpEntity)) {

            content = updateJSON(content);
        }

        if (_isStatus2XX(statusCode)) {
            return content;
        } else if ((statusCode == HttpServletResponse.SC_BAD_REQUEST)
                || (statusCode == HttpServletResponse.SC_FORBIDDEN)
                || (statusCode == HttpServletResponse.SC_METHOD_NOT_ALLOWED)
                || (statusCode == HttpServletResponse.SC_NOT_ACCEPTABLE)
                || (statusCode == HttpServletResponse.SC_NOT_FOUND)) {

            throw new JSONWebServiceInvocationException(content, statusCode);
        } else if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
            throw new JSONWebServiceTransportException.AuthenticationFailure(
                    "Not authorized to access JSON web service");
        }

        throw new JSONWebServiceTransportException.CommunicationFailure("Server returned status " + statusCode,
                statusCode);
    } catch (ExecutionException ee) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ee);
    } catch (InterruptedException ie) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ie);
    } catch (IOException ioe) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ioe);
    } finally {
        httpRequestBase.releaseConnection();
    }
}

From source file:org.osaf.cosmo.cmp.CmpServlet.java

private void processAccountDelete(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    User user = getLoggedInUser();/*from w ww .j  a v  a  2 s  .  co  m*/
    if (user.isOverlord()) {
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    userService.removeUser(user);
    resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Sets the HTTP status on the response to no content, and returns an empty value, suitable for
 * returning from a @ResponseBody annotated Spring controller method.
 * //from  w ww.j  a va  2 s . com
 * @param response
 * @return
 */
public static Object noContent(HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    return "";
}

From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java

private LookupResult lookupWhatsnew(HttpServletRequest request, URL targetUrl, String path, String serviceId) {
    URL fileUrl = null;/*from  w w w  .  j  av  a  2 s .  c  om*/

    try {
        String resPath = "/" + LangUtils.packageToPath(serviceId) + "/meta/" + path;
        fileUrl = getResURL(resPath);
        if (fileUrl == null)
            throw new NotFoundException();

        Resource resFile = getFile(WebTopApp.get(request), fileUrl);
        return new StaticFile(fileUrl.toString(), getMimeType(path), ClientCaching.YES, resFile);

    } catch (ForbiddenException ex) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    } catch (NotFoundException ex) {
        return new Error(HttpServletResponse.SC_NO_CONTENT, "Not Content");
    } catch (InternalServerException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } catch (ServletException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:com.imaginary.home.controller.CloudService.java

public boolean postState() throws CommunicationException, ControllerException {
    HttpClient client = getClient(endpoint, proxyHost, proxyPort);
    HttpPut method = new HttpPut(endpoint + "/relay/" + serviceId);
    long timestamp = System.currentTimeMillis();

    method.addHeader("Content-Type", "application/json");
    method.addHeader("x-imaginary-version", VERSION);
    method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
    method.addHeader("x-imaginary-api-key", serviceId);

    if (token == null) {
        authenticate();/*w  w w.  java  2  s  .c  om*/
    }
    String stringToSign = "PUT:/relay" + serviceId + ":" + serviceId + ":" + token + ":" + timestamp + ":"
            + VERSION;

    try {
        method.addHeader("x-imaginary-signature", sign(apiKeySecret.getBytes("utf-8"), stringToSign));
    } catch (Exception e) {
        throw new ControllerException(e);
    }
    ArrayList<Map<String, Object>> devices = new ArrayList<Map<String, Object>>();
    HashMap<String, Object> state = new HashMap<String, Object>();

    state.put("action", "update");
    for (ManagedResource resource : HomeController.getInstance().listResources()) {
        HashMap<String, Object> json = new HashMap<String, Object>();

        resource.toMap(json);
        devices.add(json);
    }
    state.put("devices", devices);

    try {
        //noinspection deprecation
        method.setEntity(new StringEntity((new JSONObject(state)).toString(), "application/json", "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new ControllerException(e);
    }
    HttpResponse response;
    StatusLine status;

    try {
        response = client.execute(method);
        status = response.getStatusLine();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommunicationException(e);
    }
    if (status.getStatusCode() != HttpServletResponse.SC_NO_CONTENT) {
        parseError(response); // this will throw an exception
    }
    Header h = response.getFirstHeader("x-imaginary-has-commands");
    String val = (h == null ? "false" : h.getValue());

    return (val != null && val.equalsIgnoreCase("true"));
}