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:net.myrrix.web.servlets.RecommendToAnonymousServlet.java

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

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
        return;/*from   w  w w.  j a va  2s. co  m*/
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    Pair<long[], float[]> itemIDsAndValue;
    try {
        itemIDsAndValue = parseItemValuePairs(pathComponents);
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (NumberFormatException nfe) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nfe.toString());
        return;
    }

    if (itemIDsAndValue.getFirst().length == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No items");
        return;
    }

    long[] itemIDs = itemIDsAndValue.getFirst();
    float[] values = itemIDsAndValue.getSecond();

    MyrrixRecommender recommender = getRecommender();
    RescorerProvider rescorerProvider = getRescorerProvider();
    try {
        IDRescorer rescorer = rescorerProvider == null ? null
                : rescorerProvider.getRecommendToAnonymousRescorer(itemIDs, recommender,
                        getRescorerParams(request));
        Iterable<RecommendedItem> recommended = recommender.recommendToAnonymous(itemIDs, values,
                getHowMany(request), rescorer);
        output(request, response, recommended);
    } catch (NotReadyException nre) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (NoSuchItemException nsie) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
    }
}

From source file:org.openmrs.module.clinicalsummary.web.controller.response.MedicationIgnoredController.java

@RequestMapping(method = RequestMethod.POST, value = "/module/clinicalsummary/response/ignoreMedication")
public void processIgnore(final @RequestParam(required = true, value = "id") Integer responseId,
        final @RequestParam(required = true, value = "comment") String comment,
        final HttpServletResponse response) throws IOException {

    if (Context.isAuthenticated()) {
        if (StringUtils.isNotBlank(comment)) {
            UtilService service = Context.getService(UtilService.class);
            MedicationResponse medicationResponse = service.getResponse(MedicationResponse.class, responseId);
            medicationResponse.setReviewer(Context.getAuthenticatedUser().getPerson());
            medicationResponse.setDateReviewed(new Date());
            medicationResponse.setReviewComment(comment);
            medicationResponse.setActionType(ActionType.ACTION_IGNORED);
            service.saveResponse(medicationResponse);
        } else {// w w w.  ja v  a2s .co  m
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    Context.getMessageSourceService().getMessage("clinicalsummary.response.required"));
        }
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w.j a v a 2 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 {
    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();
        return;
    }
    Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
    if (StringUtils.isEmpty(request.getParameter("schedule_id"))) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Schedule id is missing");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }

    try {
        Integer scheduleEmailId = Integer.parseInt(request.getParameter("schedule_id"));
        Map<String, Object> scheduleEmailDetails = ScheduleDAO.getScheduleEmailDetails(userId, scheduleEmailId);
        response.getWriter().write(AppConstants.GSON.toJson(scheduleEmailDetails));
        response.getWriter().flush();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (ParseException parse) {
        logger.log(Level.SEVERE, null, parse);
    } catch (NumberFormatException ex) {
        logger.log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Schedule id cannot be parsed to integer");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(GetScheduledEmailDetailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.lternet.pasta.datapackagemanager.dataserver.DataServerServlet.java

/**
 * Process a data download HEAD request using information that was generated
 * by the Data Package Manager service./*from  www. j  a  va 2  s  .co m*/
 */
protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    String dataToken = request.getParameter("dataToken");
    String size = request.getParameter("size");
    String objectName = request.getParameter("objectName");

    if (dataToken == null || dataToken.isEmpty() || size == null || size.isEmpty() || objectName == null
            || objectName.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        /*
         * Find out which directory the temporary data files are being
         * placed in by the Data Package Manager
         */
        PropertiesConfiguration options = ConfigurationListener.getOptions();
        String tmpDir = options.getString("datapackagemanager.tmpDir");

        if (tmpDir == null || tmpDir.equals("")) {
            throw new ServletException("datapackagemanager.tmpDir property value was not specified.");
        }

        try {
            // reads input file from an absolute path
            String filePath = String.format("%s/%s", tmpDir, dataToken);
            File downloadFile = new File(filePath);
            if (!downloadFile.exists()) {
                String message = String.format("File not found: %s", filePath);
                throw new FileNotFoundException(message);
            }
            ServletContext context = getServletContext();

            // gets MIME type of the file
            String mimeType = context.getMimeType(filePath);
            if (mimeType == null) {
                // set to binary type if MIME mapping not found
                mimeType = "application/octet-stream";
            }

            // modifies response
            response.setContentType(mimeType);

            long length = Long.parseLong(size);
            if (length <= Integer.MAX_VALUE) {
                response.setContentLength((int) length);
            } else {
                response.addHeader("Content-Length", Long.toString(length));
            }

            // forces download
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", objectName);
            response.setHeader(headerKey, headerValue);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}

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

@RequestMapping(value = { "/Session" }, method = RequestMethod.POST)
public void insert(HttpServletRequest httpServletRequest, HttpServletResponse response,
        @RequestBody String jsonSession) {

    try {// www .  j  av a 2s .c  o  m

        ObjectMapper objectMapper = new ObjectMapper();

        Credentials credentials = (Credentials) objectMapper.readValue(jsonSession, Credentials.class);

        Usuario usuario = usuarioDAO.findByLogin(credentials.getLogin());

        if (usuario == null) {
            //No existe usuario con login introducido
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            String jsonOutput = objectMapper.writeValueAsString(null);
            response.getWriter().println(jsonOutput);
        } else {

            boolean existe = usuario.checkPassword(credentials.getPassword());

            if (existe) {

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

                String jsonOutput = objectMapper.writeValueAsString(usuario);
                response.getWriter().println(jsonOutput);

                httpServletRequest.getSession(true).setAttribute("idUsuario", usuario.getId_usuario());

            } else {

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

                String jsonOutput = objectMapper.writeValueAsString(null);
                response.getWriter().println(jsonOutput);
            }

        }

    } 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.thoughtworks.go.domain.ChecksumFileHandler.java

public boolean handleResult(int returncode, GoPublisher goPublisher) {
    if (returncode == HttpServletResponse.SC_NOT_FOUND) {
        deleteQuietly(checksumFile);/*w  w w . java 2s  .c  o  m*/
        goPublisher.taggedConsumeLineWithPrefix(GoPublisher.ERR,
                "[WARN] The md5checksum property file was not found on the server. Hence, Go can not verify the integrity of the artifacts.");
        return true;
    }
    if (returncode == HttpServletResponse.SC_NOT_MODIFIED) {
        LOG.info("[Agent Fetch Artifact] Not downloading checksum file as it has not changed");
        return true;
    }
    if (returncode == HttpServletResponse.SC_OK) {
        LOG.info("[Agent Fetch Artifact] Saved checksum property file [{}]", checksumFile);
        return true;
    }
    return returncode < HttpServletResponse.SC_BAD_REQUEST;
}

From source file:cz.incad.kramerius.client.CacheServlet.java

private void saveToFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {/* w  w  w .j  a v  a 2 s  . c o m*/
        String filename = getPath() + req.getParameter("f");
        String content = req.getParameter("c");
        File f = new File(filename);
        FileUtils.writeStringToFile(f, content, "UTF-8");

        resp.getWriter().write("File saved");
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not save file: " + e.toString());
    }
}

From source file:org.smigo.plants.PlantController.java

@RequestMapping(value = { "/rest/plant" }, method = RequestMethod.POST)
@ResponseBody//from  www  .ja  va2 s. c om
public Integer addPlant(@Valid @RequestBody Plant plant, BindingResult result,
        @AuthenticationPrincipal AuthenticatedUser user, HttpServletResponse response) {
    if (result.hasErrors()) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
    return plantHandler.addPlant(user, plant);

}

From source file:io.getlime.security.powerauth.app.server.service.controller.RESTResponseExceptionResolver.java

@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception exception) {
    try {/*from w ww. ja  v  a  2  s. co m*/
        // Build the error list
        RESTErrorModel error = new RESTErrorModel();
        error.setCode("ERR_SPRING_JAVA");
        error.setMessage(exception.getMessage());
        error.setLocalizedMessage(exception.getLocalizedMessage());
        List<RESTErrorModel> errorList = new LinkedList<>();
        errorList.add(error);

        // Prepare the response
        RESTResponseWrapper<List<RESTErrorModel>> errorResponse = new RESTResponseWrapper<>("ERROR", errorList);

        // Write the response in JSON and send it
        ObjectMapper mapper = new ObjectMapper();
        String responseString = mapper.writeValueAsString(errorResponse);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getOutputStream().print(responseString);
        response.flushBuffer();
    } catch (IOException e) {
        // Response object does have an output stream here
    }
    return new ModelAndView();
}

From source file:com.graphaware.module.resttest.RestTestApi.java

@RequestMapping(value = "/assertSameGraph", method = RequestMethod.POST)
@ResponseBody/*  ww w  . j  a v a2s .co m*/
public String assertSameGraph(@RequestBody RestTestRequest request, HttpServletResponse response)
        throws IOException {
    if (request.getCypher() == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cypher statement must be provided");
    }

    try {
        GraphUnit.assertSameGraph(database, request.getCypher(), resolveInclusionPolicies(request));
        response.setStatus(HttpServletResponse.SC_OK);
        return null;
    } catch (AssertionError error) {
        response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
        return error.getMessage();
    }
}