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, String msg) throws IOException;

Source Link

Document

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

Usage

From source file:com.nec.harvest.security.HarvestLoginUrlAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    if (isPreflight(request)) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (isRestRequest(request)) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    } else {//from  www  .j av  a2  s.c o m
        super.commence(request, response, authException);
    }
}

From source file:eionet.transfer.controller.FileOpsController.java

/**
 * AJAX Upload file for transfer.//from   www  .  j  a  v  a2 s  .c  o m
 */
@RequestMapping(value = "/fileupload", method = RequestMethod.POST, params = "ajaxupload=1")
public void importFileWithAJAX(@RequestParam("file") MultipartFile myFile, @RequestParam("fileTTL") int fileTTL,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (myFile == null || myFile.getOriginalFilename() == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Select a file to upload");
        return;
    }
    if (fileTTL > 90) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid expiration date");
        return;
    }
    String uuidName = storeFile(myFile, fileTTL);
    response.setContentType("text/xml");
    PrintWriter printer = response.getWriter();
    StringBuffer requestUrl = request.getRequestURL();
    String url = requestUrl.substring(0, requestUrl.length() - "/fileupload".length());
    printer.println("<?xml version='1.0'?>");
    printer.println("<package>");
    printer.println("<downloadLink>" + url + "/download/" + uuidName + "</downloadLink>");
    printer.println("<deleteLink>" + url + "/delete/" + uuidName + "</deleteLink>");
    printer.println("</package>");
    printer.flush();
    response.flushBuffer();
}

From source file:com.liusoft.dlog4j.action.ActionExtend.java

/**
 * // w ww .jav a 2s  .com
 * @param mapping
 * @param form
 * @param req
 * @param res
 * @return
 * @throws Exception
 */
protected ActionForward doDefault(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {
    res.sendError(HttpServletResponse.SC_NOT_FOUND, "METHOD NOT FOUND.");
    return null;
}

From source file:ch.ge.ve.protopoc.jwt.JwtAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException {
    // This is invoked when user tries to access a secured REST resource without supplying any credentials
    // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.ajax.VitroAjaxController.java

/**
 * Sub-classes should not override this. Instead, implement doRequest().
 *///from   w  w w  .  j a  va  2s.c  o m
@Override
protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    VitroRequest vreq = new VitroRequest(req);
    if (PolicyHelper.isAuthorizedForActions(vreq, requiredActions(vreq))) {
        doRequest(vreq, resp);
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Not authorized");
    }
}

From source file:org.xwiki.resource.servlet.AbstractServletResourceReferenceHandler.java

/**
 * Sends back the specified status code with the given message in order for the browser to know the resource
 * couldn't be served. This is especially important as we don't want to cache an empty response.
 * //from   w w  w. j a  v a2  s . c  om
 * @param statusCode the response status code to send
 * @param message the error message
 * @param parameters the message parameters
 * @throws ResourceReferenceHandlerException if setting the response status code fails
 */
private void sendError(int statusCode, String message, Object... parameters)
        throws ResourceReferenceHandlerException {
    Response response = this.container.getResponse();
    if (response instanceof ServletResponse) {
        HttpServletResponse httpResponse = ((ServletResponse) response).getHttpServletResponse();
        try {
            httpResponse.sendError(statusCode, String.format(message, parameters));
        } catch (IOException e) {
            throw new ResourceReferenceHandlerException(
                    String.format("Failed to return status code [%s].", statusCode), e);
        }
    }
}

From source file:esg.node.filters.UrlResolvingFilter.java

@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (filterConfig == null)
        return;//from   w  w  w .j a va  2  s .co m

    boolean success = false;

    //firewall off any errors so that nothing stops the show...
    try {
        if (urlResolvingDAO != null) {

            //This filter should only appy to specific requests
            //in particular requests for data files (*.nc)

            HttpServletResponse res = (HttpServletResponse) response;
            HttpServletRequest req = (HttpServletRequest) request;
            String url = req.getRequestURL().toString().trim();
            Matcher m = urlPattern.matcher(url);

            if (m.matches()) {

                System.out.println("Executing Url Filter For: " + url);
                String resourcePath = urlResolvingDAO.resolveDRSUrl(url);
                //if(null != resourcePath) {
                //    File resolvedResource = new File(resourcePath);
                //    if(!resolvedResource.exists()) { 
                //        log.error("The resolved resource does not exist! ["+url+" -> "+resourcePath+"]");
                //        ((HttpServletResponse)response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 
                //                                                  "Requested Resource Not Present! ["+url+"]");
                //        return;
                //    }
                //    String contentType = "application/x-netcdf";
                //    //ServletUtil.returnFile(req, res, resolvedResource, contentType);
                //    
                //}
                //This would not work... threw IllegalStateException...
                //filterConfig.getServletContext().getRequestDispatcher(urlResolvingDAO.resolveUrl(url)).forward(request,response);

                log.debug("*Passing through chain...");
                chain.doFilter(request, response);

            } else {
                log.debug("No url resolving for: " + url);
            }

        } else {
            log.error("DAO is null :[" + urlResolvingDAO + "]");
            HttpServletResponse resp = (HttpServletResponse) response;
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Invalid State Of ESG Url Resolving Filter");
        }

    } catch (Throwable t) {
        log.error(t);
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Caught unforseen Exception in ESG Url Resolving Filter");
    }

    log.debug("Passing through chain...");
    chain.doFilter(request, response);

}

From source file:com.feilong.controller.DownloadController.java

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
    File f = new File(filePath);
    if (!f.exists()) {
        response.sendError(404, "File not found!");
        return;//from   www .  java  2 s  . c o m
    }
    BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
    byte[] buf = new byte[1024];
    int len = 0;

    response.reset(); // ???
    if (isOnLine) { // ?
        URL u = new URL("file:///" + filePath);
        response.setContentType(u.openConnection().getContentType());
        response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
        // ????UTF-8
    } else { // ?
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
    }
    OutputStream out = response.getOutputStream();
    while ((len = br.read(buf)) > 0)
        out.write(buf, 0, len);
    br.close();
    out.close();
}

From source file:net.sf.appstatus.web.StatusWebHandler.java

/**
 * Handle a POST request./* w w  w . j a v  a2s. com*/
 *
 * @param req
 * @param resp
 * @throws IOException
 */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    if (allowIp != null) {
        if (!req.getRemoteAddr().equals(allowIp)) {
            resp.sendError(401, "IP not authorized");
            return;
        }
    }

    if (req.getParameter("p") != null && pages.containsKey(req.getParameter("p"))) {
        pages.get(req.getParameter("p")).doPost(this, req, resp);

    } else {
        pages.get("status").doPost(this, req, resp);
    }

    doGet(req, resp);
}

From source file:com.sesnu.orion.web.controller.EstimateController.java

private Bid getBidWinner(long OrderId, HttpServletResponse response) throws IOException {
    List<Bid> bid = bidDao.getBidWinner(OrderId);
    if (bid.size() > 0) {
        return bid.get(0);
    } else {//w ww. ja  v  a 2s  . co  m
        response.sendError(400, Util.parseError("Bid winner not found"));
        return null;
    }
}