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.pentaho.pat.server.servlet.ExportController.java

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

    try {/*  w ww  .j a  v a 2  s.co  m*/
        if (OlapUtil.getCellSet(queryExportBean.getQuery()) != null) {

            byte[] resultExcel = exportExcel(queryExportBean.getQuery());
            if (resultExcel != null && resultExcel.length > 0) {
                response.setContentType("application/vnd.ms-excel"); //$NON-NLS-1$
                response.setHeader("Content-Disposition", "attachment; filename=PAT_Export.xls");
                response.setHeader("Content-Length", "" + resultExcel.length);
                response.getOutputStream().write(resultExcel);
                response.flushBuffer();

            } else {
                LOG.error("Empty Excel resultset - nothing to return");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            }

        } else {
            LOG.error("CellSet for query ID not found :" + queryExportBean.getQuery());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    return null;
}

From source file:dk.dma.msiproxy.web.MessageDetailsServlet.java

/**
 * Main GET method//ww  w . j a v  a2s  . c  o  m
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Never cache the response
    response = WebUtils.nocache(response);

    // Read the request parameters
    String providerId = request.getParameter("provider");
    String lang = request.getParameter("lang");
    String messageId = request.getParameter("messageId");
    String activeNow = request.getParameter("activeNow");
    String areaHeadingIds = request.getParameter("areaHeadings");

    List<AbstractProviderService> providerServices = providers.getProviders(providerId);

    if (providerServices.size() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid 'provider' parameter");
        return;
    }

    // Ensure that the language is valid
    lang = providerServices.get(0).getLanguage(lang);

    // Force the encoding and the locale based on the lang parameter
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    final Locale locale = new Locale(lang);
    request = new HttpServletRequestWrapper(request) {
        @Override
        public Locale getLocale() {
            return locale;
        }
    };

    // Get the messages in the given language for the requested provider
    MessageFilter filter = new MessageFilter().lang(lang);
    Date now = "true".equals(activeNow) ? new Date() : null;
    Integer id = StringUtils.isNumeric(messageId) ? Integer.valueOf(messageId) : null;
    Set<Integer> areaHeadings = StringUtils.isNotBlank(areaHeadingIds) ? Arrays
            .asList(areaHeadingIds.split(",")).stream().map(Integer::valueOf).collect(Collectors.toSet())
            : null;

    List<Message> messages = providerServices.stream().flatMap(p -> p.getCachedMessages(filter).stream())
            // Filter on message id
            .filter(msg -> (id == null || id.equals(msg.getId())))
            // Filter on active messages
            .filter(msg -> (now == null || msg.getValidFrom() == null || msg.getValidFrom().before(now)))
            // Filter on area headings
            .filter(msg -> (areaHeadings == null || areaHeadings.contains(getAreaHeadingId(msg))))
            .collect(Collectors.toList());

    // Register the attributes to be used on the JSP apeg
    request.setAttribute("messages", messages);
    request.setAttribute("baseUri", app.getBaseUri());
    request.setAttribute("lang", lang);
    request.setAttribute("locale", locale);
    request.setAttribute("provider", providerId);

    if (request.getServletPath().endsWith("pdf")) {
        generatePdfFile(request, response);
    } else {
        generateHtmlPage(request, response);
    }
}

From source file:de.yaio.services.webshot.server.controller.WebshotController.java

@ExceptionHandler(PermissionException.class)
public void handleCustomException(final HttpServletRequest request, final PermissionException e,
        final HttpServletResponse response) throws IOException {
    LOGGER.info("Exception while running request:" + createRequestLogMessage(request), e);
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.getWriter().append("permission denied (firewall...) while webshoting resource");
}

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

@RequestMapping(value = "/api/login", method = RequestMethod.POST)
public void loginByPost(@RequestBody String requestBody,
        @RequestHeader(value = "Content-Type") MimeType contentType, HttpServletRequest request,
        HttpServletResponse response) throws IOException, JSONException {

    String username;/* w  w w. ja  v  a 2 s .  com*/
    String password;
    String localeStr;
    if (contentType.match(JSONConverter.MIME_TYPE_JSON)) {
        try {
            JSONObject json = new JSONObject(requestBody);
            username = json.getString("username");
            password = json.getString("password");
            localeStr = json.getString("locale");
        } catch (JSONException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
    } else if (contentType.match(FORM_TYPE)) {
        String[] pairs = requestBody.split("\\&");
        Map<String, String> name2value = new HashMap<>();
        for (String pair : pairs) {
            String[] fields = pair.split("=");
            if (fields.length < 2) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            String name = URLEncodeUtils.decodeUtf8(fields[0]);
            String value = URLEncodeUtils.decodeUtf8(fields[1]);
            name2value.put(name, value);
        }
        username = name2value.get("username");
        password = name2value.get("password");
        localeStr = name2value.get("locale");
    } else {
        throw new IllegalStateException("Unsupported content type: " + contentType);
    }

    doLogin(username, password, localeStr, request, response);
}

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

@RequestMapping(value = Routes.RETAIL_CUSTOMER_COLLECTION, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody//from w  ww . j av  a  2s .co  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 {
        exportService.exportRetailCustomers(subscriptionId, response.getOutputStream(),
                new ExportFilter(params));
    } catch (Exception e) {
        System.out.printf("***** Error Caused by RetailCustomer.x.IndentifiedObject need: %s", e.toString());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.samaxes.javax.rs.validation.PersonsIT.java

@Test
@RunAsClient//w w w  .  j a v  a  2 s . c  om
@InSequence(20)
public void shouldReturnAValidationErrorWhenGettingAPerson(@ArquillianResource URL baseURL) {
    Client client = ClientBuilder.newBuilder().register(JacksonJsonProvider.class).build();
    Response response = client.target(baseURL + "r/persons/{id}").resolveTemplate("id", "test")
            .request(MediaType.APPLICATION_JSON).header("Accept-Language", "en").get();
    response.bufferEntity();

    logResponse("shouldReturnAValidationErrorWhenGettingAPerson", response);
    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
}

From source file:com.github.fge.jsonschema.servlets.SyntaxValidateServlet.java

@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Set<String> params = Sets.newHashSet();

    /*//from w w  w . jav  a  2 s  . co m
     * First, check our parameters
     */
    /*
     * Why, in 2013, doesn't servlet-api provide an Iterator<String>?
     *
     * Well, at least, Jetty's implementation has a generified Enumeration.
     * Still, that sucks.
     */
    final Enumeration<String> enumeration = req.getParameterNames();

    // FIXME: no duplicates, it seems, but I cannot find the spec which
    // guarantees that
    while (enumeration.hasMoreElements())
        params.add(enumeration.nextElement());

    // We have required parameters
    if (!params.containsAll(Request.required())) {
        log.warn("Missing parameters! Someone using me as a web service?");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters");
        return;
    }

    // We don't want extraneous parameters
    params.removeAll(Request.valid());

    if (!params.isEmpty()) {
        log.warn("Invalid parameters! Someone using me as a web service?");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameters");
        return;
    }

    final String rawSchema = req.getParameter(Request.SCHEMA);

    // Set correct content type
    resp.setContentType(MediaType.JSON_UTF_8.toString());

    final JsonNode ret;
    try {
        ret = buildResult(rawSchema);
    } catch (ProcessingException e) {
        // Should not happen!
        log.error("Uh, syntax validation failed!", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    final OutputStream out = resp.getOutputStream();

    try {
        out.write(ret.toString().getBytes(Charset.forName("UTF-8")));
        out.flush();
    } finally {
        Closeables.closeQuietly(out);
    }
}

From source file:de.yaio.services.metaextract.server.controller.MetaExtractController.java

@ExceptionHandler(PermissionException.class)
public void handleCustomException(final HttpServletRequest request, final PermissionException e,
        final HttpServletResponse response) throws IOException {
    LOGGER.info("PermissionException while running request:" + createRequestLogMessage(request), e);
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.getWriter()/*  w  ww  . j ava 2  s .c om*/
            .append("permission denied (firewall...) while extracting metadata for requested resource");
}

From source file:ch.entwine.weblounge.test.harness.rest.SearchEndpointTest.java

/**
 * Performs a search request for existing content.
 * /*from  www  . j  a v  a  2 s.  co m*/
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void searchExisting(String serverUrl) throws Exception {
    logger.info("Preparing test of search rest api");

    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/search");

    // Prepare the request
    logger.info("Searching for a page");
    HttpGet searchRequest = new HttpGet(requestUrl);

    // Send the request. The response should be a 400 (bad request)
    logger.debug("Sending empty get request to {}", searchRequest.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, null);
        assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());
        assertEquals(0, response.getEntity().getContentLength());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for search terms that don't yield a result
    String searchTerms = "xyz";
    httpClient = new DefaultHttpClient();
    searchRequest = new HttpGet(UrlUtils.concat(requestUrl, searchTerms));
    logger.info("Sending search request for '{}' to {}", searchTerms, requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, null);
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Document xml = TestUtils.parseXMLResponse(response);
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@documents"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@hits"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@offset"));
        assertEquals("1", XPathHelper.valueOf(xml, "/searchresult/@page"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@pagesize"));
        assertEquals("0", XPathHelper.valueOf(xml, "count(/searchresult/result)"));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for search terms that should yield a result
    searchTerms = "Friedrich Nietzsche Suchresultat";
    httpClient = new DefaultHttpClient();
    searchRequest = new HttpGet(UrlUtils.concat(requestUrl, URLEncoder.encode(searchTerms, "utf-8")));
    String[][] params = new String[][] { { "limit", "5" } };
    logger.info("Sending search request for '{}' to {}", searchTerms, requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Document xml = TestUtils.parseXMLResponse(response);
        assertEquals("5", XPathHelper.valueOf(xml, "/searchresult/@documents"));
        assertEquals("5", XPathHelper.valueOf(xml, "/searchresult/@hits"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@offset"));
        assertEquals("1", XPathHelper.valueOf(xml, "/searchresult/@page"));
        assertEquals("5", XPathHelper.valueOf(xml, "/searchresult/@pagesize"));
        assertEquals("5", XPathHelper.valueOf(xml, "count(/searchresult/result)"));
        assertEquals("4bb19980-8f98-4873-a813-000000000006",
                XPathHelper.valueOf(xml, "/searchresult/result/id"));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for exact matches on subjects
    String[] exactMatches = { "Search Topic A", "Search Topic B" };
    for (String searchTerm : exactMatches) {

        // Full match
        httpClient = new DefaultHttpClient();
        searchRequest = new HttpGet(UrlUtils.concat(requestUrl, URLEncoder.encode(searchTerms, "utf-8")));
        params = new String[][] { { "limit", "5" } };
        logger.info("Sending search request for exact match of '{}' to {}", searchTerm, requestUrl);
        try {
            HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document xml = TestUtils.parseXMLResponse(response);
            int documentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
            int hitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
            Assert.assertTrue(documentCount == 5);
            Assert.assertTrue(hitCount == 5);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

    }

    // Check for partial matches in fields that should be supporting partial
    // matches
    String[] partialSearchTerms = { "Kurzer Seitentitel", // German title
            "Il titre de la page", // French title
            "Lange Beschreibung", // German description
            "Dscription longue", // French description
            "Hans Muster", // creator, publisher
            "Amlie Poulard", // modifier
            "Friedrich Nietzsche Suchresultat", // element text
            "Ein amsanter Titel", // German element text
            "Un titre joyeux" // French element text
    };

    for (String searchTerm : partialSearchTerms) {
        int fullMatchDocumentCount = 0;
        int fullMatchHitCount = 0;

        // Full match
        httpClient = new DefaultHttpClient();
        searchRequest = new HttpGet(UrlUtils.concat(requestUrl, URLEncoder.encode(searchTerms, "utf-8")));
        params = new String[][] { { "limit", "5" } };
        logger.info("Sending search request for full match of '{}' to {}", searchTerm, requestUrl);
        try {
            HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document xml = TestUtils.parseXMLResponse(response);
            fullMatchDocumentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
            fullMatchHitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
            Assert.assertTrue(fullMatchDocumentCount >= 1);
            Assert.assertTrue(fullMatchHitCount >= fullMatchDocumentCount);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        // Full match lowercase
        httpClient = new DefaultHttpClient();
        String lowerCaseSearchTerm = searchTerm.toLowerCase();
        searchRequest = new HttpGet(
                UrlUtils.concat(requestUrl, URLEncoder.encode(lowerCaseSearchTerm, "utf-8")));
        params = new String[][] { { "limit", "5" } };
        logger.info("Sending search request for lowercase match of '{}' to {}", searchTerm, requestUrl);
        try {
            HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document xml = TestUtils.parseXMLResponse(response);
            int documentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
            int hitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
            Assert.assertTrue(documentCount >= fullMatchDocumentCount);
            Assert.assertTrue(hitCount >= fullMatchHitCount);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        // Partial match
        for (String partialSearchTerm : StringUtils.split(searchTerm)) {
            httpClient = new DefaultHttpClient();
            searchRequest = new HttpGet(
                    UrlUtils.concat(requestUrl, URLEncoder.encode(partialSearchTerm, "utf-8")));
            params = new String[][] { { "limit", "5" } };
            logger.info("Sending search request for partial match of '{}' to {}", searchTerm, requestUrl);
            try {
                HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
                Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
                Document xml = TestUtils.parseXMLResponse(response);
                int documentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
                int hitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
                Assert.assertTrue(documentCount > 0);
                Assert.assertTrue(hitCount > 0);
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
    }

}

From source file:be.fedict.trust.service.ocsp.OCSPResponderServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String contentType = request.getContentType();
    if (false == OCSP_REQUEST_CONTENT_TYPE.equals(contentType)) {
        LOG.error("incorrect content type: " + contentType);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;//from w  w  w  . j  a  v  a 2 s. co m
    }

    InputStream ocspRequestInputStream = request.getInputStream();
    OCSPReq ocspReq = new OCSPReq(ocspRequestInputStream);

    Req[] requestList = ocspReq.getRequestList();
    if (1 != requestList.length) {
        LOG.error("OCSP request list size not 1: " + requestList.length);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    Req ocspRequest = requestList[0];

    CertificateID certificateID = ocspRequest.getCertID();
    LOG.debug("certificate Id hash algo OID: " + certificateID.getHashAlgOID());
    if (false == CertificateID.HASH_SHA1.equals(certificateID.getHashAlgOID())) {
        LOG.debug("only supporting SHA1 hash algo");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    BigInteger serialNumber = certificateID.getSerialNumber();
    byte[] issuerNameHash = certificateID.getIssuerNameHash();
    byte[] issuerKeyHash = certificateID.getIssuerKeyHash();
    LOG.debug("serial number: " + serialNumber);
    LOG.debug("issuer name hash: " + new String(Hex.encodeHex(issuerNameHash)));
    LOG.debug("issuer key hash: " + new String(Hex.encodeHex(issuerKeyHash)));

    Date revocationDate = this.validationService.validate(serialNumber, issuerNameHash, issuerKeyHash);

    PrivateKeyEntry privateKeyEntry = this.validationService.getPrivateKeyEntry();
    if (null == privateKeyEntry) {
        LOG.debug("missing service identity");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    PublicKey publicKey = certificate.getPublicKey();
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    try {
        BasicOCSPRespGenerator basicOCSPRespGenerator = new BasicOCSPRespGenerator(publicKey);
        CertificateStatus certificateStatus;
        if (null == revocationDate) {
            certificateStatus = CertificateStatus.GOOD;
        } else {
            certificateStatus = new RevokedStatus(revocationDate, CRLReason.unspecified);
        }
        basicOCSPRespGenerator.addResponse(certificateID, certificateStatus);
        BasicOCSPResp basicOCSPResp = basicOCSPRespGenerator.generate("SHA1WITHRSA", privateKey, null,
                new Date(), BouncyCastleProvider.PROVIDER_NAME);
        OCSPRespGenerator ocspRespGenerator = new OCSPRespGenerator();
        OCSPResp ocspResp = ocspRespGenerator.generate(OCSPRespGenerator.SUCCESSFUL, basicOCSPResp);
        response.setContentType("application/ocsp-response");
        response.getOutputStream().write(ocspResp.getEncoded());
    } catch (Exception e) {
        LOG.error("OCSP generator error: " + e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
}