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.zcarioca.jmx.servlet.handlers.RestRequestHandler.java

public void respond(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from  w  w w .  ja v a2 s.  c o m
        Object value = getResponse(request);

        if (value != null) {
            response.setContentType(MediaType.APPLICATION_JSON);
            response.setCharacterEncoding("UTF-8");

            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(out, value);

            out.flush();
            out.close();
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (InvalidObjectException exc) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } catch (IOException exc) {
        throw exc;
    } catch (Exception exc) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

/**
 * Get a rule by name//from  w w  w .j  ava2s. c o m
 *
 * @param epService Esper provider containing rules
 * @param ruleName Name of the rule
 *
 * @return Result object with a code and a JSON response
 */
public static synchronized Result get(EPServiceProvider epService, String ruleName) {
    try {

        logger.debug("rule asked for: " + ruleName);
        ruleName = ruleName == null ? "" : ruleName;
        EPAdministrator epa = epService.getEPAdministrator();

        if (ruleName.length() != 0) {
            EPStatement st = epa.getStatement(ruleName);
            if (st == null) {
                return new Result(HttpServletResponse.SC_NOT_FOUND,
                        String.format("{\"error\":\"%s not found\"}\n", ruleName));
            } else {
                return new Result(HttpServletResponse.SC_OK, Utils.Statement2JSONObject(st).toString());
            }
        } else {
            String[] sttmntNames = epa.getStatementNames();
            JSONArray ja = new JSONArray();
            for (String name : sttmntNames) {
                logger.debug("getting rule " + name);
                EPStatement st = epa.getStatement(name);
                ja.put(Utils.Statement2JSONObject(st));
            }
            return new Result(HttpServletResponse.SC_OK, ja.toString());
        }

    } catch (EPException epe) {
        logger.error("getting statement" + epe);
        return new Result(HttpServletResponse.SC_BAD_REQUEST,
                String.format("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage())));
    }
}

From source file:com.starit.diamond.server.controller.ConfigController.java

/**
 * ???/*from   ww w.j  a v  a  2s.c o  m*/
 * 
 * @param request
 * @param dataId
 * @param clientGroup
 *            ?
 * @return
 */
@RequestMapping(method = RequestMethod.GET)
public String getConfig(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(Constants.DATAID) String dataId,
        @RequestParam(value = Constants.GROUP, required = false) String group) {
    response.setHeader("Content-Type", "text/plain;charset=UTF-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";

    }

    if (group == null) {
        group = Constants.DEFAULT_GROUP;
    }

    String md5 = this.configService.getContentMD5(dataId, group);
    if (md5 != null) {
        response.setHeader(Constants.CONTENT_MD5, md5);

        // Md5304
        String requestMd5 = request.getHeader(Constants.CONTENT_MD5);
        if (md5.equals(requestMd5)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return "304";
        }
    } else {
        // 404.jsp, 404??, ???404.jsp
        return "404";
    }
    // 304???double-check??
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    String path = configService.getConfigInfoPath(dataId, address, group);
    // ?
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "forward:" + path;
}

From source file:com.haulmont.cuba.core.controllers.FileUploadController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserSession userSession = getSession(request, response);
    if (userSession == null)
        return;/* w  w  w.  jav a 2 s  .  com*/

    AppContext.setSecurityContext(new SecurityContext(userSession));
    try {
        InputStream is = request.getInputStream();
        if (is == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        FileDescriptor fd = getFileDescriptor(request, response);
        if (fd == null)
            return;

        try {
            fileStorage.saveStream(fd, is);
        } catch (FileStorageException e) {
            log.error("Unable to upload file", e);
            response.sendError(e.getType().getHttpStatus());
        } finally {
            IOUtils.closeQuietly(is);
        }
    } finally {
        AppContext.setSecurityContext(null);
    }
}

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

protected void list(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {// www  . j  a  v a2  s.  c o  m
        File streamDir = new File(streamDirName);

        StringBuffer fileList = new StringBuffer("");
        File[] fileArray = streamDir.listFiles();
        if (null != fileArray) {
            Iterator<File> files = Arrays.asList(fileArray).iterator();
            while (files.hasNext()) {
                File f = files.next();
                if (f.isFile())
                    fileList.append(f.getName() + "\n");
            }
        }

        setTextResponse(response, HttpServletResponse.SC_OK, fileList.toString());
    } catch (FileNotFoundException fnfE) {
        setTextResponse(response, HttpServletResponse.SC_OK, "");
    } catch (IllegalArgumentException iaE) {
        setTextResponse(response, HttpServletResponse.SC_BAD_REQUEST, iaE.getMessage());
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w  w  .java  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 {
        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;
        }
        //As of now schedule description is not yet mandatory.
        String schedule_id = (String) requestBodyMap.get("schedule_id");
        String scheduleDesc = requestBodyMap.containsKey("schedule_desc")
                ? String.valueOf(requestBodyMap.get("schedule_desc"))
                : null;

        Map<String, Integer> idMap = ScheduleDAO.updatetoScheduledEmailList(userId,
                Integer.parseInt(schedule_id), 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(","), scheduleDesc,
                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);
    }

}

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

@RequestMapping(value = "/{featureIdOrName}", method = RequestMethod.GET)
public QueryResponse getFeatureByIdOrName(@PathVariable("featureIdOrName") String featureIdOrName,
        @RequestParam("species") String species, HttpServletResponse response)
        throws IllegalOpenCGACredentialsException, IOException {

    initializeQueryOptions();/*ww w . j av a 2  s.  c o  m*/

    if (species == null || species.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return setQueryResponse("Please specify a species");
    }

    MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species));

    List<FeatureCoordinates> features = featureRepository.findByIdOrName(featureIdOrName, featureIdOrName);

    QueryResult<FeatureCoordinates> queryResult = new QueryResult<>();
    queryResult.setResult(features);
    return setQueryResponse(queryResult);
}

From source file:de.hackerspacebremen.commands.WebCommand.java

protected void handleError(final int errorCode) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    result.addError(errorCode);
}

From source file:org.keycloak.secretstore.boundary.QRCodeServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String tokenIdAsString = req.getParameter("tokenId");
    String sizeAsString = req.getParameter("size");
    Principal principal = req.getUserPrincipal();

    int size = 250;

    if (null != sizeAsString && !sizeAsString.isEmpty()) {
        try {//from  w ww  . ja  va  2 s  . co m
            size = Integer.parseInt(req.getParameter("size"));
        } catch (Throwable t) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Size is invalid.");
            return;
        }
    }

    if (null == tokenIdAsString || tokenIdAsString.isEmpty()) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Token key is missing.");
        return;
    }

    UUID tokenId;
    try {
        tokenId = UUID.fromString(tokenIdAsString);
    } catch (Throwable t) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Token key is invalid.");
        return;
    }

    Token token = tokenService.getByIdForDistribution(tokenId);
    if (null == token) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Token could not be found.");
        return;
    }

    if (!principal.getName().equals(token.getPrincipal())) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Token could not be found for principal.");
        return;
    }

    String response = token.getId().toString() + "," + token.getSecret();

    if (null != token.getExpiresAt()) {
        response += "," + token.getExpiresAt().toString();
    }

    BitMatrix bitMatrix;
    try {
        QRCodeWriter writer = new QRCodeWriter();
        bitMatrix = writer.encode(response, BarcodeFormat.QR_CODE, size, size);
    } catch (WriterException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while generating the QR Code.");
        return;
    }

    ByteArrayOutputStream pngOut = new ByteArrayOutputStream();
    MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOut);
    byte[] pngData = pngOut.toByteArray();

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType("image/png");
    resp.getOutputStream().write(pngData);
}

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

@Override
protected void reply(HttpServletRequest req, HttpServletResponse res, PrintWriter writer,
        HttpEndPoint httpEndPoint, EndPoint connection) {
    try {/*  w  w w.j  av  a  2s.  c o  m*/
        String context = retriveParameter(req, "context");
        JSONObject jsonContext = (JSONObject) JSONValue.parseWithException(context);
        ContextMsg msg = new ContextMsg(null, Context.fromJSON(jsonContext));

        logger.debug("Endpoint {}, Context: {}", httpEndPoint, msg);
        broker.receiveMessage(msg, connection);
        writeOut(writer, httpEndPoint.getEndPoint(), "context success");
    } catch (ParseException ex) {

        logger.warn("Context exception: {}", ex.getMessage());

        try {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException ex1) {
            logger.warn("Context reply exception: {}", ex1.getMessage());
        }
    }
}