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.pymegest.applicationserver.api.ProductoController.java

@RequestMapping(value = { "/Producto/{idsProductos}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsProductos") String idsProductosStr) {

    try {//www. j a  v a2 s . com

        String[] idsProductosArr = idsProductosStr.split(",");
        List<Producto> listaProductos = new ArrayList();
        for (int i = 0; i < idsProductosArr.length; i++) {
            listaProductos.add(productoDAO.read(Integer.parseInt(idsProductosArr[i])));
        }

        if (listaProductos.isEmpty() == false) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(listaProductos);
            response.getWriter().println(json);

        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de productos esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.pymegest.applicationserver.api.EmpleadoController.java

@RequestMapping(value = { "/Empleado/{idsEmpleados}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsEmpleados") String idsEmpleadosStr) {

    try {/*from  w ww.j  a  v  a 2 s.c  o  m*/

        String[] idsEmpleadosArr = idsEmpleadosStr.split(",");
        List<Empleado> listaEmpleados = new ArrayList();
        for (int i = 0; i < idsEmpleadosArr.length; i++) {
            listaEmpleados.add(empleadoDAO.read(Integer.parseInt(idsEmpleadosArr[i])));
        }

        if (listaEmpleados.isEmpty() == false) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(listaEmpleados);
            response.getWriter().println(json);

        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de empleados esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.telefonica.iot.perseo.RulesManager.java

/**
 * Make a new rule from a JSON representation of an object with a name field
 * and a text field//from ww  w  . ja v a 2 s  .c o  m
 *
 * @param epService Esper provider containing rules
 * @param text JSON text of the rule
 *
 * @return Result object with a code and a JSON response
 */
public static synchronized Result make(EPServiceProvider epService, String text) {
    try {

        logger.debug("rule text: " + text);
        org.json.JSONObject jo = new JSONObject(text);

        logger.debug("rule as JSONObject: " + jo);
        String name = jo.optString("name", "");
        logger.info("post rule: " + name);
        if ("".equals(name.trim())) {
            return new Result(HttpServletResponse.SC_BAD_REQUEST, "{\"error\":\"missing name\"}");
        }
        String newEpl = jo.optString("text", "");
        if ("".equals(newEpl.trim())) {
            return new Result(HttpServletResponse.SC_BAD_REQUEST, "{\"error\":\"missing text\"}");
        }
        logger.debug("statement name: " + name);
        logger.debug("statement text: " + newEpl);

        EPStatement statement;
        EPStatement prevStmnt = epService.getEPAdministrator().getStatement(name);
        if (prevStmnt == null) {
            logger.debug("found new statement: " + name);

            statement = epService.getEPAdministrator().createEPL(newEpl, name);
            logger.debug("statement json: " + Utils.Statement2JSONObject(statement));
            statement.addListener(new GenericListener());
        } else {
            String oldEpl = prevStmnt.getText();
            logger.debug("old epl: " + oldEpl);
            if (!newEpl.equals(oldEpl)) {
                logger.debug("found changed statement: " + name);
                prevStmnt.destroy();
                logger.debug("deleted statement: " + name);
                statement = epService.getEPAdministrator().createEPL(newEpl, name);
                logger.debug("re-created statement: " + name);
                logger.debug("statement json: " + Utils.Statement2JSONObject(statement));
                statement.addListener(new GenericListener());
            } else {
                logger.debug("found repeated statement: " + name);
                statement = prevStmnt;
            }
        }
        return new Result(HttpServletResponse.SC_OK, Utils.Statement2JSONObject(statement).toString());
    } catch (EPException epe) {
        logger.error("creating statement " + epe);
        return new Result(HttpServletResponse.SC_BAD_REQUEST,
                String.format("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage())));
    } catch (JSONException je) {
        logger.error("creating statement " + je);
        return new Result(HttpServletResponse.SC_BAD_REQUEST,
                String.format("{\"error\":%s}\n", JSONObject.valueToString(je.getMessage())));
    }
}

From source file:com.pymegest.applicationserver.api.UsuarioController.java

@RequestMapping(value = { "/Usuario/{idsUsuarios}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsUsuarios") String idsUsuariosStr) {

    try {/*ww w  . j  av  a2s. c o  m*/

        String[] idsUsuariosArr = idsUsuariosStr.split(",");
        List<Usuario> listaUsuarios = new ArrayList();
        for (int i = 0; i < idsUsuariosArr.length; i++) {
            listaUsuarios.add(usuarioDAO.read(Integer.parseInt(idsUsuariosArr[i])));
        }

        if (listaUsuarios.isEmpty() == false) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(listaUsuarios);
            response.getWriter().println(json);

        }

        else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de usuarios esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.controller.schedule.ScheduleSocialPostActionsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  ww.j a v  a 2  s.c  o m*/
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        response.setContentType("application/json");
        HttpSession session = request.getSession();
        if (session.getAttribute("UID") == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "User is not logged in");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().flush();
            response.setContentType("application/json");
            return;
        }
        Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
        List<Map<String, Object>> requestBodyList = AppConstants.GSON
                .fromJson(new BufferedReader(request.getReader()), List.class);
        if (requestBodyList == null || requestBodyList.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "Request body is missing");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        List<String> errorMessages = validateRequestBodyList(requestBodyList);
        if (!errorMessages.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMessages);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }

        for (Map<String, Object> requestBodyMap : requestBodyList) {
            String tokenDataString = requestBodyMap.get("token_data").toString();
            String type = requestBodyMap.get("type").toString();
            errorMessages.addAll(validateTokenData(tokenDataString, type));
            String metadataString = requestBodyMap.get("metadata").toString();
            errorMessages.addAll(validateMetadata(metadataString, type));
        }

        if (!errorMessages.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMessages);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        List<Map<String, Integer>> daoResponseList = new ArrayList<>();
        try (Connection conn = ConnectionManager.getInstance().getConnection()) {
            conn.setAutoCommit(false);
            try {
                for (Map<String, Object> requestBodyMap : requestBodyList) {
                    String tokenDataString = requestBodyMap.get("token_data").toString();
                    String metadataString = requestBodyMap.get("metadata").toString();
                    String schedule_id = (String) requestBodyMap.get("schedule_id");
                    Map<String, Integer> daoResponse = ScheduleSocialPostDAO.updateActionsToScheduleSocialPost(
                            userId, Integer.parseInt(schedule_id), requestBodyMap.get("image_name").toString(),
                            AppConstants.GSON.fromJson(tokenDataString, Map.class),
                            AppConstants.GSON.fromJson(metadataString, Map.class),
                            requestBodyMap.get("type").toString(), TemplateStatus.template_saved.toString(),
                            conn);
                    daoResponseList.add(daoResponse);
                }
                conn.commit();
            } catch (SQLException ex) {
                conn.rollback();
                throw ex;
            }
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(AppConstants.GSON.toJson(daoResponseList));
            response.getWriter().flush();

        } catch (SQLException ex) {
            Logger.getLogger(ScheduleSocialPostServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (Exception e) {
        Logger.getLogger(ScheduleSocialPostServlet.class.getName()).log(Level.SEVERE, null, e);
        out.println(e);
    }
}

From source file:de.fme.topx.webscript.TopXSearchWebscript.java

/**
 * executes the search- checks input parameter, executes the search and
 * sends back the json result.//w w w.  j  a va  2 s  . c  o  m
 * 
 * (non-Javadoc)
 * 
 * @see org.springframework.extensions.webscripts.WebScript#execute(org.springframework.extensions.webscripts.WebScriptRequest,
 *      org.springframework.extensions.webscripts.WebScriptResponse)
 */
@Override
public void execute(WebScriptRequest req, WebScriptResponse response) throws IOException {
    // get input parameter
    String queryType = req.getParameter("queryType");
    String parentId = req.getParameter("parentId");
    String maxItems = req.getParameter("maxItems") != null ? req.getParameter("maxItems") : DEFAULT_MAX_ITEMS;
    LOG.debug("Incoming request: queryType=" + queryType + ", parentId=" + parentId + ", maxItems=" + maxItems
            + "");

    if (StringUtils.isBlank(queryType)) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        try {
            List<Node> results = searchComponent.submitSearch(queryType, maxItems, parentId);
            generateJson(results, response);
        } catch (Throwable e) {
            LOG.error("Encountered exception while searching and generating json ", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTJobSummary.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    // Get the uri of the resource
    String url = restUtils.extractRepositoryUri(req.getPathInfo());
    if (log.isDebugEnabled()) {
        log.debug("getting job summary for " + url);
    }//from w w w  .j  a va2  s  .c  o  m
    if (url == null) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "malformed url: " + url);
    }

    if (isValidUri(url)) {
        JobSummary[] summaries = new JobSummary[0];
        try {
            summaries = reportSchedulerService.getReportJobs(url);
        } catch (AxisFault axisFault) {
            throw new ServiceException(HttpServletResponse.SC_NOT_FOUND,
                    "could not locate jobs for report in uri: " + url + axisFault.getLocalizedMessage());
        }

        if (summaries == null) {
            restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("found " + summaries.length + "job summaries for report: " + req.getPathInfo());
            }
            restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, generateSummeryReport(summaries));
        }
    } else
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "bad report uri");
}

From source file:com.cloudbees.jenkins.plugins.gogs.hooks.GogsSCMSourcePushHookReceiver.java

/**
 * Receives Gogs push notifications./*from   w  ww. j a v  a 2s . c  om*/
 *
 * @param req Stapler request. It contains the payload in the body content
 *          and a header param "X-Event-Key" pointing to the event type.
 * @return the HTTP response object
 * @throws IOException if there is any issue reading the HTTP content payload.
 */
public HttpResponse doNotify(StaplerRequest req) throws IOException {
    String body = IOUtils.toString(req.getInputStream());
    String eventKey = req.getHeader("X-Gogs-Event");
    if (eventKey == null) {
        return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, "X-Gogs-Event HTTP header not found");
    }
    HookEventType type = HookEventType.fromString(eventKey);
    if (type == null) {
        LOGGER.info("Received unknown Gogs hook: " + eventKey + ". Skipping.");
        return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST,
                "X-Gogs-Event HTTP header invalid: " + eventKey);
    }
    type.getProcessor().process(body);
    return HttpResponses.ok();
}

From source file:com.controller.schedule.ScheduleSocialPostServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  w  w .j a va2  s  .  c o m*/
 *
 * @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 {

    response.setContentType("application/json");
    HttpSession session = request.getSession();
    if (session.getAttribute("UID") == null) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "User is not logged in");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().flush();
        response.setContentType("application/json");
        return;
    }
    Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
    List<Map<String, Object>> requestBodyList = AppConstants.GSON
            .fromJson(new BufferedReader(request.getReader()), List.class);
    if (requestBodyList == null || requestBodyList.isEmpty()) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Request body is missing");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }
    System.out.println(requestBodyList);
    List<String> errorMessages = validateRequestBodyList(requestBodyList);
    if (!errorMessages.isEmpty()) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", errorMessages);
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }

    /*
     If no error messages in the above validation, then next is to validate
     the JSON structure associated with the keys token_data and metadata
     */
    for (Map<String, Object> requestBodyMap : requestBodyList) {
        String tokenDataString = requestBodyMap.get("token_data").toString();
        String type = requestBodyMap.get("type").toString();
        errorMessages.addAll(validateTokenData(tokenDataString, type));
        String metadataString = requestBodyMap.get("metadata").toString();
        errorMessages.addAll(validateMetadata(metadataString, type));
    }

    if (!errorMessages.isEmpty()) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", errorMessages);
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }
    List<Map<String, Integer>> daoResponseList = new ArrayList<>();
    try (Connection conn = ConnectionManager.getInstance().getConnection()) {
        conn.setAutoCommit(false);
        try {
            for (Map<String, Object> requestBodyMap : requestBodyList) {
                Double schedule = (Double) requestBodyMap.get("schedule_time");

                Timestamp scheduleTimeStamp = new Timestamp(schedule.longValue());
                String tokenDataString = requestBodyMap.get("token_data").toString();
                String metadataString = requestBodyMap.get("metadata").toString();

                //As of now schedule description is not yet mandatory.
                String scheduleDesc = requestBodyMap.containsKey("schedule_desc")
                        ? String.valueOf(requestBodyMap.get("schedule_desc"))
                        : null;

                Map<String, Integer> daoResponse = ScheduleSocialPostDAO.addToScheduleSocialPost(userId,
                        requestBodyMap.get("image_name").toString(),
                        AppConstants.GSON.fromJson(tokenDataString, Map.class),
                        AppConstants.GSON.fromJson(metadataString, Map.class),
                        requestBodyMap.get("type").toString(), requestBodyMap.get("schedule_title").toString(),
                        scheduleDesc, scheduleTimeStamp, TemplateStatus.template_saved.toString(), conn);
                daoResponseList.add(daoResponse);
            }
            conn.commit();
        } catch (SQLException ex) {
            conn.rollback();
            throw ex;
        }
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(daoResponseList));
        response.getWriter().flush();

    } catch (SQLException ex) {
        Logger.getLogger(ScheduleSocialPostServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.lushapp.common.web.servlet.RemoteContentServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ??//from  ww w  . jav  a2s  .c o  m
    String contentUrl = request.getParameter("contentUrl");
    if (StringUtils.isBlank(contentUrl)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "contentUrl parameter is required.");
    }

    // ??
    String client = request.getParameter("client");

    InputStream input = null;
    if ("apache".equals(client)) {
        // Apache HttpClient
        fetchContentByApacheHttpClient(response, contentUrl);
    } else {
        // JDK HttpUrlConnection
        fetchContentByJDKConnection(response, contentUrl);
    }
}