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.controller.schedule.GetScheduledEntitiesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w ww.  j a  va  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("application/json");
    try {
        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());
        List<String> errorMsgs = new ArrayList<>();

        if (StringUtils.isEmpty(request.getParameter("from"))) {
            errorMsgs.add("from date parameter is missing");
        }
        if (StringUtils.isEmpty(request.getParameter("to"))) {
            errorMsgs.add("to date parameter is missing");
        }

        if (!errorMsgs.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(responseMap));
            response.getWriter().flush();
            return;
        }

        LocalDate fromDate = null;
        LocalDate toDate = null;
        //Dates have to follow the format: 2011-12-03
        try {
            fromDate = LocalDate.parse(request.getParameter("from"));
        } catch (DateTimeParseException ex) {
            errorMsgs.add("from parameter is not in the required yyyy-mm-dd format");
            logger.log(Level.SEVERE, "", ex);
        }

        try {
            toDate = LocalDate.parse(request.getParameter("to"));
        } catch (DateTimeParseException ex) {
            errorMsgs.add("to parameter is not in the required yyyy-mm-dd format");
            logger.log(Level.SEVERE, "", ex);
        }
        if (!errorMsgs.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(responseMap));
            response.getWriter().flush();
            return;
        }

        JSONObject scheduledEntities = ScheduleDAO.getScheduledEntities(userId, fromDate, toDate);
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(scheduledEntities));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(GetScheduledEntitiesServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.ayovel.nian.servlet.UserBaseServlet.java

/**
 * ??//from  w  ww. j a  v  a  2s.c o m
 */
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String action = request.getParameter(RestConstants.ACTION_PARAM);
    String userid = request.getParameter(RestConstants.USER_ID);

    JSONObject json;
    if (action.equals(RestConstants.USER_LOGIN)) {
        json = userLogin(request, response);
        userid = (String) json.get("userid");
        response.sendRedirect("mainpage");//?
        if (StringUtils.isNotEmpty(userid)) {
            response.sendRedirect("mainpage");//?
        }
    } else if (action.equals(RestConstants.USER_REG)) {
        json = getUserReg(request, response);
        userid = (String) json.get("userid");
        if (StringUtils.isNotEmpty(userid)) {
            response.sendRedirect("mainpage");//?
        }

    } else {//userid?
        if (StringUtils.isEmpty(userid)) {
            response.sendRedirect("userlogin");//?
        }
    }

    if (action.equals(RestConstants.USER_HOME)) {
        json = getUserHome(request, response);
    } else if (action.equals(RestConstants.USER_INFO)) {
        json = getUserInfo(request, response);
    } else {
        throw new XServletException(HttpServletResponse.SC_BAD_REQUEST, ErrorCode.E0303,
                RestConstants.ACTION_PARAM, action);
    }

    if (json != null) {
        sendJsonResponse(response, HttpServletResponse.SC_OK, json);
    } else {
        response.setStatus(HttpServletResponse.SC_OK);
    }
}

From source file:ch.admin.suis.msghandler.servlet.PingServlet.java

private void doProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from   www  . j  av  a 2 s  .  c  om
        response.getWriter().println(handleRequest(request, response));

    } catch (InvalidParameterException ex) {
        LOG.error("Invalid parameter: " + ex);
        response.getWriter().println(ex.getMessage());
        response.setContentType(TEXT);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    } catch (IOException ex) {
        LOG.fatal("MonitorServlet: " + ex.getMessage(), ex);
        throw ex;
    }
}

From source file:com.cognifide.cq.cqsm.core.servlets.ScriptRemoveServlet.java

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    final String all = request.getParameter("confirmation");
    final String fileName = request.getParameter("file");
    ResourceResolver resolver = request.getResourceResolver();
    if (fileName != null) {
        removeSingleFile(resolver, response, fileName);
    } else if (all != null) {
        removeAllFiles(resolver, response, all);
    } else {//w w  w. j a v  a  2 s  . co  m
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ServletUtils.writeMessage(response, "error", "Invalid arguments specified");
    }
}

From source file:org.piraso.server.spring.web.PirasoServletTest.java

@Test
public void testNullServiceParameter() throws Exception {
    servlet.handleRequest(request, response);

    assertTrue(response.getErrorMessage().contains("required"));
    assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
}

From source file:org.jasig.portlet.announcements.controller.RssFeedController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws IllegalStateException, IOException {

    response.setContentType(CONTENT_TYPE);

    Long topicId;/*from  w  ww.  ja  va 2 s .c o m*/
    try {
        topicId = Long.valueOf(ServletRequestUtils.getIntParameter(request, "topic"));
        if (topicId == null) {
            throw new IllegalStateException("Must specify the topic id");
        }
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Must specify topic id");
        return null;
    }

    Topic t = null;
    try {
        t = announcementService.getTopic(topicId);
    } catch (PortletException e) {
        e.printStackTrace();
    }

    if (t == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "no such topic");
        return null;
    }

    if (!t.isAllowRss()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "This topic is not available as RSS");
        return null;
    }

    // fetch and sort the announcements
    List<Announcement> announcements = new ArrayList<Announcement>();
    announcements.addAll(t.getPublishedAnnouncements());

    Collections.sort(announcements);

    // create the feed
    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType("rss_2.0");
    feed.setTitle(t.getTitle());
    feed.setLink(request.getRequestURL().append("?topic=").append(topicId.toString()).toString());
    feed.setDescription(t.getDescription());

    List<SyndEntry> entries = new ArrayList<SyndEntry>();
    SyndEntry entry;
    SyndContent description;

    for (Announcement a : announcements) {
        entry = new SyndEntryImpl();
        entry.setTitle(a.getTitle());
        entry.setAuthor(a.getAuthor());
        if (a.getLink() != null)
            entry.setLink(a.getLink());
        entry.setPublishedDate(a.getStartDisplay());
        description = new SyndContentImpl();
        description.setType("text/plain");
        description.setValue(a.getMessage());
        entry.setDescription(description);
        entries.add(entry);
    }

    feed.setEntries(entries);

    SyndFeedOutput output = new SyndFeedOutput();
    String out;
    try {
        out = output.outputString(feed);
    } catch (FeedException e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating feed");
        return null;
    }

    response.setContentLength(out.length());
    response.getOutputStream().print(out);
    response.getOutputStream().flush();

    return null;

}

From source file:com.carolinarollergirls.scoreboard.jetty.XmlScoreBoardServlet.java

protected void set(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
    XmlListener listener = getXmlListenerForRequest(request);
    if (null == listener) {
        registrationKeyNotFound(request, response);
        return;//from   w  w w.  j  a  v  a2 s .  c o m
    }

    Document requestDocument = editor.toDocument(request.getInputStream());
    if (null == requestDocument) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (debugSet)
        ScoreBoardManager.printMessage(
                "SET from " + listener.getKey() + "\n" + rawXmlOutputter.outputString(requestDocument));

    scoreBoardModel.getXmlScoreBoard().mergeDocument(requestDocument);

    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:eu.europeana.core.util.web.ExceptionResolver.java

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object,
        Exception exception) {/* ww w.  j  a  v a 2  s. c om*/
    PortalTheme theme = ThemeFilter.getTheme();
    if (theme == null) {
        theme = themeHandler.getDefaultTheme();
    }
    final EmailTarget emailTarget = theme.getEmailTarget();
    if (request.getRequestURI().endsWith(".ajax")) {
        return ajaxFailure(request, response, exception);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        QueryProblem queryProblem = QueryProblem.NONE;
        if (exception instanceof EuropeanaQueryException) {
            queryProblem = ((EuropeanaQueryException) exception).getFetchProblem();
        }
        Boolean debugMode = Boolean.valueOf(debug);
        String stackTrace = getStackTrace(exception);
        if (queryProblem == QueryProblem.NONE || queryProblem == QueryProblem.SOLR_UNREACHABLE) {
            if (!debugMode) { // don't send email in debugMode
                emailSender.create("exception").setFrom(emailTarget.getSystemFrom())
                        .setTo(emailTarget.getExceptionTo()).setSubject(queryProblem.getFragment())
                        .set("hostName", request.getServerName())
                        .set("request", ControllerUtil.formatFullRequestUrl(request))
                        .set("stackTrace", stackTrace).set("cacheUrl", cacheUrl).set("portalName", portalName)
                        .set("portalTheme", theme.getName()).set("portalColor", theme.getColorScheme())
                        .set("portalDisplayName", theme.getDisplayName())
                        .set("agent", request.getHeader("User-Agent"))
                        .set("referer", request.getHeader("referer")).send();
            }
            log.error(stackTrace + queryProblem);
        } else {
            log.warn("Oops", exception);
        }
        String errorMessage = MessageFormat.format("errorMessage={0}", queryProblem.toString());
        clickStreamLogger.logCustomUserAction(request, ClickStreamLogger.UserAction.EXCEPTION_CAUGHT,
                errorMessage);
        ModelAndView mav = ThemeFilter.createThemedModelAndViewPage("exception");
        mav.addObject("debug", debugMode);
        mav.addObject("interfaceLanguage", ControllerUtil.getLocale(request));
        mav.addObject("cacheUrl", theme.getCacheUrl());
        mav.addObject("portalName", portalName);
        mav.addObject("portalTheme", "theme/" + theme.getName());
        mav.addObject("portalThemeName", theme.getName());
        mav.addObject("portalColor", theme.getColorScheme());
        mav.addObject("portalDisplayName", theme.getDisplayName());
        mav.addObject("queryProblem", queryProblem);
        mav.addObject("exception", exception);
        mav.addObject("stackTrace", stackTrace);
        mav.addObject("includedMacros", includedMacros);
        final QueryParamList queryParamList = FreemarkerUtil.createQueryParamList(request.getParameterMap());
        mav.addObject("queryParamList", queryParamList);
        mav.addObject("defaultParams", queryParamList.getDefaultParamsFormatted());
        mav.addObject("pageGrabber", freeMarkerUtil);
        return mav;
    }
}

From source file:io.wcm.config.editor.impl.EditorParameterPersistence.java

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    String configurationId = getCurrentConfigurationId(request);
    if (StringUtils.isEmpty(configurationId)) {
        log.error("Could not find configuration id for resource {}", request.getResource().getPath());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Could not find configuration id for resource " + request.getResource().getPath());
        return;//w w w  . j a v  a 2s.co  m
    }

    try {
        persistence.storeData(request.getResourceResolver(), configurationId, getPersistenceData(request),
                false);
    } catch (Throwable ex) {
        log.error("Could not persist data for configuration id {}", configurationId, ex);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}