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.ss.Controller.T4uApproveRefundServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from www.  ja  v a2  s.c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    T4uUser user = (T4uUser) session.getAttribute(T4uConstants.T4uUser);
    if (!user.getUserGroup().equals("officer")) // Not authorised, only user himself can cancel order
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not authorised");
    else
        try {
            long orderId = Long.parseLong(request.getParameter("orderId"));
            T4uOrder order = T4uOrderDAO.getOrderById(orderId);
            if (order.getOrderStatus() == 2) { // Current status is Pending
                T4uOrderDAO.changeOrderStatus(orderId, 3, user);
                T4uOrder t4uOrder = new T4uOrder();
                t4uOrder.setOrderId(orderId);
                String json = new Gson().toJson(t4uOrder);
                response.setContentType("application/json");
                // Get the printwriter object from response to write the required json object to the output stream      
                PrintWriter out = response.getWriter();
                // Assuming your json object is **jsonObject**, perform the following, it will return your json object  
                out.print(json);
                out.flush();
            } else // Not pending status
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad order status");
        } catch (NumberFormatException ex) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "NumberFormatException");
        }
}

From source file:org.dspace.app.webui.cris.controller.OUDetailsController.java

@Override
public ModelAndView handleDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    OrganizationUnit ou = extractOrganizationUnit(request);

    if (ou == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "OU page not found");
        return null;
    }//from  w  ww  .  j av a 2 s.c o  m

    Context context = UIUtil.obtainContext(request);
    EPerson currentUser = context.getCurrentUser();
    if ((ou.getStatus() == null || ou.getStatus().booleanValue() == false)
            && !AuthorizeManager.isAdmin(context)) {

        if (currentUser != null || Authenticate.startAuthentication(context, request, response)) {
            // Log the error
            log.info(LogManager.getHeader(context, "authorize_error",
                    "Only system administrator can access to disabled researcher page"));

            JSPManager.showAuthorizeError(request, response,
                    new AuthorizeException("Only system administrator can access to disabled researcher page"));
        }
        return null;
    }

    if (AuthorizeManager.isAdmin(context)) {
        model.put("ou_page_menu", new Boolean(true));
    }

    ModelAndView mvc = null;

    try {
        mvc = super.handleDetails(request, response);
    } catch (RuntimeException e) {
        return null;
    }

    if (subscribeService != null) {
        boolean subscribed = subscribeService.isSubscribed(currentUser, ou);
        model.put("subscribed", subscribed);
    }

    request.setAttribute("sectionid", StatsConfig.DETAILS_SECTION);
    new DSpace().getEventService().fireEvent(new UsageEvent(UsageEvent.Action.VIEW, request, context, ou));

    mvc.getModel().putAll(model);
    mvc.getModel().put("ou", ou);
    return mvc;
}

From source file:org.opens.urlmanager.rest.controller.GenericRestControllerTest.java

/**
 * Test of handleRestException method, of class GenericRestController.
 *//*from www .  java2s .  c o  m*/
public void testHandleRestException() throws Exception {
    System.out.println("handleRestException");
    /* parameters */
    int errorCode = 404;
    String errorMessage = "resource not found";
    /* creating mock */
    GenericRestException exception = createMock(GenericRestException.class);
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);
    /* set up mock */
    expect(exception.getCode()).andReturn(errorCode);
    expect(exception.getMessage()).andReturn(errorMessage);
    response.sendError(errorCode, errorMessage);
    /* create instance */
    GenericRestController instance = new GenericRestController();
    /* playing mock */
    replay(exception);
    replay(request);
    replay(response);

    /* running test */
    instance.handleRestException(exception, request, response);
    /* verifying mock */
    verify(exception);
    verify(request);
    verify(response);
}

From source file:org.magnum.dataup.VideoSvcCtrl.java

/**
 * POST /video/{id}/data//from ww  w.  j a  va 2s . c  om
 * Upload a video... after the user has created it
 * 
 * The binary mpeg data for the video should be provided in a multipart
 * request as a part with the key "data". The id in the path should be
 * replaced with the unique identifier generated by the server for the
 * Video
 * @param videoData
 * @return
 * @throws IOException 
 */
@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.POST)
public @ResponseBody VideoStatus addVideoData(@PathVariable(ID_PARAMETER) long id,
        final @RequestParam(DATA_PARAMETER) MultipartFile videoData, HttpServletResponse response)
        throws IOException {

    Video video;
    try {
        video = videos.get(id);
        saveSomeData(video, videoData);
    } catch (Throwable e) {
        response.sendError(404, ERROR_MSG);
    } finally {
        return new VideoStatus(VideoState.READY);
    }

}

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

@RequestMapping(value = "/api/user/pay/{id}", method = RequestMethod.DELETE)

public @ResponseBody List<PayView> deleteItem(@PathVariable("id") long id, HttpServletResponse response)
        throws Exception {
    Payment pay = payDao.get(id);/*from ww  w .  j a v a 2s.  c om*/
    long orderRef = pay.getOrderRef();

    if (pay.getStatus() != null && pay.getStatus().equals("Approved")) {
        response.sendError(400, Util.parseError("Payment is approved, it can not be deleted"));
        return null;
    }

    if (pay != null) {
        payDao.delete(pay);
        List<PayView> pays = payDao.listAll();
        if (pays.size() > 0) {
            return pays;
        }
    }
    response.sendError(400);
    return null;
}

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

@RequestMapping(value = "/api/user/budget/{year}/{month}", method = RequestMethod.GET)
public @ResponseBody List<Budget> items(@PathVariable("year") int year, @PathVariable("month") String month,
        HttpServletResponse response) throws IOException {
    List<SalesView> salesViews = null;
    if (year == 0 || month.equals("latest")) {
        salesViews = getLatestSalesPlan();
    } else {//from w w w .  j ava2  s.  co m
        salesViews = salesPlanDao.list(year, month.trim());
    }

    if (salesViews.size() < 0) {
        response.sendError(404, Util.parseError("Sales Plan not found"));
        return null;
    }

    List<Budget> budgets = new ArrayList<Budget>();
    for (SalesView sp : salesViews) {
        budgets.add(generateBudget(sp));
    }

    return budgets;
}

From source file:com.headstartech.iam.web.controllers.ExceptionMapper.java

/**
 * Handle constraint violation exceptions.
 *
 * @param response The HTTP response/*w w  w. j a va2  s  . c o m*/
 * @param cve      The exception to handle
 * @throws IOException on error in sending error
 */
@ExceptionHandler(ConstraintViolationException.class)
public void handleConstraintViolation(final HttpServletResponse response,
        final ConstraintViolationException cve) throws IOException {
    final StringBuilder builder = new StringBuilder();
    for (final ConstraintViolation<?> cv : cve.getConstraintViolations()) {
        if (builder.length() != 0) {
            builder.append(NEW_LINE);
        }
        builder.append(cv.getMessage());
    }
    response.sendError(HttpStatus.PRECONDITION_FAILED.value(), builder.toString());
}

From source file:org.magnum.dataup.VideoServiceController.java

@RequestMapping(value = DATA_PATH, method = RequestMethod.POST)
public @ResponseBody VideoStatus setVideoData(@PathVariable("id") long id,
        @RequestParam("data") MultipartFile videoData, HttpServletResponse response) throws IOException {

    VideoStatus result = null;/*from   w  ww. j a v  a2s. c  o  m*/

    if (videos.containsKey(id)) {
        if (videoData != null) {
            manager.saveVideoData(videos.get(id), videoData.getInputStream());
            result = new VideoStatus(VideoState.READY);
        } else {
            response.sendError(400, "No video data given.");
        }
    } else {
        response.sendError(404, "No video with id=" + id + " exists.");
    }

    return result;
}

From source file:edu.northwestern.bioinformatics.studycalendar.web.template.ExportActivitiesController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String identifier = extractIdentifier(request.getPathInfo(), ID_PATTERN);
    String fullPath = request.getPathInfo();
    String extension = fullPath.substring(fullPath.lastIndexOf(".") + 1).toLowerCase();

    if (identifier == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not extract study identifier");
        return null;
    }//from www.  j a v a  2 s .c  o  m
    Source source = sourceDao.getByName(identifier);
    if (source == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
    if (!(extension.equals("csv") || extension.equals("xls") || extension.equals("xml"))) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong extension type");
        return null;
    }
    String elt;

    if (extension.equals("xml")) {
        response.setContentType("text/xml");
        elt = activitySourceXmlSerializer.createDocumentString(source);
    } else {
        if (extension.equals("csv")) {
            response.setContentType("text/plain");
            elt = sourceSerializer.createDocumentString(source, ',');
        } else {
            response.setContentType("text");
            elt = sourceSerializer.createDocumentString(source, '\t');
        }
    }

    byte[] content = elt.getBytes();
    response.setContentLength(content.length);
    response.setHeader("Content-Disposition", "attachment");
    FileCopyUtils.copy(content, response.getOutputStream());
    return null;
}

From source file:io.liuwei.web.StaticContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ??/*from  w  ww.j  av  a  2s .  co m*/
    String contentPath = request.getPathInfo();
    if (StringUtils.isBlank(contentPath) || "/".equals(contentPath)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "contentPath parameter is required.");
        return;
    }

    // ??.
    ContentInfo contentInfo = getContentInfo(contentPath);
    if (!contentInfo.file.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "file not found.");
        return;
    }

    // ?EtagModifiedSince Header?, ??304,.
    if (!Servlets.checkIfModifiedSince(request, response, contentInfo.lastModified)
            || !Servlets.checkIfNoneMatchEtag(request, response, contentInfo.etag)) {
        return;
    }

    // Etag/
    Servlets.setExpiresHeader(response, Servlets.ONE_YEAR_SECONDS);
    Servlets.setLastModifiedHeader(response, contentInfo.lastModified);
    Servlets.setEtag(response, contentInfo.etag);

    // MIME
    response.setContentType(contentInfo.mimeType);

    // ?Header
    if (request.getParameter("download") != null) {
        Servlets.setFileDownloadHeader(response, contentInfo.fileName);
    }

    // OutputStream
    OutputStream output;
    if (checkAccetptGzip(request) && contentInfo.needGzip) {
        // outputstream, http1.1 trunked??content-length.
        output = buildGzipOutputStream(response);
    } else {
        // outputstream, content-length.
        response.setContentLength(contentInfo.length);
        output = response.getOutputStream();
    }

    // ?,?input file
    FileUtils.copyFile(contentInfo.file, output);
    output.flush();
}