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.thoughtworks.go.server.controller.PropertiesController.java

@RequestMapping(value = "/repository/restful/properties/post", method = RequestMethod.POST)
public void setProperty(@RequestParam("pipelineName") String pipelineName,
        @RequestParam("pipelineCounter") String pipelineCounter, @RequestParam("stageName") String stageName,
        @RequestParam("stageCounter") String stageCounter, @RequestParam("jobName") String buildName,
        @RequestParam("property") String property, @RequestParam("value") String value,
        HttpServletResponse response, HttpServletRequest request) throws Exception {

    if (!headerConstraint.isSatisfied(request)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required header 'Confirm'");
        return;//from w  ww.  jav  a  2  s .  c o  m
    }

    JobIdentifier jobIdentifier;
    try {
        jobIdentifier = restfulService.findJob(pipelineName, pipelineCounter, stageName, stageCounter,
                buildName);
    } catch (Exception e) {
        BasicRestfulAction.jobNotFound(
                new JobIdentifier(pipelineName, -1, pipelineCounter, stageName, stageCounter, buildName))
                .respond(response);
        return;
    }
    Long id = jobIdentifier.getBuildId();
    propertyService.addProperty(id, property, value).respond(response);
}

From source file:cc.kune.core.server.rack.filters.rest.CORSServiceFilter.java

@Override
protected void customDoFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    final boolean cors = (Boolean) request.getAttribute("cors.isCorsRequest");

    // This part is similar to RESTServiceFilter
    final String methodName = RackHelper.getMethodName(request, pattern);
    final ParametersAdapter parameters = new ParametersAdapter(request);
    LOG.debug((cors ? "" : "NO ") + "CORS METHOD: '" + methodName + "' on: " + serviceClass.getSimpleName());

    response.setCharacterEncoding("utf-8");

    // See: http://software.dzhuvinov.com/cors-filter-tips.html
    response.setContentType("text/plain");

    final RESTResult result = transactionalFilter.doService(serviceClass, methodName, parameters,
            getInstance(serviceClass));/*from w w w  . ja va  2s .  c om*/
    if (result != null) {
        final Exception exception = result.getException();
        if (exception != null) {
            if (exception instanceof InvocationTargetException && ((InvocationTargetException) exception)
                    .getTargetException() instanceof ContentNotFoundException) {
                printMessage(response, HttpServletResponse.SC_NOT_FOUND, result.getException().getMessage());
            } else {
                printMessage(response, HttpServletResponse.SC_BAD_REQUEST, result.getException().getMessage());
            }
        } else {
            final String output = result.getOutput();
            if (output != null) {
                final PrintWriter writer = response.getWriter();
                writer.print(output);
                writer.flush();
            } else {
                // Is not for us!!!
            }
        }
    }
}

From source file:com.thoughtworks.go.domain.FileHandler.java

public boolean handleResult(int httpCode, GoPublisher goPublisher) {
    checksumValidationPublisher.publish(httpCode, artifact, goPublisher);

    return httpCode < HttpServletResponse.SC_BAD_REQUEST;
}

From source file:contestWebsite.PublicResults.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets, html/templates");
    ve.init();//ww w  . j a  v a 2 s .c  o m
    VelocityContext context = new VelocityContext();
    Pair<Entity, UserCookie> infoAndCookie = init(context, req);

    UserCookie userCookie = infoAndCookie.y;
    boolean loggedIn = (boolean) context.get("loggedIn");

    Map<String, Integer> awardCriteria = Retrieve.awardCriteria(infoAndCookie.x);

    if (!loggedIn && req.getParameter("refresh") != null && req.getParameter("refresh").equals("1")) {
        resp.sendRedirect("/?refresh=1");
    }

    Entity contestInfo = infoAndCookie.x;

    context.put("testsGradedNums",
            contestInfo.hasProperty("testsGradedNums") && contestInfo.getProperty("testsGradedNums") != null
                    ? ((Text) contestInfo.getProperty("testsGradedNums")).getValue()
                    : "{}");
    if (contestInfo.hasProperty("testsGraded") && contestInfo.getProperty("testsGraded") != null) {
        context.put("testsGraded", contestInfo.getProperty("testsGraded"));
    }

    Object complete = contestInfo.getProperty("complete");
    if (complete != null && (Boolean) complete || loggedIn && userCookie.isAdmin()) {
        context.put("complete", true);

        String type = req.getParameter("type");
        context.put("type", type);

        if (type != null) {
            String[] types = type.split("_");

            String levelString = req.getParameter("level");
            Level level;
            try {
                level = Level.fromString(levelString);
            } catch (IllegalArgumentException e) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid level: " + levelString);
                return;
            }

            context.put("level", level.toString());
            context.put("tests", Test.getTests(level));
            context.put("Test", Test.class);

            if (type.startsWith("category_")) {
                context.put("test", Test.fromString(types[1]));
                context.put("trophy", awardCriteria.get("category_" + level + "_trophy"));
                context.put("medal", awardCriteria.get("category_" + level + "_medal"));
                context.put("winners", Retrieve.categoryWinners(types[1], level));
            } else if (type.startsWith("qualifying_")) {
                context.put("School", School.class);
                Pair<School, List<Student>> schoolAndStudents = Retrieve.schoolStudents(types[1], level);
                context.put("school", schoolAndStudents.x);
                context.put("students", schoolAndStudents.y);
            } else if (type.startsWith("categorySweep")) {
                context.put("trophy", awardCriteria.get("categorySweep_" + level));
                context.put("winners", Retrieve.categorySweepstakesWinners(level));
            } else if (type.equals("sweep")) {
                context.put("trophy", awardCriteria.get("sweepstakes_" + level));
                context.put("winners", Retrieve.sweepstakesWinners(level));
            } else if (type.equals("visualizations")) {
                Map<Test, Statistics> statistics;
                try {
                    statistics = Retrieve.visualizations(level);
                } catch (JSONException e) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                    e.printStackTrace();
                    return;
                }

                context.put("statistics", statistics);
            } else {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid type: " + type);
                return;
            }
        } else {
            context.put("type", "avail");
        }
    } else {
        context.put("complete", false);
    }

    Map<Level, List<String>> schools = new HashMap<Level, List<String>>();
    for (Level level : Level.values()) {
        schools.put(level, Retrieve.schoolNames(level));
    }
    context.put("schools", schools);

    context.put("qualifyingCriteria", Retrieve.qualifyingCriteria(infoAndCookie.x));
    context.put("hideFullNames", contestInfo.getProperty("hideFullNames"));
    context.put("date", contestInfo.getProperty("updated"));
    context.put("subjects", Subject.values());
    context.put("Level", Level.class);
    context.put("levels", Level.values());
    context.put("esc", new EscapeTool());

    close(context, ve.getTemplate("publicResults.html"), resp);
}

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getPathInfo();
    log.debug(path);//from   ww  w . java  2  s . c o  m

    if (path == null) {
        return;
    }
    String[] parts = path.split("/");

    if (path.length() < 1) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad request");
        return;
    }

    // for this validation, the key and secret are passed as POST parameters
    if (StringUtils.equals(parts[1], "validateOAuthConsumer")) {
        validateOAuthConsumer(request, response);
        return;
    }

    HttpSession session = request.getSession();
    String consumerKey = (String) session.getAttribute("consumerKey");
    String consumerSecret = (String) session.getAttribute("consumerSecret");

    if (!checkOAuthConsumer(consumerKey, consumerSecret)) {
        // no valid key in session, no access
        log.error("Request without valid key from " + request.getRemoteAddr());
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not allowed to access the servlet!");
        return;
    }

    if (StringUtils.equals(parts[1], "deleteTweet")) {
        deleteTweets(request, response);

    } else if (StringUtils.equals(parts[1], "updateUserStatus")) {
        updateUserStatus(request, response);

    } else if (StringUtils.equals(parts[1], "retweet")) {
        retweet(request, response);

    } else if (StringUtils.equals(parts[1], "verifyCredentials")) {
        verifyCredentials(request, response);

    } else if (StringUtils.equals(parts[1], "getTweets")) {
        getTweets(request, response);

    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad request");
        return;
    }
}

From source file:com.thinkberg.webdav.PropFindHandler.java

/**
 * Handle a PROPFIND request./*www .  j  a v a  2s  .c o m*/
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        logXml(propDoc);

        Element propFindEl = propDoc.getRootElement();
        for (Object propElObject : propFindEl.elements()) {
            Element propEl = (Element) propElObject;
            if (VALID_PROPFIND_TAGS.contains(propEl.getName())) {
                FileObject object = VFSBackend.resolveFile(request.getPathInfo());
                if (object.exists()) {
                    // respond as XML encoded multi status
                    response.setContentType("text/xml");
                    response.setCharacterEncoding("UTF-8");
                    response.setStatus(SC_MULTI_STATUS);

                    Document multiStatusResponse = getMultiStatusResponse(object, propEl, getBaseUrl(request),
                            getDepth(request));
                    logXml(multiStatusResponse);

                    // write the actual response
                    XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
                    writer.write(multiStatusResponse);
                    writer.flush();
                    writer.close();

                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
                break;
            }
        }
    } catch (DocumentException e) {
        LOG.error("invalid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

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

private void doProcess(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {// w w w . ja v a 2  s  . com
        FilterClient filterClient = handleParam(request);
        List<DBLogEntry> dbLogEntries = filterClient.filter(mhContext.getLogService().getAllEntries());
        response.getWriter().println(toJson(dbLogEntries, dbLogEntries.getClass()));
        response.setContentType(JSON);
        response.setStatus(HttpServletResponse.SC_OK);

    } catch (LogServiceException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new ServletException(ex);

    } catch (MonitorException ex) {
        LOG.error("Unable to process the task: " + ex.getMessage(), ex);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType(TEXT);
        response.getWriter().println("Invalid request: " + ex.getMessage());

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

From source file:eionet.web.action.SchemasJsonApiActionBean.java

/**
 * Returns information on released/public schemas associated with the given obligation in DD. Both generated schemas (e.g.
 * http://dd.eionet.europa.eu/GetSchema?id=TBL8286) and manually uploaded schemas (e.g.
 * http://dd.eionet.europa.eu/schemas/fgases/FGasesReporting.xsd) are to be included in the response.
 *
 * The response of the method is to be sent as JSON objects (application/json) representing each schema. Every object shall have
 * the following attributes: url identifier (for generated schemas it's the table's Identifier) name (for generated schemas it's
 * the table's Short name). status - Dataset/Schemaset status eg. Released, Recorded or Public draft.
 *
 * If no schemas are found for the requested obligation ID, the method shall return HTTP 404.
 *
 * Parameters: obligationId - Obligation Identifier. Eg, ROD URL: http://rod.eionet.europa.eu/obligations/28 releasedOnly - if
 * true, then returns only released schemas. Otherwise all public schemas will be returned
 *
 * @return Stripes StreamingResolution or ErrorResolution
 *///from  w ww. ja  v  a  2  s.co  m
@HandlesEvent("forObligation")
public Resolution getSchemasForObligation() {

    if (StringUtils.isEmpty(obligationId)) {
        return new ErrorResolution(HttpServletResponse.SC_BAD_REQUEST, "Missing obligationId parameter.");
    }
    List<DataSetTable> datasetTables;
    List<Schema> schemas;
    try {
        datasetTables = tableService.getTablesForObligation(obligationId, releasedOnly);
        schemas = schemaService.getSchemasForObligation(obligationId, releasedOnly);

        if (CollectionUtils.isNotEmpty(datasetTables) || CollectionUtils.isNotEmpty(schemas)) {
            String jsonResult = convertToJson(datasetTables, schemas);
            return new StreamingResolution("application/json", jsonResult);
        } else {
            return new ErrorResolution(HttpServletResponse.SC_NOT_FOUND,
                    "Schemas not found for this obligation.");
        }

    } catch (ServiceException e) {
        e.printStackTrace();
        return new ErrorResolution(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "System error occurred.");
    }
}

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

@RequestMapping(value = Routes.ROOT_USAGE_POINT_COLLECTION, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody//from  w w w  . j ava  2 s .c  o  m
public void index(HttpServletRequest request, HttpServletResponse response,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    Long subscriptionId = getSubscriptionId(request);

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    try {
        System.out.println("Exporting root usage paoints for subscription: " + subscriptionId);
        exportService.exportUsagePoints_Root(subscriptionId, response.getOutputStream(),
                new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

}

From source file:org.mypackage.spring.controllers.EmailsSpringController.java

@RequestMapping(value = "/contacts/{id}/modify/new_email_submitted", method = RequestMethod.POST)
public ModelAndView postCreateNewEmail(@PathVariable String id, @RequestParam("address") String address,
        @RequestParam("category") String categoryValue, @RequestParam("contactId") String contactId) {
    ModelAndView modelAndView = new ModelAndView();
    try {//from w w  w . ja  v a2  s.c  o m
        int newEmailId = newEmailController.addNewEmail(address, categoryValue, id);
        modelAndView.addObject("emailId", newEmailId);
        modelAndView = contactsSpringController.getAContact(id);
        modelAndView.setViewName("redirect:/contacts/" + id + "/modify");
    } catch (DalException ex) {
        logger.error("An error occured while trying to add a new email for contact with ID = " + id
                + "Email object parameters: " + "/nAddress: " + address + "/nCategory value (enum): "
                + categoryValue + "/nfContactId: " + contactId, ex);
        modelAndView.addObject("errorCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        modelAndView.addObject("errorMessage", "An internal database error occured. Please try again.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (MalformedIdentifierException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_BAD_REQUEST);
        modelAndView.addObject("errorMessage",
                "An error occured because of a malformed id." + id + " Please use only numeric values.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (MalformedCategoryException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_CONFLICT);
        modelAndView.addObject("errorMessage",
                "An internal conflict concerning the category of the email occured. Please try again.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (DuplicateEmailException ex) {
        modelAndView = getCreateNewEmail(id);
        modelAndView.addObject("errorMessage", "This address already exists. Please enter a new one.");
    }
    return modelAndView;
}