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:cn.leancloud.diamond.server.controller.ConfigController.java

public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response,
        String probeModify) {/* w ww  .jav a 2 s.c  om*/
    response.setHeader("Content-Type", "text/html;charset=UTF-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    final List<ConfigKey> configKeyList = getConfigKeyList(probeModify);

    StringBuilder resultBuilder = new StringBuilder();
    for (ConfigKey key : configKeyList) {
        String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup());
        if (!StringUtils.equals(md5, key.getMd5())) {
            resultBuilder.append(key.getDataId()).append(Constants.WORD_SEPARATOR).append(key.getGroup())
                    .append(Constants.LINE_SEPARATOR);
        }
    }

    String returnHeader = resultBuilder.toString();
    try {
        returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8");
    } catch (Exception e) {
        // ignore
    }

    request.setAttribute("content", returnHeader);
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "200";
}

From source file:com.alfaariss.oa.ManagerServlet.java

/**
 * Handles requests send by the system manager.
 * /*www.  j  a  va 2s. co m*/
 * The following requests are supported at this moment:
 * <ul>
 * <li>do=restart</li>
 * <li>do=stop</li>
 * <li>do=start</li>
 * </ul>
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse)
        throws ServletException, IOException {
    try {
        Properties pConfig = cloneConfigurationFromRequest(oRequest);
        String sDo = oRequest.getParameter("do");
        if (sDo == null) //No 'do' paramater
        {
            String sGet = oRequest.getParameter("get");
            if (sGet == null) //No 'get' and no 'do' paramater
            {
                _logger.error("Invalid request sent from IP: " + oRequest.getRemoteAddr());
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } else {
                StringBuffer sbWarning = new StringBuffer("Invalid request with name: ");
                sbWarning.append(sGet);
                sbWarning.append(", sent from IP: ");
                sbWarning.append(oRequest.getRemoteAddr());
                _logger.error(sbWarning.toString());
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }

        } else if (sDo.equals("restart")) {
            _logger.info("Performing restart request sent from IP: " + oRequest.getRemoteAddr());
            _oEngineLauncher.restart(pConfig);
        } else if (sDo.equals("stop")) {
            _logger.info("Performing stop request sent from IP: " + oRequest.getRemoteAddr());
            _oEngineLauncher.stop();
        } else if (sDo.equals("start")) {
            _logger.info("Performing start request sent from IP: " + oRequest.getRemoteAddr());
            _oEngineLauncher.start(pConfig);
        } else {
            StringBuffer sbWarning = new StringBuffer("Invalid request with name: ");
            sbWarning.append(sDo);
            sbWarning.append(", sent from IP: ");
            sbWarning.append(oRequest.getRemoteAddr());
            _logger.error(sbWarning.toString());
            oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }

        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_OK);
    } catch (OAException e) {
        _logger.error("Error processing request", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();

        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        _logger.fatal("Internal error", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();

        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.vmware.identity.WebssoMetadataController.java

/**
 * Handle GET request for the metadata/* w w w. j  a v a 2  s. c  om*/
 */
@RequestMapping(value = "/websso/SAML2/Metadata/{tenant:.*}", method = RequestMethod.GET)
public void metadata(Locale locale, @PathVariable(value = "tenant") String tenant, Model model,
        HttpServletResponse response) throws IOException {
    logger.info("Welcome to Metadata handler! " + "The client locale is " + locale.toString() + ", tenant is "
            + tenant);

    //TODO - check for correlation id in the headers PR1561606
    String correlationId = UUID.randomUUID().toString();
    DefaultIdmAccessorFactory factory = new DefaultIdmAccessorFactory(correlationId);
    try {
        IdmAccessor accessor = factory.getIdmAccessor();
        accessor.setTenant(tenant);
        String metadata = accessor.exportConfigurationAsString();
        Validate.notNull(metadata);
        response.setHeader("Content-Disposition", "attachment; filename=" + SAML_METADATA_FILENAME);
        Shared.sendResponse(response, Shared.METADATA_CONTENT_TYPE, metadata);
    } catch (Exception e) {
        logger.error("Caught exception", e);
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null);
        String message = vr.getMessage(messageSource, locale);
        response.sendError(vr.getResponseCode(), message);
        logger.info("Responded with ERROR " + vr.getResponseCode() + ", message " + message);
    }

    model.addAttribute("tenant", tenant);
}

From source file:org.jahia.modules.serversettings.portlets.PreparedPortletsController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    File war = null;//from   w  ww .  j a  v  a  2  s. c  o m
    String fileName = null;
    String warName = null;
    try {
        fileName = ServletRequestUtils.getRequiredStringParameter(request, "file");
        warName = ServletRequestUtils.getStringParameter(request, "war", fileName);
        war = new File(System.getProperty("java.io.tmpdir"), fileName);
    } catch (ServletRequestBindingException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Required parameter war is not found in the request");
        return null;
    }
    InputStream is = null;
    try {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + warName + "\"");

        is = new BufferedInputStream(new FileInputStream(war));
        IOUtils.copy(is, response.getOutputStream());
    } finally {
        IOUtils.closeQuietly(is);
        FileUtils.deleteQuietly(war);
    }
    return null;
}

From source file:com.haulmont.cuba.restapi.FileUploadController.java

@RequestMapping(value = "/api/upload", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserSession userSession = getSession(request, response);
    if (userSession == null)
        return;/*from  ww w. ja  v  a2  s  .  c om*/

    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 {
            uploadToMiddleware(userSession, is, fd);
            saveFileDescriptor(fd);

            response.setStatus(HttpServletResponse.SC_OK);
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
            writer.write(fd.getId().toString());
            writer.close();

        } 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:org.gooru.insights.api.spring.exception.InsightsExceptionResolver.java

public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {/*from   ww w .  j a v a2  s . com*/
    ResponseParamDTO<Map<Object, Object>> responseDTO = new ResponseParamDTO<Map<Object, Object>>();
    Map<Object, Object> errorMap = new HashMap<Object, Object>();
    Integer statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    String traceId = request.getAttribute("traceId") != null ? request.getAttribute("traceId").toString()
            : DEFAULT_TRACEID;
    if (ex instanceof BadRequestException) {
        statusCode = HttpServletResponse.SC_BAD_REQUEST;
    } else if (ex instanceof AccessDeniedException) {
        statusCode = HttpServletResponse.SC_FORBIDDEN;
    } else if (ex instanceof NotFoundException) {
        statusCode = HttpServletResponse.SC_NOT_FOUND;
    } else {
        statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    if (statusCode.toString().startsWith(Numbers.FOUR.getNumber())) {
        InsightsLogger.debug(traceId, ex);
        errorMap.put(DEVELOPER_MESSAGE, ex.getMessage());
    } else if (statusCode.toString().startsWith(Numbers.FIVE.getNumber())) {
        InsightsLogger.error(traceId, ex);
        errorMap.put(DEVELOPER_MESSAGE, DEFAULT_ERROR);
    } else if (statusCode.equals(HttpServletResponse.SC_NO_CONTENT)) {
        InsightsLogger.error(traceId, ex);
        errorMap.put(DEVELOPER_MESSAGE, CONTENT_UNAVAILABLE);
    }
    errorMap.put(STATUS_CODE, statusCode);
    errorMap.put(MAIL_To, SUPPORT_EMAIL_ID);

    response.setStatus(statusCode);
    responseDTO.setMessage(errorMap);
    return new ModelAndView(modelAttributes.VIEW_NAME.getAttribute(),
            modelAttributes.RETURN_NAME.getAttribute(),
            new JSONSerializer().exclude(ApiConstants.EXCLUDE_CLASSES).deepSerialize(responseDTO));

}

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

public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response,
        String probeModify) {/*from  w  ww .j  av  a 2s .c o  m*/
    response.setHeader("Content-Type", "text/html;charset=GBK");
    final String address = getRemortIP(request);
    if (address == null) {
        // 400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    final List<ConfigKey> configKeyList = getConfigKeyList(probeModify);

    StringBuilder resultBuilder = new StringBuilder();
    for (ConfigKey key : configKeyList) {
        String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup());
        if (!StringUtils.equals(md5, key.getMd5())) {
            resultBuilder.append(key.getDataId()).append(WORD_SEPARATOR).append(key.getGroup())
                    .append(LINE_SEPARATOR);
        }
    }

    String returnHeader = resultBuilder.toString();
    try {
        returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8");
    } catch (Exception e) {
        // ignore
    }

    request.setAttribute("content", returnHeader);
    // 
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "200";
}

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

/**
 * ???GetPost??PUTDELETE//from w w w.  j a va 2 s . co  m
 */
@Test
@Ignore
public void testHttpActionGetAndPost() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    response.setCharacterEncoding("UTF-8");

    try {
        request.setMethod("PUT");
        filter.doFilter(request, response, null);

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

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

@Test
public void testInvalidServiceParameter() throws Exception {
    request.addParameter("service", "notvalid");
    servlet.handleRequest(request, response);

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

From source file:com.graphaware.module.resttest.RestTestApi.java

@RequestMapping(value = "/assertSubgraph", method = RequestMethod.POST)
@ResponseBody/*w  w w  . ja  v a  2  s.  co  m*/
public String assertSubgraph(@RequestBody RestTestRequest request, HttpServletResponse response)
        throws IOException {
    if (request.getCypher() == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cypher statement must be provided");
    }

    try {
        GraphUnit.assertSubgraph(database, request.getCypher(), resolveInclusionPolicies(request));
        response.setStatus(HttpServletResponse.SC_OK);
        return null;
    } catch (AssertionError error) {
        response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
        return error.getMessage();
    }
}