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.fpmislata.banco.presentation.controladores.UsuarioController.java

@RequestMapping(value = "/usuario/{idUsuario}", method = RequestMethod.DELETE, produces = "application/json")
public void delete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @PathVariable("idUsuario") int idUsuario) {
    try {//from   w w  w. ja va 2s. c  om
        boolean deleteUsuario;
        deleteUsuario = usuarioService.delete(idUsuario);

        if (deleteUsuario == true) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        } else {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:io.nirvagi.utils.servlet.RecorderServlet.java

private void process(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Action action = this.getActionFromParam(req.getParameter(ACTION_PARAM));
    try {//from  ww  w. j  a  v a2  s.  co m
        switch (action) {
        case START:
        case STOP:
            final String key = req.getParameter(KEY_PARAM);
            if (key == null || key.isEmpty()) {
                action = Action.SHOWFILES;
            }
            if (action == Action.START) {
                // Store the key , IN case if the node is killed cleanup (stop) the recorder using this key
                recorderKey = key;
                recorder.start(key);
                long timeout = getTimeout(req.getParameter(MAX_TIMEOUT_PARAM));
                System.err.println("The recorder timeout is " + timeout + " seconds!");
                futureHandle = executorService.schedule(new RecorderMonitorTask(recorder, key), timeout,
                        TimeUnit.SECONDS);
                return;
            }
            if (action == Action.STOP) {
                System.err.println("Stopping the monitor thread");
                futureHandle.cancel(true);
                recorder.stop(key);
                return;
            }
        case SHOWFILES:
            String htmlString = buildFileListHtml();
            resp.getWriter().print(htmlString);
            return;
        case DOWNLOAD:
            String filename = req.getParameter(FILENAME_PARAM);
            resp.setContentType(CONTENT_TYPE);
            resp.setHeader(CONTENT_DISPOSITION_HEADER, String.format(FILE_NAME, filename));
            FileUtils.copyFile(new File(filename), resp.getOutputStream());
            return;
        }
    } catch (Exception err) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, err.getMessage());
        return;
    }
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.ibm.controllers.WatsonController.java

@RequestMapping(value = "/textprocess", method = RequestMethod.GET)
public void processtext(@ModelAttribute("Spring") Text txt, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    TextToSpeech service = new TextToSpeech();
    service.setUsernameAndPassword(TEXTUSERNAME, TEXTPASSWORD);
    try {//  www  .ja v  a 2 s . co  m

        String text = request.getParameter("text");
        InputStream stream = service.synthesize(text, Voice.EN_ALLISON, AudioFormat.WAV).execute();
        InputStream in = WaveUtils.reWriteWaveHeader(stream);

        if (request.getParameter("download") != null) {
            response.setHeader("content-disposition", "attachment; filename=audio.wav");
        }
        OutputStream out = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        out.close();
        in.close();
        stream.close();
        System.out.println("done");
    } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }

    // return "done";
}

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

@RequestMapping(value = { "/restaurantes/{id}" }, method = RequestMethod.GET, produces = "application/json")
public void getRestauranteById(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse,
        @PathVariable("id") int idRestaurante) {
    try {/*  ww w.j  av  a 2  s .  co m*/
        Restaurante restaurante = restaurantesDAO.get(idRestaurante);
        String jsonSalida = jsonTransformer.toJson(restaurante);
        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:com.almende.eve.transport.http.DebugServlet.java

/**
 * Handle session./*w  ww . j a v a  2  s  . c om*/
 * 
 * @param req
 *            the req
 * @param res
 *            the res
 * @return true, if successful
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private boolean handleSession(final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    try {

        if (req.getSession(false) != null) {
            return true;
        }
        // TODO: make sure connection is secure if configured to enforce
        // that.
        final Handshake hs = doHandShake(req);
        if (hs.equals(Handshake.INVALID)) {
            return false;
        }

        final boolean doAuthentication = HttpService.doAuthentication(myUrl);
        if (hs.equals(Handshake.NAK) && doAuthentication) {
            if (!req.isSecure()) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Request needs to be secured with SSL for session management!");
                return false;
            }
            if (!req.authenticate(res)) {
                return false;
            }
        }
        // generate new session:
        req.getSession(true);
    } catch (final Exception e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Exception running HandleSession:" + e.getMessage());
        LOG.log(Level.WARNING, "", e);
        return false;
    }
    return true;
}

From source file:com.sun.faban.harness.webclient.CLIServlet.java

/**
 * Submits new runs or kills runs. For submission, the POST request must be
 * a multi-part POST. The first parts contain user name and password
 * information (if security is enabled). Each subsequent part contains the
 * run configuration file. The configuration file is not used for kill
 * requests.//from  w w  w. jav a  2s. c  o  m
 * <br><br>
 * Path to call this servlet is http://.../submit/${benchmark}/${profile}
 * and http://.../kill/${runId}.
 *
 * @param request The mime multi-part post request
 * @param response The response object
 * @throws ServletException Error executing servlet
 * @throws IOException I/O error
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Path to call this servlet is http://...../${benchmark}/${profile}
    // And it is a post request with optional user, password, and
    // all the config files.
    String[] reqC = getPathComponents(request);
    if ("/submit".equals(reqC[0])) {
        doSubmit(reqC, request, response);
    } else if ("/kill".equals(reqC[0])) {
        doKill(reqC, request, response);
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Request string " + reqC[0] + " not understood!");
    }
}

From source file:org.energyos.espi.datacustodian.web.api.AuthorizationRESTController.java

@RequestMapping(value = Routes.ROOT_AUTHORIZATION_MEMBER, method = RequestMethod.PUT, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody/*from  www  .ja  v  a 2s  .  c  o  m*/
public void update(HttpServletResponse response, @PathVariable Long authorizationId,
        @RequestParam Map<String, String> params, InputStream stream) throws IOException, FeedException {
    Authorization authorization = authorizationService.findById(authorizationId);

    if (authorization != null) {
        try {

            Authorization newAuthorization = authorizationService.importResource(stream);
            authorization.merge(newAuthorization);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java

private void sendSaveSolutionResult() {
    try {//from   w ww.j  a  va 2 s.co m
        boolean completed = Boolean.parseBoolean(request.getParameter("completed"));
        Project solution = objectMapper.readValue(request.getParameter("solution"), Project.class);
        solution.args = "";
        MySqlConnector.getInstance().saveSolution(sessionInfo.getUserInfo(), solution, completed);
    } catch (IOException e) {
        writeResponse("Can't write response", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (DatabaseOperationException e) {
        writeResponse(e.getMessage(), HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.imaginary.home.cloud.api.call.RelayCall.java

@Override
public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {/*from   ww w.  j a va  2  s  .  c  o  m*/
        if (path.length < 2) {
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No PUT on /relay");
        }
        ControllerRelay relay = ControllerRelay.getRelay(path[1]);

        if (relay == null) {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                    "Relay " + path[1] + " not found");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());
        String action;

        if (object.has("action") && !object.isNull("action")) {
            action = object.getString("action");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "An invalid action was specified (or not specified) in the PUT");
        }
        if (action.equalsIgnoreCase("update")) {
            if (userId != null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.USER_NOT_ALLOWED,
                        "This API call may be called only by controller relays");
            }
            update(relay, object, resp);
        } else if (action.equalsIgnoreCase("modify")) {
            if (object.has("relay")) {
                object = object.getJSONObject("relay");
            } else {
                object = null;
            }
            if (object == null) {
                throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PUT,
                        "No location was specified in the PUT");
            }
            String name;

            if (object.has("name") && !object.isNull("name")) {
                name = object.getString("name");
            } else {
                name = relay.getName();
            }
            relay.modify(name);
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "The action " + action + " is not a valid action.");
        }
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in body");
    } catch (PersistenceException e) {
        e.printStackTrace();
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                "Internal database error");
    }
}

From source file:org.energyos.espi.datacustodian.web.api.UsagePointRESTController.java

@RequestMapping(value = Routes.ROOT_USAGE_POINT_MEMBER, method = RequestMethod.PUT, consumes = "application/atom+xml")
@ResponseBody/*w w w . ja v  a  2  s .c  om*/
public void update(HttpServletResponse response, @PathVariable Long usagePointId,
        @RequestParam Map<String, String> params, InputStream stream) {
    UsagePoint usagePoint = usagePointService.findById(usagePointId);

    if (usagePoint != null) {
        try {

            UsagePoint newUsagePoint = usagePointService.importResource(stream);
            usagePoint.merge(newUsagePoint);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}