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:smartrics.rest.test.fitnesse.fixture.ResourcesServlet.java

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    LOG.debug("Resource DELETE REQUEST ========= " + req.toString());
    String uri = sanitise(req.getRequestURI());
    String type = getType(uri);/*from w  w  w. j  a va 2  s .com*/
    echoHeader(req, resp);
    String id = getId(uri);
    Resource resource = resources.get(type, id);
    if (resource != null) {
        // resource.setDeleted(true);
        resources.remove(type, id);
        resp.getOutputStream().write("".getBytes());
        resp.setStatus(HttpServletResponse.SC_OK);
    } else {
        notFound(resp);
    }
    resp.getOutputStream().write("".getBytes());
    resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    LOG.debug("Resource DELETE RESPONSE ========= " + req.toString());
}

From source file:org.eclipse.dirigible.runtime.registry.RegistryServlet.java

@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    String repositoryPath = null;
    final String requestPath = request.getPathInfo();
    boolean deep = false;
    if (requestPath == null) {
        deep = true;//w w  w  .j  av a  2  s .  co m
    }
    final OutputStream out = response.getOutputStream();
    try {
        repositoryPath = extractRepositoryPath(request);
        final IEntity entity = getEntity(repositoryPath, request);
        byte[] data;
        if (entity != null) {
            if (entity instanceof IResource) {
                data = buildResourceData(entity, request, response);
            } else if (entity instanceof ICollection) {
                String collectionPath = request.getRequestURI().toString();
                String acceptHeader = request.getHeader(ACCEPT_HEADER);
                if ((acceptHeader != null) && acceptHeader.contains(JSON)) {
                    if (!collectionPath.endsWith(IRepository.SEPARATOR)) {
                        collectionPath += IRepository.SEPARATOR;
                    }
                    data = buildCollectionData(deep, entity, collectionPath);
                } else {
                    // welcome file and tabris.js support
                    IResource index = ((ICollection) entity).getResource(INDEX_HTML);
                    IResource tabrisJs = ((ICollection) entity).getResource(TABRIS_JS);
                    IResource tabrisJsMin = ((ICollection) entity).getResource(TABRIS_JS_MIN);

                    if (index.exists() && (collectionPath.endsWith(IRepository.SEPARATOR))) {
                        data = buildResourceData(index, request, response);
                    } else if ((tabrisJs.exists() || tabrisJsMin.exists())
                            && collectionPath.contains(NODE_MODULES_TABRIS)) {
                        data = buildResourceData(tabrisJs.exists() ? tabrisJs : tabrisJsMin, request, response);
                    } else {
                        // listing of collections is forbidden
                        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                                LISTING_OF_FOLDERS_IS_FORBIDDEN);
                        return;
                    }
                }
            } else {
                exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                        LISTING_OF_FOLDERS_IS_FORBIDDEN);
                return;
            }
        } else {
            if (requestPath != null) {
                exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NOT_FOUND,
                        String.format("Resource at [%s] does not exist", requestPath));
                return;
            }
            // artifact root folder doesn't exist at the public registry - no published artifacts at all
            sendData(out, new byte[] {});
            return;
        }

        if (entity instanceof IResource) {
            final IResource resource = (IResource) entity;
            String mimeType = null;
            String extension = ContentTypeHelper.getExtension(resource.getName());
            if ((mimeType = ContentTypeHelper.getContentType(extension)) != null) {
                response.setContentType(mimeType);
            } else {
                response.setContentType(resource.getContentType());
            }

            // encoding
            String acceptLang = request.getHeader("Accept-Language");
            String contentLang = acceptLang;
            if ((acceptLang != null) && (acceptLang.indexOf(",") > 0)) {
                contentLang = acceptLang.substring(0, acceptLang.indexOf(","));
                if (contentLang.indexOf("-") > 0) {
                    contentLang = contentLang.substring(0, contentLang.indexOf("-"));
                }
            }

            if (contentLang != null) {
                response.setHeader("Content-Language", contentLang);
            }
        }
        sendData(out, data);
        setContentLengthHeader(entity, data.length, request, response);
    } catch (final IllegalArgumentException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } catch (final MissingResourceException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NO_CONTENT, ex.getMessage());
    } catch (final RuntimeException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ex.getMessage());
    } finally {
        out.flush();
        out.close();
    }
}

From source file:org.opencastproject.episode.endpoint.AbstractEpisodeServiceRestEndpoint.java

@DELETE
@Path("delete/{id}")
@RestQuery(name = "remove", description = "Remove an episode from the archive.", pathParameters = {
        @RestParameter(name = "id", isRequired = true, type = RestParameter.Type.STRING, description = "The media package ID to remove from the archive.") }, reponses = {
                @RestResponse(description = "The mediapackage was removed, no content to return.", responseCode = HttpServletResponse.SC_NO_CONTENT),
                @RestResponse(description = "There has been an internal error and the mediapackage could not be deleted", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "No content is returned.")
public Response delete(@PathParam("id") final String mediaPackageId) {
    return handleException(new Function0.X<Response>() {
        @Override/* w  ww.j  a va 2 s .  c o m*/
        public Response xapply() throws NotFoundException {
            if (mediaPackageId != null && getEpisodeService().delete(mediaPackageId))
                return noContent();
            else
                return notFound();
        }
    });
}

From source file:de.thm.arsnova.controller.SessionController.java

@RequestMapping(value = "/publicpool", method = RequestMethod.GET)
public List<SessionInfo> getPublicPoolSessions(final HttpServletResponse response) {
    List<SessionInfo> sessions = sessionService.getPublicPoolSessionsInfo();

    if (sessions == null || sessions.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return null;
    }/*from w w w .ja v a 2s . co  m*/

    return sessions;
}

From source file:org.wiredwidgets.cow.server.web.TasksController.java

/**
 * Assign a task to a user, or return a task to unassigned status. A task
 * can only be assigned if is currently in an unassigned state, otherwise an
 * error will result. Note: the UI client should be prepared to gracefully
 * handle a race condition, as two users may try to take the same task at
 * nearly the same time: in this case, one will succeed and the other will
 * receive an error response. Response: http 204 or an error code.
 *
 * @param id the ID of the task//from  w  w  w . j  a  va2 s  . c  o m
 * @param assignee the person taking the task. Use a blank value
 * (?assignee=) to return the task to unassigned status
 * @param response
 */
@RequestMapping(value = "/active/{id}", method = RequestMethod.POST, params = "assignee")
public void takeTask(@PathVariable("id") String id, @RequestParam("assignee") String assignee,
        HttpServletResponse response) {
    // a request with a blank query string, e.g. ?assignee=, results in an empty string value
    if (assignee.equals("")) {
        taskService.removeTaskAssignment(Long.valueOf(id));
    } else {
        taskService.takeTask(Long.valueOf(id), assignee);
    }
    response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204

    //Task t = taskService.getTask(id);
    //amqpNotifier.amqpTaskPublish(t, "process", "TaskTaken", id);*/
}

From source file:org.opencastproject.episode.endpoint.EpisodeRestService.java

@POST
@Path("unlock/{id}")
@RestQuery(name = "unlock", description = "Flag a mediapackage as unlocked.", pathParameters = {
        @RestParameter(name = "id", isRequired = true, type = RestParameter.Type.STRING, description = "The media package to unlock.") }, reponses = {
                @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "The mediapackage was unlocked, no content to return."),
                @RestResponse(responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR, description = "There has been an internal error and the mediapackage could not be locked") }, returnDescription = "No content is returned.")
public Response unlock(@PathParam("id") String mediaPackageId) {
    try {//from   w w w .  ja  v a 2 s  . c  o  m
        if (mediaPackageId != null && episodeService.lock(mediaPackageId, false))
            return Response.noContent().build();
        else
            throw new NotFoundException();
    } catch (Exception e) {
        throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
    }
}

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

/**
 * Put a content file and check that onContentUpdate fired
 * <p>/* w  w  w .  j  a va  2  s . co m*/
 * Lock the file
 * <p>
 * Put the contents
 * <p>
 * Unlock the node
 */
@Test
public void testUploadNewContentFiresContentUpdatePolicies() throws Exception {
    flag = false;
    counter = 0;
    policyComponent.bindClassBehaviour(OnContentUpdatePolicy.QNAME, ContentModel.TYPE_CONTENT,
            new JavaBehaviour(this, "doOnContentUpdate"));

    String fileName = "file-" + GUID.generate();
    NodeRef fileNoderef = null;

    try {
        executeMethod(WebDAV.METHOD_LOCK, fileName, davLockInfoFile, null);

        ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE,
                "PATH:\"/app:company_home//cm:" + fileName + "\"");
        fileNoderef = resultSet.getNodeRef(0);
        resultSet.close();

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

    txn.commit();
    txn = transactionService.getUserTransaction();
    txn.begin();

    // Construct IF HEADER
    String lockToken = fileNoderef.getId() + WebDAV.LOCK_TOKEN_SEPERATOR
            + AuthenticationUtil.getAdminUserName();
    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, fileName, testDataFile, headers);

        assertTrue("File does not exist.", nodeService.exists(fileNoderef));
        assertEquals("Filename is not correct", fileName,
                nodeService.getProperty(fileNoderef, 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(fileNoderef, ContentModel.ASPECT_NO_CONTENT));
        InputStream updatedFileIS = fileFolderService.getReader(fileNoderef).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()));
    }

    txn.commit();
    txn = transactionService.getUserTransaction();
    txn.begin();

    headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_LOCK_TOKEN, "<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">");
    try {
        executeMethod(WebDAV.METHOD_UNLOCK, fileName, 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(fileNoderef, ContentModel.ASPECT_NO_CONTENT));
        assertEquals("File should be unlocked", LockStatus.NO_LOCK, lockService.getLockStatus(fileNoderef));
    } catch (Exception e) {
        fail("Failed to unlock a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }

    assertTrue("onContentUpdate policies were not triggered", flag);
    assertEquals("onContentUpdate policies should be triggered only once", counter, 1);

    if (fileNoderef != null) {
        nodeService.deleteNode(fileNoderef);
    }
}

From source file:org.ednovo.gooru.controllers.v2.api.PartyRestV2Controller.java

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_PARTY_CUSTOM_FIELD_DELETE })
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}/custom-field")
public void deletePartyCustomField(@RequestBody String data, @PathVariable(value = ID) String partyId,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = (User) request.getAttribute(Constants.USER);
    getPartyservice().deleteCustomField(partyId, buildPartyCustomFieldFromInputParameters(data), user);
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:org.opencastproject.archive.base.endpoint.ArchiveRestEndpointBase.java

@POST
@Path("apply/{wfDefId}")
@RestQuery(name = "apply", description = "Apply a workflow to a list of media packages.", pathParameters = {
        @RestParameter(name = "wfDefId", type = RestParameter.Type.STRING, description = "The ID of the workflow to apply", isRequired = true) }, restParameters = {
                @RestParameter(name = "mediaPackageIds", type = RestParameter.Type.STRING, description = "A list of media package ids.", isRequired = true) }, reponses = {
                        @RestResponse(description = "The workflows have been started.", responseCode = HttpServletResponse.SC_NO_CONTENT) }, returnDescription = "No content is returned.")
public Response applyWorkflow(@PathParam("wfDefId") final String wfId,
        @FormParam("mediaPackageIds") final List<String> mpIds, @Context final HttpServletRequest req) {
    return handleException(new Function0.X<Response>() {
        @Override//from   ww w.  j av  a2  s .  c om
        public Response xapply() throws Exception {
            final Map<String, String[]> params = (Map<String, String[]>) req.getParameterMap();
            // filter and reduce String[] to String
            final Map<String, String> wfp = mlist(params.entrySet().iterator()).foldl(
                    Collections.<String, String>map(),
                    new Function2<Map<String, String>, Map.Entry<String, String[]>, Map<String, String>>() {
                        @Override
                        public Map<String, String> apply(Map<String, String> wfConf,
                                Map.Entry<String, String[]> param) {
                            final String key = param.getKey();
                            if (!"mediaPackageIds".equalsIgnoreCase(key))
                                wfConf.put(key, param.getValue()[0]);
                            return wfConf;
                        }
                    });
            final WorkflowDefinition wfd = getWorkflowService().getWorkflowDefinitionById(wfId);
            getArchive().applyWorkflow(workflow(wfd, wfp), uriRewriter, mpIds);
            return Response.noContent().build();
        }
    });
}

From source file:org.dasein.cloud.nimbula.NimbulaMethod.java

private void authenticate() throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + NimbulaMethod.class.getName() + ".authenticate()");
    }//from w  w  w . j  a v a2s.c o  m
    try {
        if (authCookie != null) {
            return;
        }
        String uri = cloud.getURL("authenticate") + "/";

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [POST (" + (new Date()) + ")] -> " + uri
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            ProviderContext ctx = cloud.getContext();

            if (ctx == null) {
                throw new CloudException("Unable to authenticate without a context");
            }
            HttpClient client = getClient(ctx, uri.startsWith("https"));
            HttpPost post = new HttpPost(uri);
            HashMap<String, Object> request = new HashMap<String, Object>();

            try {
                request.put("user",
                        "/" + ctx.getAccountNumber() + "/" + new String(ctx.getAccessPublic(), "utf-8"));
                request.put("password", new String(ctx.getAccessPrivate(), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                throw new InternalException(e);
            }
            post.addHeader("Accept", "application/nimbula-v2+json");

            try {
                //noinspection deprecation
                post.setEntity(new StringEntity((new JSONObject(request)).toString(),
                        "application/nimbula-v2+json", "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new InternalException(e);
            }
            if (wire.isDebugEnabled()) {
                wire.debug(post.getRequestLine().toString());
                for (Header header : post.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");

                try {
                    wire.debug(EntityUtils.toString(post.getEntity()));
                } catch (IOException ignore) {
                }

                wire.debug("");
            }
            HttpResponse response;

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

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

            if (code != HttpServletResponse.SC_NO_CONTENT) {
                HttpEntity entity = response.getEntity();
                String data = "";

                if (entity != null) {
                    try {
                        data = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new CloudException(e);
                    }
                }
                if (wire.isDebugEnabled()) {
                    wire.debug(data);
                    wire.debug("");
                }
            }
            checkResponse(response, code);
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [POST (" + (new Date()) + ")] -> " + uri
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + NimbulaMethod.class.getName() + ".authenticate()");
        }
    }
}