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:ai.susi.server.api.vis.PieChartServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    Query post = RemoteAccess.evaluate(request);

    // Get the json data to visualize as a key value pair of data=

    if (post.isDoS_blackout()) {
        response.sendError(503, "Your request frequency is too high");
        return;/*from w w w. ja  va 2 s.c o  m*/
    }

    // Get the data json string passed as stream parameter
    String data = post.get("data", "");
    String legendBitString = post.get("legend", "");
    String tooltipBitString = post.get("tooltip", "");
    String widthString = post.get("width", "");
    String heightString = post.get("height", "");
    boolean legendBit = true;
    boolean tooltipBit = false;

    int width = 500;
    int height = 500;

    if ("".equals(legendBitString) || "false".equals(legendBitString)) {
        legendBit = true;
    } else {
        legendBit = false;
    }

    if ("".equals(tooltipBitString) || !"true".equals(tooltipBitString)) {
        tooltipBit = false;
    } else {
        tooltipBit = true;
    }

    if (!"".equals(widthString)) {
        width = Integer.parseInt(widthString);
    }

    if (!"".equals(heightString)) {
        height = Integer.parseInt(heightString);
    }

    JSONObject json = new JSONObject(data);

    response.setContentType("image/png");

    OutputStream outputStream = response.getOutputStream();

    JFreeChart chart = getChart(json, legendBit, tooltipBit);
    ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
}

From source file:com.cognitivabrasil.repositorio.web.FileController.java

@RequestMapping(value = "/{id}/thumbnail", method = RequestMethod.GET)
public void getThumbnail(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {

    if (id == null || id == 0) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "O arquivo solicitado no foi encontrado.");
    } else {//from ww w .  j a  v a 2  s . c  o m
        String fileName = Config.FILE_PATH + id + "/thumbnail";

        try {
            // get your file as InputStream
            InputStream is = new FileInputStream(new File(fileName));

            response.setHeader("Content-Disposition", "attachment; filename= thumbnail" + id);
            response.setStatus(HttpServletResponse.SC_CREATED);
            // copy it to response's OutputStream
            IOUtils.copy(is, response.getOutputStream());

            response.flushBuffer();

        } catch (FileNotFoundException fe) {
            // get your file as InputStream

            InputStream is = new FileInputStream(new File(DEFAULT_THUMBNAIL_PATH));

            response.setHeader("Content-Disposition", "attachment; filename=default-thumbnail.png");
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
            response.setStatus(HttpServletResponse.SC_CREATED);
            // copy it to response's OutputStream
            IOUtils.copy(is, response.getOutputStream());

            response.flushBuffer();
            LOG.error("Imagen solicitada no foi encontrada.", fe);
        } catch (IOException ex) {
            LOG.error("Error writing file to output stream. Filename was '" + fileName + "'");
            throw ex;
        }
    }
}

From source file:de.steilerdev.myVerein.server.security.rest.RestLogoutSuccessHandler.java

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    User currentUser = (User) authentication.getPrincipal();
    logger.info("[{}] Successfully logged user out from IP {}", currentUser,
            SecurityHelper.getClientIpAddr(request));
    if (!response.isCommitted()) {
        response.sendError(HttpServletResponse.SC_OK, "Successfully logged out");
    }/* www.java2 s . c o m*/
}

From source file:net.lr.jmsbridge.BridgeServlet.java

/**
 * Forward HTTP request to a jms queue and listen on a temporary queue for the reply.
 * Connects to the jms server by using the username and password from the HTTP basic auth.
 *//*  www.  jav  a2s.c  o  m*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String authHeader = req.getHeader("Authorization");
    if (authHeader == null) {
        resp.setHeader("WWW-Authenticate", "Basic realm=\"Bridge\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "auth");
        return;
    }
    UserNameAndPassword auth = extractUserNamePassword(authHeader);
    PrintStream out = new PrintStream(resp.getOutputStream());
    String contextPath = req.getContextPath();
    String uri = req.getRequestURI();
    String queueName = uri.substring(contextPath.length() + 1);
    final StringBuffer reqContent = retrieveRequestContent(req.getReader());

    ConnectionFactory cf = connectionPool.getConnectionFactory(auth);
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(10000);
    final Destination replyDest = connectionPool.getReplyDestination(cf, auth);
    jmsTemplate.send(queueName, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(reqContent.toString());
            message.setJMSReplyTo(replyDest);
            return message;
        }

    });
    Message replyMsg = jmsTemplate.receive(replyDest);
    if (replyMsg instanceof TextMessage) {
        TextMessage replyTMessage = (TextMessage) replyMsg;
        try {
            out.print(replyTMessage.getText());
        } catch (JMSException e) {
            JmsUtils.convertJmsAccessException(e);
        }
    }
}

From source file:com.thoughtworks.go.server.websocket.ConsoleLogSocketServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Username userName = SessionUtils.currentUsername();
    String pipeline = pipeline(request);

    if (authorizedToViewPipeline(userName, pipeline)) {
        super.service(request, response);
        return;//from   w w w.  jav  a 2  s .c  o  m
    }

    response.sendError(SC_FORBIDDEN,
            String.format("%s is not authorized to view the pipeline %s", userName.getDisplayName(), pipeline));
}

From source file:com.seleniumtests.it.driver.support.server.PageServlet.java

/**
  * Allow downloading of files in upload folder
  *///from w ww  .  j  av  a 2 s.  c  om
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        if (this.resourceFile.endsWith(".css")) {
            resp.addHeader("Content-Type", "text/css ");
        }
        IOUtils.copy(getClass().getResourceAsStream(this.resourceFile), resp.getOutputStream());
    } catch (IOException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error while handling request: " + e.getMessage());
    }
}

From source file:de.mpg.escidoc.services.pidcache.web.MainServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.info("POST request");

    if (req.getParameter("url") == null) {
        logger.warn("URL parameter failed.");
        resp.sendError(HttpServletResponse.SC_NO_CONTENT, "URL parameter failed.");
    }/*from w  ww.  j a va  2 s  .co  m*/
    try {

        if (!authenticate(req, resp)) {
            logger.warn("Unauthorized request from " + req.getRemoteHost());
            return;
        }

        PidCacheService cacheService = new PidCacheService();
        String xmlOutput = null;

        if (logger.isDebugEnabled()) {
            logger.info("request pathInfo <" + req.getPathInfo() + ">");
        }
        if (GwdgPidService.GWDG_PIDSERVICE_CREATE.equals(req.getPathInfo())) {
            xmlOutput = cacheService.create(req.getParameter("url"));
        } else if (GwdgPidService.GWDG_PIDSERVICE_EDIT.equals(req.getPathInfo())) {
            if (req.getParameter("pid") == null) {
                resp.sendError(HttpServletResponse.SC_NO_CONTENT, "PID parameter failed.");
            }
            xmlOutput = cacheService.update(req.getParameter("pid"), req.getParameter("url"));
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getPathInfo());
        }

        resp.encodeRedirectURL(cacheService.getLocation());
        resp.addHeader("Location", cacheService.getLocation());
        resp.getWriter().append(xmlOutput);
    } catch (Exception e) {
        throw new ServletException("Error processing request", e);
    }
}

From source file:org.ngrinder.home.controller.HomeController.java

/**
 * Return the health check message. If there is shutdown lock, it returns
 * 503. Otherwise it returns region lists.
 *
 * @param response response//from www .  j  a va 2 s  . c o m
 * @return region list
 */
@RequestMapping("/check/healthcheck")
public HttpEntity<String> healthCheck(HttpServletResponse response) {
    if (getConfig().hasShutdownLock()) {
        try {
            response.sendError(503, "nGrinder is about to down");
        } catch (IOException e) {
            LOG.error("While running healthCheck() in HomeController, the error occurs.");
            LOG.error("Details : ", e);
        }
    }
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("current", regionService.getCurrent());
    map.put("regions", regionService.getAll());
    return toJsonHttpEntity(map, rawObjectJsonSerializer);
}

From source file:com.carolinarollergirls.scoreboard.jetty.LoadXmlScoreBoard.java

protected void handleDocument(HttpServletRequest request, HttpServletResponse response, Document doc)
        throws IOException {
    if (request.getPathInfo().equalsIgnoreCase("/load"))
        getXmlScoreBoard().loadDocument(doc);
    else if (request.getPathInfo().equalsIgnoreCase("/merge"))
        getXmlScoreBoard().mergeDocument(doc);
    else/*from  w w  w.  j a  v  a2  s  .c  om*/
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Must specify to load or merge document");
    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:net.shopxx.interceptor.ValidateInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if (!isValid(request)) {
        String requestType = request.getHeader("X-Requested-With");
        if (StringUtils.equalsIgnoreCase(requestType, "XMLHttpRequest")) {
            response.addHeader("validateStatus", "accessDenied");
        }//  ww w .j a va  2  s  . co  m
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ERROR_MESSAGE);
        return false;
    }
    return true;
}