Example usage for javax.servlet.http HttpServletResponse SC_BAD_REQUEST

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

Introduction

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

Prototype

int SC_BAD_REQUEST

To view the source code for javax.servlet.http HttpServletResponse SC_BAD_REQUEST.

Click Source Link

Document

Status code (400) indicating the request sent by the client was syntactically incorrect.

Usage

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

@RequestMapping(value = { "/restaurantes" }, method = RequestMethod.GET, produces = "application/json")
public void getRestaurantes(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse) {
    List<Restaurante> listaRestaurantes = new ArrayList<>();
    try {//from   w  w w.  j  a  v  a2  s  .com
        listaRestaurantes = restaurantesDAO.findAll();
        String jsonSalida = jsonTransformer.toJson(listaRestaurantes);
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        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:net.big_oh.common.web.servlets.mime.MimeServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.info(getServletConfig().getServletName() + " invoked.  Requested mime resource: "
            + req.getParameter(REQUESTED_RESOURCE_NAME));

    // Get the name of the requested resource
    String requestedResourceName = req.getParameter(REQUESTED_RESOURCE_NAME);

    if (requestedResourceName == null || requestedResourceName.equals("")) {
        logger.error("Called " + getServletConfig().getServletName() + " without providing a parameter for '"
                + REQUESTED_RESOURCE_NAME + "'");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;//from  w  w  w .  ja v a  2 s.  c  o  m
    }

    // Ensure that the user is allowed to access the requested resource
    if (!isCanUserAccessRequestedResource(requestedResourceName, req.getSession(true))) {
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Get a byte array representation of the resource to be returned in the
    // response
    byte[] resourceBytes = getMimeResourceBytes(requestedResourceName);

    if (resourceBytes == null || resourceBytes.length == 0) {
        logger.error("No resource found under the name \"" + requestedResourceName + "\"");
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Set content length for the response
    resp.setContentLength(resourceBytes.length);

    // Get the MIME type for the resource
    String mimeType = getMimeType(requestedResourceName);

    if (mimeType == null || mimeType.equals("")) {
        logger.error("Failed to get MIME type for the requested resource.");
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Set the content type for the response
    resp.setContentType(mimeType);

    // Control the HTTP caching of the response
    // This setting controls how frequently the cached resource is
    // revalidated (which is not necessarily the same as reloaded)
    resp.setHeader("Cache-Control", "max-age=" + getMaxAgeInSeconds(requestedResourceName));

    // Use streams to return the requested resource
    ByteArrayInputStream in = new ByteArrayInputStream(resourceBytes);
    OutputStream out = resp.getOutputStream();

    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }

    in.close();
    out.close();

}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ??/*  w w w . j av  a 2  s  .  c  o 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();
}

From source file:de.liedtke.presentation.WebCommand.java

protected void handleError(final int errorCode) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    final String error;
    if (this.errorMessages == null) {
        error = "";
    } else {//  w  w  w .j  a v  a  2  s  .  c  om
        error = this.errorMessages.getMessage(errorCode);
    }
    result.addError(error, errorCode);
}

From source file:com.devicehive.websockets.WebSocketResponseBuilder.java

public JsonObject buildResponse(JsonObject request, WebSocketSession session) {
    JsonObject response;//from w w w.  j av a2s.c om
    try {
        response = requestProcessor.process(request, session).getResponseAsJson();
    } catch (BadCredentialsException ex) {
        logger.error("Unauthorized access", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_UNAUTHORIZED, "Invalid credentials").build();
    } catch (AccessDeniedException ex) {
        logger.error("Access to action is denied", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized").build();
    } catch (HiveException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createError(ex).build();
    } catch (ConstraintViolationException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage()).build();
    } catch (org.hibernate.exception.ConstraintViolationException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage()).build();
    } catch (JsonParseException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST,
                Messages.INVALID_REQUEST_PARAMETERS).build();
    } catch (OptimisticLockException ex) {
        logger.error("Error executing the request", ex);
        logger.error("Data conflict", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, Messages.CONFLICT_MESSAGE).build();
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
            response = JsonMessageBuilder
                    .createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage()).build();
        } else {
            response = JsonMessageBuilder
                    .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage())
                    .build();
        }
    } catch (Exception ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage())
                .build();
    }

    return new JsonMessageBuilder().addAction(request.get(JsonMessageBuilder.ACTION))
            .addRequestId(request.get(JsonMessageBuilder.REQUEST_ID)).include(response).build();
}

From source file:com.webtide.jetty.load.generator.web.MonitorServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (_restrictToLocalhost) {
        if (!isLoopbackAddress(req.getRemoteAddr())) {
            resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }//  w  w w.jav  a2s. c  o  m
    }

    if (Boolean.valueOf(req.getParameter("start"))) {
        start = platformMonitor.start();
        return;
    }

    if (Boolean.valueOf(req.getParameter("stop"))) {
        stop = platformMonitor.stop();
        return;
    }

    if (Boolean.valueOf(req.getParameter("stats"))) {
        if (start == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        if (stop == null) {
            stop = platformMonitor.stop();
        }
        sendResponse(resp);
    }
}

From source file:fi.hoski.web.forms.EventServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    Event event;/* www  .j a va2 s .  c o m*/
    String[] eventKeys = request.getParameterValues("event");
    if (eventKeys == null) {
        log("Event parameter missing");
        sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "<div id=\"eNoEvent\">Event parameter missing</div>");
        return;
    } else if (Arrays.asList(eventKeys).contains(Event.EVENT_KEY_CHOOSE)) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "<div id='eChooseEvent'>Choose the event</div>");
        return;
    }

    int count = 1;
    try {
        for (String eventKey : eventKeys) {
            if (!eventKey.isEmpty()) {
                try {
                    event = eventManager.getEvent(eventKey);
                } catch (Exception e) {
                    log(eventKey);
                    log(e.getMessage(), e);
                    sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                            "<div id=\"eNoEvent\">Event not found</div>");
                    return;
                }

                Reservation reservation = new Reservation(event);

                @SuppressWarnings("unchecked")
                Map<String, String[]> params = (Map<String, String[]>) request.getParameterMap();

                reservation.set(Reservation.CREATOR, request.getRemoteUser());
                reservation.populate(params);
                String[] bk = params.get(Repository.VENEET_KEY);
                if (bk != null) {
                    Key boatKey = KeyFactory.stringToKey(bk[0]);
                    reservation.set(Repository.VENEID, boatKey);
                }

                eventManager.createReservation(reservation, false);
            } else {
                if (count == 1) {
                    sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                            "<div id=\"eNoEvent\">Event key not found</div>");
                    return;
                }
            }
            count++;
        }
    } catch (EntityNotFoundException ex) {
        throw new ServletException(ex);
    } catch (DoubleBookingException ex) {
        if (count == 1) {
            log(ex.getMessage(), ex);
            sendError(response, HttpServletResponse.SC_CONFLICT,
                    "<div id=\"eDoubleBooking\">Double booking.</div>");
        }
    } catch (EventFullException e) {
        if (count == 1) {
            log(e.getMessage(), e);
            sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eEventFull\">Event full.</div>");
        }
    } catch (BoatNotFoundException e) {
        log(e.getMessage(), e);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eBoatNotFound\">Boat not found.</div>");

    } catch (MandatoryPropertyMissingException e) {
        log(e.getMessage(), e);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eMandatoryPropertyMissing\">"
                + e.getMessage() + " mandatory property missing.</div>");

    } catch (ConcurrentModificationException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT,
                "<div id=\"eConcurrentModification\">Concurrent modification.</div>");
    }
    response.setContentType("UTF-8");
    response.getWriter().write("Ilmoittautumisesi on vastaanotettu.");
}

From source file:es.tid.cep.esperanza.Events.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*ww  w  .j ava 2  s.  c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("events doPost");
    PrintWriter out = response.getWriter();
    try {
        response.setContentType("application/json;charset=UTF-8");
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        sis.close();
        String eventText = new String(b);
        logger.debug("event as text:" + eventText);
        org.json.JSONObject jo = new JSONObject(eventText);
        logger.debug("event as JSONObject: " + jo);
        Map<String, Object> otro = Utils.JSONObject2Map(jo);
        logger.debug("event as map: " + otro);
        epService.getEPRuntime().sendEvent(otro, "iotEvent");
        logger.debug("event was sent: " + otro);
    } catch (JSONException je) {
        logger.debug("error: " + je.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":\"%s\"}\n", je.getMessage());

    } finally {
        out.close();
    }
}

From source file:org.wte4j.examples.showcase.server.services.GwtOrderServiceServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String fileParameter = req.getParameter("file");
    if (StringUtils.isNotEmpty(fileParameter)) {
        File file = new File(fileParameter);
        sendDocument(file, resp);/*w  ww  .  j  av  a 2 s .com*/
        file.delete();
    } else
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
}

From source file:es.eucm.mokap.backend.server.MokapBackend.java

/**
 * Method: POST Processes post requests.
 * /*from   w w  w.j  av a  2s  .c  om*/
 * <pre>
 * - Requests must be multipart/form-data.
 * - The field with the file must be named "file". 
 * - The file must be a .zip compressed file with the structure
 *   defined in {@link UploadZipStructure}.
 * </pre>
 */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    MokapInsertController iCont = new MokapInsertController();
    // Check api key
    if (!ApiKeyVerifier.checkApiKey(req, resp)) {
        return;
    } else {

        try {
            // Get the uploaded file stream
            FileItemStream fis = getUploadedFile(req);
            if (fis != null) {
                // Actually process the uploaded resource
                String str = iCont.processUploadedResource(fis);
                // Send the response
                PrintWriter out = resp.getWriter();
                out.print(str);
                out.flush();
                out.close();
            } else {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        ServerReturnMessages.INVALID_UPLOAD_FILENOTFOUND);
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    ServerReturnMessages.m(ServerReturnMessages.GENERIC_INTERNAL_ERROR, e.getMessage()));
        }
    }
}