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.wiredwidgets.cow.server.web.ProcessInstancesController.java

/**
 * Delete a process instance, or all instances for a key
 * @param id the process key. Doubly URL encode if it contains "/"
 * @param ext the process instance number, or "*" to delete all for the key
 * @param response//w  w  w  .ja  va2s .  c o  m
 */
@RequestMapping(value = "/active/{id}.{ext}", method = RequestMethod.DELETE)
public void deleteProcessInstance(@PathVariable("id") String id, @PathVariable("ext") String ext,
        HttpServletResponse response) {
    String instanceId = "";
    id = decode(id);
    if (ext.equals("*")) {
        processInstanceService.deleteProcessInstancesByKey(id);
        response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204
    } else {
        instanceId = id + '.' + ext;
        if (processInstanceService.deleteProcessInstance(instanceId)) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404
        }
    }

    /*if (instanceId == ""){
       amqpNotifier.amqpProcessPublish(id, "process", "ProcessDeleted");
    } else {
       amqpNotifier.amqpProcessPublish(instanceId, "process", "ProcessDeleted");
    }*/

}

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

@POST
@Path("lock/{id}")
@RestQuery(name = "lock", description = "Flag a mediapackage as locked.", pathParameters = {
        @RestParameter(name = "id", isRequired = true, type = RestParameter.Type.STRING, description = "The media package to lock.") }, reponses = {
                @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "The mediapackage was locked, 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 lock(@PathParam("id") String mediaPackageId) {
    try {//from w  w  w.  jav a 2  s .  c o m
        if (mediaPackageId != null && episodeService.lock(mediaPackageId, true))
            return Response.noContent().build();
        else
            throw new NotFoundException();
    } catch (Exception e) {
        throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
    }
}

From source file:org.apache.archiva.web.rss.RssFeedServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    String repoId = null;/*  w  w  w .  j  av a  2 s  .c om*/
    String groupId = null;
    String artifactId = null;

    String url = StringUtils.removeEnd(req.getRequestURL().toString(), "/");

    if (StringUtils.countMatches(StringUtils.substringAfter(url, "feeds/"), "/") > 0) {
        artifactId = StringUtils.substringAfterLast(url, "/");
        groupId = StringUtils.substringBeforeLast(StringUtils.substringAfter(url, "feeds/"), "/");
        groupId = StringUtils.replaceChars(groupId, '/', '.');
    } else if (StringUtils.countMatches(StringUtils.substringAfter(url, "feeds/"), "/") == 0) {
        // we receive feeds?babla=ded which is not correct
        if (StringUtils.countMatches(url, "feeds?") > 0) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request url.");
            return;
        }
        repoId = StringUtils.substringAfterLast(url, "/");
    } else {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request url.");
        return;
    }

    RssFeedProcessor processor = null;

    try {
        Map<String, String> map = new HashMap<>();
        SyndFeed feed = null;

        if (isAllowed(req, repoId, groupId, artifactId)) {
            if (repoId != null) {
                // new artifacts in repo feed request
                processor = newArtifactsprocessor;
                map.put(RssFeedProcessor.KEY_REPO_ID, repoId);
            } else if ((groupId != null) && (artifactId != null)) {
                // TODO: this only works for guest - we could pass in the list of repos
                // new versions of artifact feed request
                processor = newVersionsprocessor;
                map.put(RssFeedProcessor.KEY_GROUP_ID, groupId);
                map.put(RssFeedProcessor.KEY_ARTIFACT_ID, artifactId);
            }
        } else {
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED);
            return;
        }

        RepositorySession repositorySession = repositorySessionFactory.createSession();
        try {
            feed = processor.process(map, repositorySession.getRepository());
        } finally {
            repositorySession.close();
        }
        if (feed == null) {
            res.sendError(HttpServletResponse.SC_NO_CONTENT, "No information available.");
            return;
        }

        res.setContentType(MIME_TYPE);

        if (repoId != null) {
            feed.setLink(req.getRequestURL().toString());
        } else if ((groupId != null) && (artifactId != null)) {
            feed.setLink(req.getRequestURL().toString());
        }

        SyndFeedOutput output = new SyndFeedOutput();
        output.output(feed, res.getWriter());
    } catch (UserNotFoundException unfe) {
        log.debug(COULD_NOT_AUTHENTICATE_USER, unfe);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
    } catch (AccountLockedException acce) {
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
    } catch (AuthenticationException authe) {
        log.debug(COULD_NOT_AUTHENTICATE_USER, authe);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
    } catch (FeedException ex) {
        log.debug(COULD_NOT_GENERATE_FEED_ERROR, ex);
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR);
    } catch (MustChangePasswordException e) {
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
    } catch (UnauthorizedException e) {
        log.debug(e.getMessage());
        if (repoId != null) {
            res.setHeader("WWW-Authenticate",
                    "Basic realm=\"Repository Archiva Managed " + repoId + " Repository");
        } else {
            res.setHeader("WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId);
        }

        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED);
    }
}

From source file:com.imaginary.home.cloud.api.call.RelayCall.java

@Override
public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {//from ww  w  .j a v a 2  s .  c o  m
        if (path.length < 2) {
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No PUT on /relay");
        }
        ControllerRelay relay = ControllerRelay.getRelay(path[1]);

        if (relay == null) {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                    "Relay " + path[1] + " not found");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());
        String action;

        if (object.has("action") && !object.isNull("action")) {
            action = object.getString("action");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "An invalid action was specified (or not specified) in the PUT");
        }
        if (action.equalsIgnoreCase("update")) {
            if (userId != null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.USER_NOT_ALLOWED,
                        "This API call may be called only by controller relays");
            }
            update(relay, object, resp);
        } else if (action.equalsIgnoreCase("modify")) {
            if (object.has("relay")) {
                object = object.getJSONObject("relay");
            } else {
                object = null;
            }
            if (object == null) {
                throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PUT,
                        "No location was specified in the PUT");
            }
            String name;

            if (object.has("name") && !object.isNull("name")) {
                name = object.getString("name");
            } else {
                name = relay.getName();
            }
            relay.modify(name);
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "The action " + action + " is not a valid action.");
        }
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in body");
    } catch (PersistenceException e) {
        e.printStackTrace();
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                "Internal database error");
    }
}

From source file:de.logicline.splash.controller.UserController.java

/**
 * loads data of the user and the assoc. salesforce contact
 * //from w  ww.  ja  v  a2  s.  c o m
 * @param userId
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "/user/edit/{userId}", method = RequestMethod.GET)
public @ResponseBody ContactDto getUserInfoByUserId(@PathVariable("userId") String userId,
        HttpServletRequest request, HttpServletResponse response) {

    ContactEntity contactEntity = userService.getContactByUserId(userId);
    if (contactEntity == null) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return null;
    }

    return contactEntity.toDto();
}

From source file:org.forgerock.openidm.filter.AuthFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (router == null) {
        throw new ServletException("Internal services not ready to process requests.");
    }/*w w w. j a va  2 s .c  o m*/

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    AuthData authData = new AuthData();

    try {
        HttpSession session = req.getSession(false);
        String logout = req.getHeader("X-OpenIDM-Logout");
        String headerLogin = req.getHeader(HEADER_USERNAME);
        String basicAuth = req.getHeader("Authorization");
        if (logout != null) {
            if (session != null) {
                session.invalidate();
            }
            res.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return;
            // if we see the certficate port this request is for client auth only
        } else if (allowClientCertOnly(req)) {
            authData = hasClientCert(req);
            logAuth(req, authData.username, authData.userId, authData.roles, Action.authenticate,
                    Status.SUCCESS);
        } else if (session == null && headerLogin != null) {
            authData = authenticateUser(req);
            logAuth(req, authData.username, authData.userId, authData.roles, Action.authenticate,
                    Status.SUCCESS);
            createSession(req, session, authData);
        } else if (session == null && basicAuth != null) {
            authData = doBasicAuth(basicAuth);
            logAuth(req, authData.username, authData.userId, authData.roles, Action.authenticate,
                    Status.SUCCESS);
            createSession(req, session, authData);
        } else if (session != null) {
            authData.username = (String) session.getAttribute(USERNAME_ATTRIBUTE);
            authData.userId = (String) session.getAttribute(USERID_ATTRIBUTE);
            authData.roles = (List<String>) session.getAttribute(ROLES_ATTRIBUTE);
            authData.resource = (String) session.getAttribute(RESOURCE_ATTRIBUTE);
        } else {
            authFailed(req, res, authData.username);
            return;
        }
    } catch (AuthException s) {
        authFailed(req, res, s.getMessage());
        return;
    }
    logger.debug("Found valid session for {} id {} with roles {}",
            new Object[] { authData.username, authData.userId, authData.roles });
    req.setAttribute(USERID_ATTRIBUTE, authData.userId);
    req.setAttribute(ROLES_ATTRIBUTE, authData.roles);
    req.setAttribute(RESOURCE_ATTRIBUTE, authData.resource);
    req.setAttribute(OPENIDM_AUTHINVOKED, "openidmfilter");

    chain.doFilter(new UserWrapper(req, authData.username, authData.userId, authData.roles), res);
}

From source file:org.alfresco.repo.content.http.HttpAlfrescoContentReader.java

private void getInfoImpl() {
    String contentUrl = getContentUrl();
    // Info will be cached
    isInfoCached = true;/*from ww  w. j a  va  2s. c  o m*/
    // Authenticate as the system user for the call
    GetMethod method = null;
    try {
        String ticket = transactionService.getRetryingTransactionHelper().doInTransaction(ticketCallback, false,
                true);
        String url = HttpAlfrescoContentReader.generateURL(baseHttpUrl, contentUrl, ticket, true);

        method = new GetMethod(url);
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpServletResponse.SC_OK) {
            // Get the information values from the request
            String responseSize = method.getResponseHeader("alfresco.dr.size").getValue();
            String responseLastModified = method.getResponseHeader("alfresco.dr.lastModified").getValue();
            String responseMimetype = method.getResponseHeader("alfresco.dr.mimetype").getValue();
            String responseEncoding = method.getResponseHeader("alfresco.dr.encoding").getValue();
            String responseLocale = method.getResponseHeader("alfresco.dr.locale").getValue();
            // Fill in this reader's values
            cachedSize = DefaultTypeConverter.INSTANCE.convert(Long.class, responseSize);
            cachedLastModified = DefaultTypeConverter.INSTANCE.convert(Date.class, responseLastModified)
                    .getTime();
            setMimetype(DefaultTypeConverter.INSTANCE.convert(String.class, responseMimetype));
            setEncoding(DefaultTypeConverter.INSTANCE.convert(String.class, responseEncoding));
            setLocale(DefaultTypeConverter.INSTANCE.convert(Locale.class, responseLocale));
            // It exists
            cachedExists = true;
            // Done
            if (logger.isDebugEnabled()) {
                logger.debug("\n" + "HttpReader content found: \n" + "   Reader: " + this + "\n" + "   Server: "
                        + baseHttpUrl);
            }
        } else {
            // Check the return codes
            if (statusCode == HttpServletResponse.SC_NO_CONTENT) {
                // It doesn't exist, which is not an error.  The defaults are fine.
            } else if (statusCode == HttpServletResponse.SC_FORBIDDEN) {
                // If the authentication fails, then the server is there, but probably not
                // clustered correctly.
                logger.error(I18NUtil.getMessage(ERR_NO_AUTHENTICATION, baseHttpUrl));
                logger.error(I18NUtil.getMessage(ERR_CHECK_CLUSTER));
            } else {
                // What is this?
                logger.error(I18NUtil.getMessage(ERR_UNRECOGNIZED, baseHttpUrl, contentUrl, statusCode));
                logger.error(I18NUtil.getMessage(ERR_CHECK_CLUSTER));
            }
            // Done
            if (logger.isDebugEnabled()) {
                logger.debug("\n" + "HttpReader content not found: \n" + "   Reader: " + this + "\n"
                        + "   Server: " + baseHttpUrl);
            }
        }
    } catch (ConnectException e) {
        logger.error(I18NUtil.getMessage(ERR_NO_CONNECTION, baseHttpUrl));
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Reader exists check failed: " + this, e);
    } finally {
        if (method != null) {
            try {
                method.releaseConnection();
            } catch (Throwable e) {
            }
        }
    }
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_RESOURCE_DELETE })
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void deleteResource(@PathVariable(value = ID) final String resourceId, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    request.setAttribute(PREDICATE, RESOURCE_DELETE_RESOURCE);
    final User user = (User) request.getAttribute(Constants.USER);
    this.resourceService.deleteResource(resourceId, user);
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:com.rsginer.spring.controllers.RestaurantesController.java

@RequestMapping(value = {
        "/restaurantes" }, method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void setRestaurante(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse,
        @RequestBody String jsonEntrada) {
    try {// ww w  .jav  a 2  s  . co  m
        Restaurante restaurante = jsonTransformer.fromJSON(jsonEntrada, Restaurante.class);
        String jsonSalida = jsonTransformer.toJson(restaurante);
        if (restaurante != null && restaurante.getNombre() != null && restaurante.getDireccion() != null
                && restaurante.getDescripcion() != null && restaurante.getPrecio() != null) {
            restaurantesDAO.insert(jsonTransformer.fromJSON(jsonSalida, Restaurante.class));
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        } else {
            httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().println(jsonSalida);

    } catch (BussinessException ex) {
        List<BussinessMessage> bussinessMessages = ex.getBussinessMessages();
        String jsonSalida = jsonTransformer.toJson(bussinessMessages);
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
}

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

@RequestMapping(value = "/publicpool", method = RequestMethod.GET, params = "statusonly=true")
public List<SessionInfo> getMyPublicPoolSessions(final HttpServletResponse response) {
    List<SessionInfo> sessions = sessionService.getMyPublicPoolSessionsInfo();

    if (sessions == null || sessions.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return null;
    }//from   w ww .j av  a  2 s. com

    return sessions;
}