Example usage for javax.servlet.http HttpServletResponse sendError

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

Introduction

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

Prototype

public void sendError(int sc) throws IOException;

Source Link

Document

Sends an error response to the client using the specified status code and clears the buffer.

Usage

From source file:info.magnolia.cms.security.SecurityFilter.java

/**
 * Checks access from Listener / Authenticator / AccessLock.
 * @param req HttpServletRequest as received by the service method
 * @param res HttpServletResponse as received by the service method
 * @return boolean <code>true</code> if access to the resource is allowed
 * @throws IOException can be thrown when the servlet is unable to write to the response stream
 *///from   w w w .  j  av a 2s .c o m
protected boolean isAllowed(HttpServletRequest req, HttpServletResponse res) throws IOException {
    if (Lock.isSystemLocked()) {
        res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return false;
    } else if (Authenticator.isAuthenticated(req)) {
        return true;
    } else if (SecureURI.isUnsecure(Path.getURI(req)))
        return true;
    else if (SecureURI.isProtected(Path.getURI(req))) {
        return authenticate(req, res);
    } else if (!Listener.isAllowed(req)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }
    return true;
}

From source file:ru.mystamps.web.controller.CollectionController.java

@GetMapping(Url.INFO_COLLECTION_PAGE)
public String showInfoBySlug(@PathVariable("slug") String slug, Model model, Locale userLocale,
        HttpServletResponse response) throws IOException {

    if (slug == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }//from   ww w.  j  av  a 2 s.co m

    CollectionInfoDto collection = collectionService.findBySlug(slug);
    if (collection == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    String owner = collection.getOwnerName();
    model.addAttribute("ownerName", owner);

    Integer collectionId = collection.getId();
    String lang = LocaleUtils.getLanguageOrNull(userLocale);
    List<SeriesInfoDto> seriesOfCollection = seriesService.findByCollectionId(collectionId, lang);
    model.addAttribute("seriesOfCollection", seriesOfCollection);

    if (seriesOfCollection.iterator().hasNext()) {
        long categoryCounter = categoryService.countCategoriesOf(collectionId);
        long countryCounter = countryService.countCountriesOf(collectionId);
        long seriesCounter = seriesService.countSeriesOf(collectionId);
        long stampsCounter = seriesService.countStampsOf(collectionId);

        List<Object[]> categoriesStat = categoryService.getStatisticsOf(collectionId, lang);
        List<Object[]> countriesStat = getCountriesStatistics(collectionId, lang);

        model.addAttribute("categoryCounter", categoryCounter);
        model.addAttribute("countryCounter", countryCounter);
        model.addAttribute("seriesCounter", seriesCounter);
        model.addAttribute("stampsCounter", stampsCounter);

        model.addAttribute("statOfCollectionByCategories", categoriesStat);
        model.addAttribute("statOfCollectionByCountries", countriesStat);
    }

    return "collection/info";
}

From source file:com.capstone.giveout.controllers.UsersController.java

@RequestMapping(value = Routes.USERS_IMAGE_PATH, method = RequestMethod.GET)
public @ResponseBody void getImage(@PathVariable("id") long id, @PathVariable("size") String size,
        HttpServletResponse response) throws IOException {
    User user = users.findOne(id);/* w ww .j av  a2  s.co  m*/
    if (user == null) {
        response.sendError(HttpStatus.NOT_FOUND.value());
        return;
    }

    try {
        ImageFileManager.get(USERS_ROOT_PATH).copyImage(user.getId(), size, response.getOutputStream());
    } catch (FileNotFoundException e) {
        response.sendError(HttpStatus.NOT_FOUND.value());
    }
}

From source file:org.shredzone.commons.gravatar.GravatarCacheServlet.java

@Override
protected void doService(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    Matcher m = HASH_PATTERN.matcher(req.getPathInfo());
    if (!m.matches()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//ww  w  .j a v  a  2s .  co m
    }

    String hash = m.group(1);

    GravatarService gs = getWebApplicationContext().getBean("gravatarService", GravatarService.class);
    File gravatarFile = gs.fetchGravatar(hash);

    long modifiedSinceTs = -1;
    try {
        modifiedSinceTs = req.getDateHeader("If-Modified-Since");
    } catch (IllegalArgumentException ex) {
        // As stated in RFC2616 Sec. 14.25, an invalid date will just be ignored.
    }

    if (modifiedSinceTs >= 0 && (modifiedSinceTs / 1000L) == (gravatarFile.lastModified() / 1000L)) {
        // The image has not been modified since last request
        resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    long size = gravatarFile.length();
    if (size > 0 && size <= Integer.MAX_VALUE) {
        // Cast to int is safe
        resp.setContentLength((int) size);
    }

    resp.setContentType("image/png");
    resp.setDateHeader("Date", System.currentTimeMillis());
    resp.setDateHeader("Last-Modified", gravatarFile.lastModified());

    try (InputStream in = new FileInputStream(gravatarFile)) {
        FileCopyUtils.copy(in, resp.getOutputStream());
    }
}

From source file:com.appdynamics.cloudfoundry.appdservicebroker.BrokerApiVersionFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {

    String header = request.getHeader(HEADER);
    if (header == null) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;//from   www . jav a 2 s . c o m
    }

    Integer[] parsed = parse(header);
    Version version = Version.forIntegers(parsed[0], parsed[1]);
    if (!version.satisfies(VALID_VERSIONS)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    filterChain.doFilter(request, response);
}

From source file:com.tasktop.c2c.server.web.proxy.AjpProxy.java

@Override
protected void proxy(String targetUrl, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    Matcher matcher = targetUrlPattern.matcher(targetUrl);
    if (!matcher.matches()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new IllegalStateException();
    }/* ww w.  j av a  2  s  .c  om*/
    String uri = matcher.group(3);
    int query = uri.indexOf('?');
    if (query != -1) {
        uri = uri.substring(0, query);
    }
    final String requestUri = uri;
    request = new HttpServletRequestWrapper(request) {
        public String getRequestURI() {
            return requestUri;
        }
    };

    AjpProtocol ajpProtocol = new AjpProtocol();
    ajpProtocol.setSocketPool(socketPool);
    ajpProtocol.setProxyHost(matcher.group(1));
    String portPart = matcher.group(2);
    ajpProtocol.setProxyPort(portPart == null ? 8009 : Integer.parseInt(portPart));
    ajpProtocol.setHeaderFilter(headerFilter);

    ajpProtocol.forward(request, response);
}

From source file:com.hypersocket.ui.RedirectHandler.java

@Override
public void handleHttpRequest(HttpServletRequest request, HttpServletResponse response,
        HttpResponseProcessor responseProcessor) throws IOException {

    response.setHeader(HttpHeaders.LOCATION, server.resolvePath(server.getUserInterfacePath()));
    response.sendError(HttpStatus.SC_MOVED_TEMPORARILY);
    responseProcessor.sendResponse(request, response, false);

}

From source file:com.skilrock.lms.embedded.roleMgmt.common.PrivsInterceptor.java

/**
 * Handles a rejection by sending a 403 HTTP error
 * /*from  w ww .  j  a v  a2s.  co  m*/
 * @param invocation
 *            The invocation
 * @return The result code
 * @throws Exception
 */
protected String handleRejection(ActionInvocation invocation, HttpServletResponse response) throws Exception {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
    return null;
}

From source file:jp.co.opentone.bsol.framework.web.filter.FeedAuthenticationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    AuthUser u = authenticate(req, res);
    if (u == null) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//  ww w  .j  a  v  a 2  s .  c  o m
    }
    storeAuthenticateUser(req, res, u);
    chain.doFilter(request, response);
}

From source file:net.incrementalism.tooter.ProfileServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    User currentUser = getCurrentUser(request);
    if (currentUser == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/* w ww  . ja va2 s.  c  o  m*/
    }

    if (request.getParameter("toot") != null) {
        String tootText = request.getParameter("tootText");
        if (isBlank(tootText)) {
            request.setAttribute("error", "'Toot' must not be empty.");
        } else {
            toot(currentUser, tootText);
        }
    } else if (request.getParameter("follow") != null) {
        String followUserName = request.getParameter("followUserName");
        if (isBlank(followUserName)) {
            request.setAttribute("error", "'Follow' must not be empty.");
        } else {
            try {
                addFollower(followUserName, currentUser.getUserName());
            } catch (UserNotFoundException e) {
                request.setAttribute("error", "User '" + e.getUserName() + "' does not exist.");
            }
        }
    }
    displayProfile(currentUser, request, response);
}