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.devicehive.websockets.AbstractWebSocketHandler.java

@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    logger.error("Error in session " + session.getId(), exception);
    JsonMessageBuilder builder;//w ww  .ja  v  a 2s. co  m

    session = sessionMonitor.getSession(session.getId());

    if (exception instanceof JsonParseException) {
        builder = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST,
                "Incorrect JSON syntax");
    } else {
        builder = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Internal server error");
    }
    session.sendMessage(new TextMessage(GsonFactory.createGson().toJson(builder.build())));
}

From source file:com.iflytek.edu.cloud.frame.web.filter.CheckOpenServiceFilterTest.java

/**
 * ??/*  w  ww  .j ava 2 s .com*/
 */
@Test
@Ignore
public void testMethodNotExist() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    response.setCharacterEncoding("UTF-8");

    try {
        request.setMethod("POST");
        request.addParameter("method", "user.add");
        request.addParameter("version", "1.0.0");
        filter.doFilter(request, response, null);

        Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_BAD_REQUEST);
        Assert.assertEquals(MainErrorType.INVALID_METHOD.value(), ErrorMsgParser.getErrorCode(response));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ServletException e) {
        e.printStackTrace();
    }
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AccessTokenController.java

private HttpEntity<String> buildInvalidClientIdResponse() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(OAuthError.TokenResponse.INVALID_CLIENT)
            .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION).buildJSONMessage();
    return new ResponseEntity<String>(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}

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

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {//  w ww .  ja v  a2  s .co m
        final LockManager manager = LockManager.getInstance();
        final LockManager.EvaluationResult evaluation = manager.evaluateCondition(object, getIf(request));
        if (!evaluation.result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        } else {
            if (!evaluation.locks.isEmpty()) {
                LOG.debug(String.format("discovered locks: %s", evaluation.locks));
                sendLockAcquiredResponse(response, evaluation.locks.get(0));
                return;
            }
        }
    } catch (LockConflictException e) {
        List<Lock> locks = e.getLocks();
        for (Lock lock : locks) {
            if (Lock.EXCLUSIVE.equals(lock.getType())) {
                response.sendError(SC_LOCKED);
                return;
            }
        }
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    try {
        SAXReader saxReader = new SAXReader();
        Document lockInfo = saxReader.read(request.getInputStream());
        //log(lockInfo);

        Element rootEl = lockInfo.getRootElement();
        String lockScope = null, lockType = null;
        Object owner = null;
        Iterator elIt = rootEl.elementIterator();
        while (elIt.hasNext()) {
            Element el = (Element) elIt.next();
            if (TAG_LOCKSCOPE.equals(el.getName())) {
                lockScope = el.selectSingleNode("*").getName();
            } else if (TAG_LOCKTYPE.equals(el.getName())) {
                lockType = el.selectSingleNode("*").getName();
            } else if (TAG_OWNER.equals(el.getName())) {
                // TODO correctly handle owner
                Node subEl = el.selectSingleNode("*");
                if (subEl != null && TAG_HREF.equals(subEl.getName())) {
                    owner = new URL(el.selectSingleNode("*").getText());
                } else {
                    owner = el.getText();
                }
            }
        }

        LOG.debug("LOCK(" + lockType + ", " + lockScope + ", " + owner + ")");

        Lock requestedLock = new Lock(object, lockType, lockScope, owner, getDepth(request),
                getTimeout(request));
        try {
            LockManager.getInstance().acquireLock(requestedLock);
            sendLockAcquiredResponse(response, requestedLock);
        } catch (LockConflictException e) {
            response.sendError(SC_LOCKED);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:org.pentaho.pat.server.servlet.FileUploadController.java

protected ModelAndView handle(final HttpServletRequest request, final HttpServletResponse response,
        final Object command, final BindException errors) throws Exception {
    final FileUploadBean fileUploadBean = (FileUploadBean) command;

    try {//from  www  . jav  a  2  s.  c om
        final MultipartFile files = fileUploadBean.getFile();
        String schemaData = new String(files.getBytes());
        String validationResult = AbstractSchemaValidator.validateAgainstXsd(schemaData);
        response.setContentType("text/plain"); //$NON-NLS-1$

        if (validationResult == null) {
            validationResult = ""; //$NON-NLS-1$
        }

        response.getWriter().print(VALIDATION_START + validationResult + VALIDATION_END);
        // Send a confirmation message to the client

        response.getWriter().print(DATA_START + (new String(Base64Coder.encode(files.getBytes()))) + DATA_END);
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        LOG.error(e.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    // return the result to the client
    response.getWriter().flush();

    return null;
}

From source file:com.enjoyxstudy.selenium.autoexec.CommandHandler.java

/**
 * handle command.//from   w  ww.  j a  v  a 2  s  .c  om
 *
 * @param commandName
 * @param request
 * @param response
 * @throws HttpException
 * @throws IOException
 */
private void command(String commandName, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {

    // type
    String type = request.getParameter("type");
    if (type == null || type.equals("")) {
        type = TYPE_TEXT;
    }

    if (!type.equals(TYPE_TEXT) && !type.equals(TYPE_JSON)) {
        throw new HttpException(HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        if (commandName.equals("server/stop")) {

            log.info("Receive command(Stop server).");

            commandServerStop(type, response);

        } else if (commandName.equals("run")) {

            log.info("Receive command(Run test).");

            commandRun(type, response);
        } else if (commandName.equals("run/async")) {

            log.info("Receive command(Run test async).");

            commandRunAsync(type, response);
        } else if (commandName.equals("status")) {

            log.info("Receive command(Get status).");

            commandStatus(type, response);

        } else {
            throw new HttpException(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (Exception e) {
        log.error("Command Error", e);
        throw new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

@RequestMapping(value = Routes.ROOT_TIME_CONFIGURATION_MEMBER, method = RequestMethod.PUT, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody/*from  w w w.j  a v  a 2 s  .  c  o m*/
public void update(HttpServletResponse response, @PathVariable Long timeConfigurationId,
        @RequestParam Map<String, String> params, InputStream stream) {

    try {
        timeConfigurationService.importResource(stream);
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

}

From source file:eu.earthobservatory.org.StrabonEndpoint.BrowseBean.java

/**
 * Processes the request made by a client of the endpoint that uses it as a
 * service.//from   www. j a  v  a  2  s .c  o  m
 * 
 * @param request
 * @param response
 * @throws IOException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletOutputStream out = response.getOutputStream();

    // get the stSPARQL Query Result format (we check only the Accept
    // header)
    stSPARQLQueryResultFormat format = stSPARQLQueryResultFormat.forMIMEType(request.getHeader("accept"));

    // get the query
    String query = request.getParameter("query");

    // check for required parameters
    if (format == null || query == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.print(ResponseMessages.getXMLHeader());
        out.print(ResponseMessages.getXMLException(PARAM_ERROR));
        out.print(ResponseMessages.getXMLFooter());

    } else {
        // decode the query
        query = URLDecoder.decode(request.getParameter("query"), "UTF-8");

        response.setContentType(format.getDefaultMIMEType());
        try {
            strabonWrapper.query(query, format.getName(), out);
            response.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print(ResponseMessages.getXMLHeader());
            out.print(ResponseMessages.getXMLException(e.getMessage()));
            out.print(ResponseMessages.getXMLFooter());
        }
    }

    out.flush();
}

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

@RequestMapping(value = Routes.ROOT_READING_TYPE_MEMBER, method = RequestMethod.DELETE)
public void delete(HttpServletResponse response, @PathVariable Long readingTypeId,
        @RequestParam Map<String, String> params) throws IOException {
    try {//  w w w  .  j  a v  a 2  s. com
        resourceService.deleteById(readingTypeId, ReadingType.class);
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:eu.stratosphere.nephele.jobmanager.web.JobmanagerInfoServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType("application/json");

    try {/*from   w  ww.  ja  va2  s. co  m*/
        if ("archive".equals(req.getParameter("get"))) {
            writeJsonForArchive(resp.getWriter(), jobmanager.getOldJobs());
        } else if ("job".equals(req.getParameter("get"))) {
            String jobId = req.getParameter("job");
            writeJsonForArchivedJob(resp.getWriter(),
                    jobmanager.getArchive().getJob(JobID.fromHexString(jobId)));
        } else if ("groupvertex".equals(req.getParameter("get"))) {
            String jobId = req.getParameter("job");
            String groupvertexId = req.getParameter("groupvertex");
            writeJsonForArchivedJobGroupvertex(resp.getWriter(),
                    jobmanager.getArchive().getJob(JobID.fromHexString(jobId)),
                    ManagementGroupVertexID.fromHexString(groupvertexId));
        } else if ("taskmanagers".equals(req.getParameter("get"))) {
            resp.getWriter().write("{\"taskmanagers\": " + jobmanager.getNumberOfTaskTrackers() + "}");
        } else if ("cancel".equals(req.getParameter("get"))) {
            String jobId = req.getParameter("job");
            jobmanager.cancelJob(JobID.fromHexString(jobId));
        } else if ("updates".equals(req.getParameter("get"))) {
            String jobId = req.getParameter("job");
            writeJsonUpdatesForJob(resp.getWriter(), JobID.fromHexString(jobId));
        } else {
            writeJsonForJobs(resp.getWriter(), jobmanager.getRecentJobs());
        }

    } catch (Exception e) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(e.getMessage());
        if (LOG.isWarnEnabled()) {
            LOG.warn(StringUtils.stringifyException(e));
        }
    }
}