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:org.activiti.rest.api.identity.LoginPost.java

/**
 * Authenticates username and password and prepares the response for the webscript template.
 *
 * @param req The webscripts request/*from  ww  w  . java2s.  c o m*/
 * @param status The webscripts status
 * @param cache The webscript cache
 * @param model The webscripts template model
 */
@Override
protected void executeWebScript(WebScriptRequest req, Status status, Cache cache, Map<String, Object> model) {
    // Extract user and password from JSON POST
    Content c = req.getContent();
    if (c == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing POST body.");
    }

    try {
        JSONObject json = new JSONObject(c.getContent());
        String userId = json.getString("userId");
        String password = json.getString("password");
        if (userId == null || userId.length() == 0) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
        }
        if (password == null) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Password not specified");
        }
        String engineName = config.getEngine();
        ProcessEngine pe = ProcessEngines.getProcessEngine(engineName);
        if (pe != null) {
            if (!pe.getIdentityService().checkPassword(userId, password)) {
                throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN,
                        "Username and password does not match.");
            }
            // Login successful ...
        } else {
            String message;
            ProcessEngineInfo pei = ProcessEngines.getProcessEngineInfo(engineName);
            if (pei != null) {
                message = pei.getException();
            } else {
                message = "Can't find process engine named '" + engineName
                        + "' which is needed to authenticate username and password.";
                List<ProcessEngineInfo> processEngineInfos = ProcessEngines.getProcessEngineInfos();
                if (processEngineInfos.size() > 0) {
                    message += "\nHowever " + processEngineInfos.size()
                            + " other process engine(s) was found: ";
                }
                for (ProcessEngineInfo processEngineInfo : processEngineInfos) {
                    message += "Process engine '" + processEngineInfo.getName() + "' ("
                            + processEngineInfo.getResourceUrl() + "):";
                    if (processEngineInfo.getException() != null) {
                        message += processEngineInfo.getException();
                    } else {
                        message += "OK";
                    }
                }
            }
            throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        }
    } catch (JSONException e) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST,
                "Unable to parse JSON POST body: " + e.getMessage());
    } catch (IOException e) {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,
                "Unable to retrieve POST body: " + e.getMessage());
    }
}

From source file:com.xyxy.platform.examples.showcase.demos.web.StaticContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ??/*  ww w .  j  a v  a2  s  . com*/
    String contentPath = request.getParameter("contentPath");
    if (StringUtils.isBlank(contentPath)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "contentPath parameter is required.");
        return;
    }

    // ??.
    ContentInfo contentInfo = getContentInfo(contentPath);

    // ?EtagModifiedSince Header?, ??304,.
    if (!Servlets.checkIfModifiedSince(request, response, contentInfo.lastModified)
            || !Servlets.checkIfNoneMatchEtag(request, response, contentInfo.etag)) {
        return;
    }

    // Etag/
    Servlets.setExpiresHeader(response, Servlets.ONE_YEAR_SECONDS);
    Servlets.setLastModifiedHeader(response, contentInfo.lastModified);
    Servlets.setEtag(response, contentInfo.etag);

    // MIME
    response.setContentType(contentInfo.mimeType);

    // ?Header
    if (request.getParameter("download") != null) {
        Servlets.setFileDownloadHeader(request, response, contentInfo.fileName);
    }

    // OutputStream
    OutputStream output;
    if (checkAccetptGzip(request) && contentInfo.needGzip) {
        // outputstream, http1.1 trunked??content-length.
        output = buildGzipOutputStream(response);
    } else {
        // outputstream, content-length.
        response.setContentLength(contentInfo.length);
        output = response.getOutputStream();
    }

    // ?,?input file
    FileUtils.copyFile(contentInfo.file, output);
    output.flush();
}

From source file:com.cradiator.TeamCityStatusPlugin.BuildMonitorController.java

protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (requestHasParameter(request, PROJECT_ID))
        return showProject(request.getParameter(PROJECT_ID), response);
    else if (requestHasParameter(request, BUILD_TYPE_ID))
        return showBuild(request.getParameter(BUILD_TYPE_ID), response);
    else {//w  ww.j ava  2s. com
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no project id or buildTypeId specified");
        return null;
    }
}

From source file:org.energyos.espi.datacustodian.web.customer.CustomerDownloadMyDataController.java

@RequestMapping(value = Routes.RETAIL_CUSTOMER_DOWNLOAD_MY_DATA, method = RequestMethod.GET)
public void downloadMyData(HttpServletResponse response, @PathVariable Long retailCustomerId,
        @PathVariable Long usagePointId, @RequestParam Map<String, String> params)
        throws IOException, FeedException {
    response.setContentType(MediaType.TEXT_HTML_VALUE);
    response.addHeader("Content-Disposition", "attachment; filename=GreenButtonDownload.xml");
    try {/*from   ww  w  .  j  a v a 2 s .  c  o m*/

        exportService.exportUsagePointFull(0L, retailCustomerId, usagePointId, response.getOutputStream(),
                new ExportFilter(params));

    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.collective.celos.servlet.JSONWorkflowSlotsServlet.java

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
    String id = req.getParameter(CelosClient.ID_PARAM);
    try {// www  .  ja  v  a2  s .  c o  m
        if (id == null) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, CelosClient.ID_PARAM + " parameter missing.");
            return;
        }
        Scheduler scheduler = getOrCreateCachedScheduler();
        Workflow wf = scheduler.getWorkflowConfiguration().findWorkflow(new WorkflowID(id));
        if (wf == null) {
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "Workflow not found: " + id);
            return;
        }

        ScheduledTime endTime = getTimeParam(req, CelosClient.END_TIME_PARAM,
                new ScheduledTime(DateTime.now(DateTimeZone.UTC)));
        ScheduledTime startTime = getTimeParam(req, CelosClient.START_TIME_PARAM,
                scheduler.getWorkflowStartTime(wf, endTime));

        if (startTime.plusHours(scheduler.getSlidingWindowHours()).getDateTime()
                .isBefore(endTime.getDateTime())) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Time interval between start and end is limited to: " + scheduler.getSlidingWindowHours()
                            + " hours");
            return;
        }
        try (StateDatabaseConnection connection = getStateDatabase().openConnection()) {
            List<SlotState> slotStates = scheduler.getSlotStates(wf, startTime, endTime, connection);
            List<JsonNode> objectNodes = Lists.newArrayList();
            for (SlotState state : Lists.reverse(slotStates)) {
                objectNodes.add(state.toJSONNode());
            }

            ObjectNode node = Util.MAPPER.createObjectNode();
            node.put(CelosClient.INFO_NODE, (JsonNode) Util.MAPPER.valueToTree(wf.getWorkflowInfo()));
            node.put(CelosClient.PAUSE_NODE, connection.isPaused(wf.getID()));
            node.putArray(CelosClient.SLOTS_NODE).addAll(objectNodes);
            writer.writeValue(res.getOutputStream(), node);
        }
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:uk.ac.ebi.eva.server.ws.ga4gh.GA4GHBeaconWSServer.java

@RequestMapping(value = "/beacon", method = RequestMethod.GET)
public GA4GHBeaconResponse beacon(@RequestParam("referenceName") String chromosome,
        @RequestParam("start") int start, @RequestParam("allele") String allele,
        @RequestParam("datasetIds") String studies, HttpServletResponse response)
        throws UnknownHostException, IllegalOpenCGACredentialsException, IOException {
    initializeQueryOptions();//from ww  w  . j a  v  a 2 s  .c  om

    if (start < 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new GA4GHBeaconResponse(chromosome, start, allele, studies,
                "Please provide a positive number as start position");
    }

    VariantDBAdaptor variantMongoDbAdaptor = DBAdaptorConnector.getVariantDBAdaptor("hsapiens_grch37");

    Region region = new Region(chromosome, start, start + allele.length());
    if (allele.equalsIgnoreCase("INDEL")) {
        queryOptions.put("type", "INDEL");
    } else {
        queryOptions.put("alternate", allele);
    }

    if (studies != null && !studies.isEmpty()) {
        queryOptions.put("studies", Arrays.asList(studies.split(",")));
    }

    QueryResult queryResult = variantMongoDbAdaptor.getAllVariantsByRegion(region, queryOptions);
    //        queryResult.setResult(Arrays.asList(queryResult.getNumResults() > 0));
    //        queryResult.setResultType(Boolean.class.getCanonicalName());
    return new GA4GHBeaconResponse(chromosome, start, allele, studies, queryResult.getNumResults() > 0);
}

From source file:eu.stratosphere.client.web.PactJobJSONServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json");

    String jobName = req.getParameter(JOB_PARAM_NAME);
    if (jobName == null) {
        LOG.warn("Received request without job parameter name.");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;//from   w  w  w .  j  a  va 2s. c o m
    }

    // check, if the jar exists
    File jarFile = new File(jobStoreDirectory, jobName);
    if (!jarFile.exists()) {
        LOG.warn("Received request for non-existing jar file.");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // create the pact plan
    PackagedProgram pactProgram;
    try {
        pactProgram = new PackagedProgram(jarFile, new String[0]);
    } catch (Throwable t) {
        LOG.info("Instantiating the PactProgram for '" + jarFile.getName() + "' failed.", t);
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(t.getMessage());
        return;
    }

    String jsonPlan = null;
    String programDescription = null;

    try {
        jsonPlan = pactProgram.getPreviewPlan();
    } catch (Throwable t) {
        LOG.error("Failed to create json dump of pact program.", t);
    }

    try {
        programDescription = pactProgram.getDescription();
    } catch (Throwable t) {
        LOG.error("Failed to create description of pact program.", t);
    }

    if (jsonPlan == null && programDescription == null) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } else {
        resp.setStatus(HttpServletResponse.SC_OK);
        PrintWriter wrt = resp.getWriter();
        wrt.print("{ \"jobname\": \"");
        wrt.print(jobName);
        if (jsonPlan != null) {
            wrt.print("\", \"plan\": ");
            wrt.println(jsonPlan);
        }
        if (programDescription != null) {
            wrt.print(", \"description\": \"");
            wrt.print(escapeString(programDescription));
            wrt.print("\"");
        }

        wrt.println("}");
    }
}

From source file:com.conwet.silbops.connectors.comet.handlers.UnsubscribeResponse.java

@Override
protected void reply(HttpServletRequest req, HttpServletResponse res, PrintWriter writer,
        HttpEndPoint httpEndPoint, EndPoint connection) {

    try {//  w  w w  .  j av a  2 s .  c o m
        String subscription = retriveParameter(req, "subscription");
        JSONObject jsonSubscription = (JSONObject) JSONValue.parseWithException(subscription);

        UnsubscribeMsg msg = new UnsubscribeMsg();
        msg.setSubscription(Subscription.fromJSON(jsonSubscription));
        broker.receiveMessage(msg, connection);
        writeOut(writer, httpEndPoint.getEndPoint(), "unsubscribe success");
    } catch (ParseException ex) {
        logger.warn("unsubscribe exception: " + ex.getMessage());
        try {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException ex1) {
            logger.warn(ex1.getMessage());
        }
    }
}

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

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    final String content = request.getParameter("content");
    if (StringUtils.isEmpty(content)) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ServletUtils.writeMessage(response, "error", "Script content is required");
        return;/*from   w  ww  .j a  va2 s . com*/
    }

    try {
        final Progress progress = scriptManager.evaluate(content, Mode.VALIDATION,
                request.getResourceResolver());
        if (progress.isSuccess()) {
            ServletUtils.writeMessage(response, "success", "Script passes validation");
        } else {
            final String message = progress.getLastError().getLastMessageText();
            final Map<String, Object> context = new HashMap<>();

            if (message != null) {
                context.put("error", message);
            }

            ServletUtils.writeMessage(response, "error", "Script does not pass validation", context);
        }
    } catch (RepositoryException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error", String
                .format("Script' cannot be validated because of " + "repository error: %s", e.getMessage()));
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w w .jav  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");
    try {
        if (!AuthenticationUtil.isUserLoggedIn(request)) {
            AuthenticationUtil.printAuthErrorToResponse(response);
            return;
        }
        Integer userId = AuthenticationUtil.getUUID(request);

        Map<String, Object> requestBodyMap = AppConstants.GSON.fromJson(new BufferedReader(request.getReader()),
                Map.class);
        if (requestBodyMap == null) {
            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> errorMsgs = validateRequestBody(requestBodyMap);
        if (!errorMsgs.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        Double schedule = (Double) requestBodyMap.get("schedule_time");
        //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> idMap = ScheduleDAO.addToScheduledEmailList(userId,
                requestBodyMap.get("email_subject").toString(), requestBodyMap.get("email_body").toString(),
                requestBodyMap.get("from_email_address").toString(),
                requestBodyMap.get("email_list").toString(), requestBodyMap.get("from_name").toString(),
                requestBodyMap.get("reply_to_email_address").toString(),
                requestBodyMap.get("to_email_addresses").toString().split(","),
                requestBodyMap.get("schedule_title").toString(), scheduleDesc,
                new Timestamp(schedule.longValue()), TemplateStatus.template_saved.toString());
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(idMap));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Invalid format for schedule time.");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (Exception ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}