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:com.google.ratel.util.RatelUtils.java

public static void writeContent(JsonService jsonService, RatelHttpServletResponse response, Object content,
        String contentType) {/*from  w  w w .  ja v a  2  s  . com*/

    if (content instanceof String) {
        String str = (String) content;
        writeContent(response, str, contentType);
        return;
    }

    try {
        if (response.getContentType() == null) {
            response.setContentType(contentType);
        }

        if (content == null) {
            if (response.isStatusSettable()) {
                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            }
            return;
        }

        PrintWriter writer = response.getWriter();
        jsonService.toJson(content, writer);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

protected @Nullable String putString(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource, @Nullable String payload) throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".putString(" + authToken + "," + endpoint + ","
                + resource + "," + payload + ")");
    }//from  w w w . j av a 2s.co  m
    if (wire.isDebugEnabled()) {
        wire.debug("---------------------------------------------------------------------------------"
                + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpPut put = new HttpPut(endpoint + resource);

        put.addHeader("Content-Type", "application/json");
        put.addHeader("X-Auth-Token", authToken);

        if (payload != null) {
            put.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
        }
        if (wire.isDebugEnabled()) {
            wire.debug(put.getRequestLine().toString());
            for (Header header : put.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (payload != null) {
                wire.debug(payload);
                wire.debug("");
            }
        }
        HttpResponse response;

        try {
            response = client.execute(put);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);

        if (code != HttpServletResponse.SC_CREATED && code != HttpServletResponse.SC_ACCEPTED
                && code != HttpServletResponse.SC_NO_CONTENT) {
            std.error("putString(): Expected CREATED, ACCEPTED, or NO CONTENT for put request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items = (json == null ? null
                    : RackspaceException.parseException(code, json));

            if (items == null) {
                items = new RackspaceException.ExceptionItems();
                items.code = 404;
                items.type = CloudErrorType.COMMUNICATION;
                items.message = "itemNotFound";
                items.details = "No such object: " + resource;
            }
            std.error("putString(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            if (code == HttpServletResponse.SC_ACCEPTED || code == HttpServletResponse.SC_CREATED) {
                HttpEntity entity = response.getEntity();
                String json = null;

                if (entity != null) {
                    try {
                        json = EntityUtils.toString(entity);

                        if (wire.isDebugEnabled()) {
                            wire.debug(json);
                            wire.debug("");
                        }
                    } catch (IOException e) {
                        throw new CloudException(e);
                    }
                }
                if (json != null && !json.trim().equals("")) {
                    return json;
                }
            }
            return null;
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".putString()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}

From source file:org.webdavaccess.servlet.WebdavServlet.java

/**
 * Process a POST request for the specified resource.
 * //from   w w  w  .  j a v  a2  s .c  om
 * @param req
 *            The servlet request we are processing
 * @param resp
 *            The servlet response we are creating
 * 
 * @exception WebdavException
 *                if an error in the underlying store occurs
 */
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (!readOnly) {
        String path = getRelativePath(req);
        String parentPath = getParentPath(path);
        String lockOwner = "doPut" + System.nanoTime() + req.toString();
        if (fResLocks.lock(path, lockOwner, true, -1)) {
            try {
                if (parentPath != null && fStore.isFolder(parentPath) && !fStore.isFolder(path)) {
                    if (!fStore.objectExists(path)) {
                        fStore.createResource(path);
                        resp.setStatus(HttpServletResponse.SC_CREATED);
                    } else {
                        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
                    }
                    fStore.setResourceContent(path, req.getInputStream(), null, null);
                    resp.setContentLength((int) fStore.getResourceLength(path));
                } else {
                    resp.sendError(WebdavStatus.SC_CONFLICT);
                }
            } catch (AccessDeniedException e) {
                log.error("WebdavServer not authenticated: ", e);
                resp.sendError(WebdavStatus.SC_FORBIDDEN);
            } catch (WebdavException e) {
                log.error("WebdavServer internal error: ", e);
                resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            } finally {
                fResLocks.unlock(path, lockOwner);
            }
        } else {
            log.error("WebdavServer unable to lock resource " + lockOwner);
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
    }

}

From source file:org.opencastproject.adminui.endpoint.EmailEndpoint.java

@POST
@Path("sendtestmail")
@Produces(MediaType.APPLICATION_JSON)//  w  ww.  ja  v a  2s.  co m
@RestQuery(name = "sendtestmail", description = "Sends an test mail with the current email configuration", returnDescription = "The sent message as JSON", restParameters = {
        @RestParameter(name = "to", description = "A semi-colon separated list of recipient addresses", isRequired = true, type = RestParameter.Type.STRING),
        @RestParameter(name = "subject", description = "The message subject", isRequired = true, type = RestParameter.Type.STRING),
        @RestParameter(name = "body", description = "The message body", isRequired = true, type = RestParameter.Type.STRING) }, reponses = {
                @RestResponse(description = "Email has been sent", responseCode = HttpServletResponse.SC_NO_CONTENT) })
public Response sendTestMail(@FormParam("to") String to, @FormParam("subject") String subject,
        @FormParam("body") String bodyString) {
    try {
        User user = securityService.getUser();

        MessageTemplate template = new MessageTemplate("Test Mail", user, subject, bodyString,
                TemplateType.INVITATION, new Date(), nil(Comment.class));
        MessageSignature messageSignature = MessageSignature.messageSignature("Test Signature", user,
                EmailAddress.emailAddress(user.getEmail(), user.getName()), "This is a test mail signature");

        List<EmailAddress> addresses = new ArrayList<EmailAddress>();
        for (String address : StringUtils.split(to, ";")) {
            addresses.add(EmailAddress.emailAddress(address, null));
        }

        String body = template.getBody().concat("\r\n").concat(messageSignature.getSignature());
        final Mail mail = new Mail(messageSignature.getSender(), messageSignature.getReplyTo(), addresses,
                template.getSubject(), body);
        mailService.send(mail);
        return Response.noContent().build();
    } catch (Exception e) {
        logger.error("Could not update the email configuration: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handleBlobRemove(HttpServletResponse response, BlobStore blobStore, String containerName,
        String blobName) throws IOException, S3Exception {
    blobStore.removeBlob(containerName, blobName);
    response.sendError(HttpServletResponse.SC_NO_CONTENT);
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Assert that the http request was successful.
 * /* w w w .  j ava  2s  .  c  o  m*/
 * @param message
 *            The message printed if assertion fails.
 * @param httpRes
 *            The http method.
 */
public static void assertHttpStatusOfMethod(final String message, final HttpResponse httpRes) {
    // Delete Operation delivers Status code 206, HttpResponse doesn't
    // contain the original hhtp method
    if (httpRes.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
        assertHttpStatus(message, HttpServletResponse.SC_OK, httpRes);

    } else if ((httpRes.getStatusLine().getStatusCode() == HttpServletResponse.SC_NO_CONTENT)) {
        assertHttpStatus(message, HttpServletResponse.SC_NO_CONTENT, httpRes);
    }

}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

protected @Nullable String putStream(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource, @Nullable String md5Hash, @Nullable InputStream stream)
        throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".putStream(" + authToken + "," + endpoint + ","
                + resource + "," + md5Hash + ",INPUTSTREAM)");
    }//from   w  ww  . jav a2 s .c  o m
    if (wire.isDebugEnabled()) {
        wire.debug("---------------------------------------------------------------------------------"
                + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpPut put = new HttpPut(endpoint + resource);

        put.addHeader("Content-Type", "application/octet-stream");
        put.addHeader("X-Auth-Token", authToken);
        if (md5Hash != null) {
            put.addHeader("ETag", md5Hash);
        }
        put.setEntity(new InputStreamEntity(stream, -1, ContentType.APPLICATION_OCTET_STREAM));

        if (wire.isDebugEnabled()) {
            wire.debug(put.getRequestLine().toString());
            for (Header header : put.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            wire.debug("--> BINARY DATA <--");
        }
        HttpResponse response;

        try {
            response = client.execute(put);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);

        String responseHash = null;

        for (Header h : response.getAllHeaders()) {
            if (h.getName().equals("ETag")) {
                responseHash = h.getValue();
            }
        }
        if (responseHash != null && md5Hash != null && !responseHash.equals(md5Hash)) {
            throw new CloudException("MD5 hash values do not match, probably data corruption");
        }
        if (code != HttpServletResponse.SC_CREATED && code != HttpServletResponse.SC_ACCEPTED
                && code != HttpServletResponse.SC_NO_CONTENT) {
            std.error("putStream(): Expected CREATED, ACCEPTED, or NO CONTENT for PUT request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items = (json == null ? null
                    : RackspaceException.parseException(code, json));

            if (items == null) {
                items = new RackspaceException.ExceptionItems();
                items.code = 404;
                items.type = CloudErrorType.COMMUNICATION;
                items.message = "itemNotFound";
                items.details = "No such object: " + resource;
            }
            std.error("putStream(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            if (code == HttpServletResponse.SC_ACCEPTED) {
                HttpEntity entity = response.getEntity();
                String json = null;

                if (entity != null) {
                    try {
                        json = EntityUtils.toString(entity);

                        if (wire.isDebugEnabled()) {
                            wire.debug(json);
                            wire.debug("");
                        }
                    } catch (IOException e) {
                        throw new CloudException(e);
                    }
                }
                if (json != null && !json.trim().equals("")) {
                    return json;
                }
            }
            return null;
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + RackspaceCloud.class.getName() + ".putStream()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handlePostBlob(HttpServletRequest request, HttpServletResponse response, InputStream is,
        BlobStore blobStore, String containerName) throws IOException, S3Exception {
    String boundaryHeader = request.getHeader(HttpHeaders.CONTENT_TYPE);
    if (boundaryHeader == null || !boundaryHeader.startsWith("multipart/form-data; boundary=")) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;//  w  w w . j a va 2s .co m
    }
    String boundary = boundaryHeader.substring(boundaryHeader.indexOf('=') + 1);

    String blobName = null;
    String contentType = null;
    String identity = null;
    // TODO: handle policy
    byte[] policy = null;
    String signature = null;
    byte[] payload = null;
    MultipartStream multipartStream = new MultipartStream(is, boundary.getBytes(StandardCharsets.UTF_8), 4096,
            null);
    boolean nextPart = multipartStream.skipPreamble();
    while (nextPart) {
        String header = multipartStream.readHeaders();
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            multipartStream.readBodyData(baos);
            if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"acl\"")) {
                // TODO: acl
            } else if (startsWithIgnoreCase(header,
                    "Content-Disposition: form-data;" + " name=\"AWSAccessKeyId\"")) {
                identity = new String(baos.toByteArray());
            } else if (startsWithIgnoreCase(header,
                    "Content-Disposition: form-data;" + " name=\"Content-Type\"")) {
                contentType = new String(baos.toByteArray());
            } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"file\"")) {
                // TODO: buffers entire payload
                payload = baos.toByteArray();
            } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"key\"")) {
                blobName = new String(baos.toByteArray());
            } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"policy\"")) {
                policy = baos.toByteArray();
            } else if (startsWithIgnoreCase(header,
                    "Content-Disposition: form-data;" + " name=\"signature\"")) {
                signature = new String(baos.toByteArray());
            }
        }
        nextPart = multipartStream.readBoundary();
    }

    if (identity == null || signature == null || blobName == null || policy == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    Map.Entry<String, BlobStore> provider = blobStoreLocator.locateBlobStore(identity, null, null);
    if (provider == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String credential = provider.getKey();

    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    String expectedSignature = BaseEncoding.base64().encode(mac.doFinal(policy));
    if (!signature.equals(expectedSignature)) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    BlobBuilder.PayloadBlobBuilder builder = blobStore.blobBuilder(blobName).payload(payload);
    if (contentType != null) {
        builder.contentType(contentType);
    }
    Blob blob = builder.build();
    blobStore.putBlob(containerName, blob);

    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:org.opencms.webdav.CmsWebdavServlet.java

/**
 * Process a POST request for the specified resource.<p>
 *
 * @param req the servlet request we are processing
 * @param resp the servlet response we are creating
 *
 * @throws IOException if an input/output error occurs
 *///w w w.j  a  v  a2  s .c o  m
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String path = getRelativePath(req);

    // Check if webdav is set to read only
    if (m_readOnly) {

        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0));
        }

        return;
    }

    // Check if resource is locked
    if (isLocked(req)) {

        resp.setStatus(CmsWebdavStatus.SC_LOCKED);

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path));
        }

        return;
    }

    boolean exists = m_session.exists(path);
    boolean result = true;

    // Temp. content file used to support partial PUT
    File contentFile = null;

    CmsWebdavRange range = parseContentRange(req, resp);

    InputStream resourceInputStream = null;

    // Append data specified in ranges to existing content for this
    // resource - create a temp. file on the local filesystem to
    // perform this operation
    // Assume just one range is specified for now
    if (range != null) {
        contentFile = executePartialPut(req, range, path);
        resourceInputStream = new FileInputStream(contentFile);
    } else {
        resourceInputStream = req.getInputStream();
    }

    try {

        // FIXME: Add attributes(from Apache Tomcat)
        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_SAVE_ITEM_0));
        }

        m_session.save(path, resourceInputStream, exists);
    } catch (Exception e) {

        if (LOG.isErrorEnabled()) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_REPOSITORY_ERROR_2, "PUT", path), e);
        }

        result = false;
        resp.setStatus(HttpServletResponse.SC_CONFLICT);
    }

    // Bugzilla 40326: at this point content file should be safe to delete
    // as it's no longer referenced.  Let's not rely on deleteOnExit because
    // it's a memory leak, as noted in this Bugzilla issue.
    if (contentFile != null) {
        try {
            contentFile.delete();
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_DELETE_TEMP_FILE_0), e);
            }
        }
    }

    if (result) {

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_SAVE_SUCCESS_0));
        }

        if (exists) {
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            resp.setStatus(HttpServletResponse.SC_CREATED);
        }
    }
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handleAbortMultipartUpload(HttpServletResponse response, BlobStore blobStore,
        String containerName, String blobName, String uploadId) throws IOException, S3Exception {
    if (Quirks.MULTIPART_REQUIRES_STUB.contains(getBlobStoreType(blobStore))) {
        if (!blobStore.blobExists(containerName, uploadId)) {
            throw new S3Exception(S3ErrorCode.NO_SUCH_UPLOAD);
        }//from w  w w  .jav a2s .com

        blobStore.removeBlob(containerName, uploadId);
    }

    // TODO: how to reconstruct original mpu?
    MultipartUpload mpu = MultipartUpload.create(containerName, blobName, uploadId,
            createFakeBlobMetadata(blobStore), new PutOptions());
    blobStore.abortMultipartUpload(mpu);
    response.sendError(HttpServletResponse.SC_NO_CONTENT);
}