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.rsginer.spring.controllers.RestaurantesController.java

@RequestMapping(value = { "/random-restaurante" }, method = RequestMethod.GET, produces = "application/json")
public void getRestauranteRandom(HttpServletRequest httpResquest, HttpServletResponse httpServletResponse) {
    try {//w w w. ja  va 2 s  .c  om
        Restaurante restaurante = restaurantesDAO.getRandom();
        String jsonSalida = jsonTransformer.toJson(restaurante);
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().println(jsonSalida);
    } catch (BussinessException ex) {
        List<BussinessMessage> bussinessMessages = ex.getBussinessMessages();
        String jsonSalida = jsonTransformer.toJson(bussinessMessages);
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
}

From source file:com.vmware.identity.samlservice.impl.LogoutStateValidator.java

/**
 * Validate LogoutResponse//from  w  w w. j  av  a2s.  c o m
 *
 * @param vr
 * @param accessor
 * @param response
 * @return
 */
private com.vmware.identity.samlservice.SamlValidator.ValidationResult validateLogoutResponse(
        com.vmware.identity.samlservice.SamlValidator.ValidationResult vr, IdmAccessor accessor,
        LogoutResponse response, SessionManager sm) {
    Validate.notNull(response.getIssuer());

    // Validate single logout service first, if that is valid, we can send
    // SAML replies
    try {
        @SuppressWarnings("unused")
        String acsUrl = accessor.getSloForRelyingParty(response.getIssuer().getValue(),
                OasisNames.HTTP_REDIRECT);
    } catch (IllegalStateException e) {
        // set validation result to 400
        log.debug("Caught illegal state exception while Validating " + e.toString() + ", returning 400");
        vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null);
    }

    // Validate ID
    if (vr == null && response.getID() == null) {
        vr = new ValidationResult(OasisNames.REQUESTER);
        log.debug("Validation FAILED - Request ID is missing");
    }

    // Validate version
    if (vr == null) {
        SAMLVersion version = response.getVersion();
        if ((version.getMajorVersion() > Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                        && version.getMinorVersion() > Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
            // version too high
            vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_HIGH);
            log.debug("Validation FAILED - Version is too high");
        } else if ((version.getMajorVersion() < Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                        && version.getMinorVersion() < Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
            // version too low
            vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_LOW);
            log.debug("Validation FAILED - Version is too low");
        }
    }

    // Validate IssueInstant
    if (vr == null) {
        DateTime dtPlus = response.getIssueInstant();
        DateTime dtMinus = response.getIssueInstant();
        DateTime instant = new DateTime();
        long clockTolerance = accessor.getClockTolerance();
        if (dtPlus == null) {
            vr = new ValidationResult(OasisNames.REQUESTER);
            log.debug("Validation FAILED - Issue Instant is missing");
        } else {
            dtPlus = dtPlus.plus(clockTolerance);
            dtMinus = dtMinus.minus(clockTolerance);
            // dtPlus must be after now and dtMinus must be before now
            // in order to satisfy clock tolerance
            if (dtPlus.isBefore(instant) || dtMinus.isAfter(instant)) {
                vr = new ValidationResult(OasisNames.REQUESTER);
                log.debug("Validation FAILED - Issue Instant outside of clock tolerance");
                log.debug("clockTolerance {} ", clockTolerance);
                log.debug("now {}", instant);
                log.debug("dtPlus {}", dtPlus.toString());
                log.debug("dtMinus {}", dtMinus.toString());
            }
        }
    }

    // Destination URL skipped, this is already done by OpenSAML when
    // parsing

    // validate inResponseTo (which is the corresponding SLO request ID that
    // this response is targetting at)
    if (vr == null) {
        String inResponseTo = response.getInResponseTo();
        if (inResponseTo == null) {
            vr = new ValidationResult(OasisNames.REQUESTER);
            log.debug("Validation FAILED - inResponseTo is missing");
        } else {
            // try to find a session by LogoutRequest id that we have
            Session session = sm.getByLogoutRequestId(inResponseTo);
            if (session == null) {
                // No session found using the SLO request ID. This could
                // happen due to
                // fail-over (node switch). So here we ignore rather than
                // throw error at browser
                log.info(
                        "Unable to identify a session the SLO response is referring to. This could be caused by site-affinity switch.");
            }
        }
    }

    // check response status code
    if (vr == null) {
        Status status = null;
        StatusCode statusCode = null;
        if (vr == null) {
            // check LogoutResponse status code here
            status = response.getStatus();
            if (status == null) {
                vr = new ValidationResult(OasisNames.REQUESTER);
                log.debug("Validation FAILED - unable to find status code");
            }
        }
        if (vr == null) {
            statusCode = status.getStatusCode();
            if (statusCode == null) {
                vr = new ValidationResult(OasisNames.REQUESTER);
                log.debug("Validation FAILED - unable to find status code");
            }
        }
        if (vr == null) {
            String code = statusCode.getValue();
            if (!OasisNames.SUCCESS.equals(code)) {
                vr = new ValidationResult(OasisNames.SUCCESS, OasisNames.PARTIAL_LOGOUT);
                log.debug("Validation FAILED - partially logged out session");
            }
        }
    }

    // validation done
    if (vr == null) {
        vr = new ValidationResult(); // success
    }
    return vr;
}

From source file:de.mpg.mpdl.inge.syndication.presentation.RestServlet.java

/**
 * {@inheritDoc}/*  w  w  w.j  a v  a  2 s.  co m*/
 */
@Override
protected final void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String url = null;
    try {
        url = PropertyReader.getProperty("escidoc.syndication.service.url") + req.getServletPath()
                + req.getPathInfo();
    } catch (Exception e) {
        handleException(e, resp);
    }
    String q = req.getQueryString();

    if (Utils.checkVal(q)) {
        url += "?" + q;
    }

    Feed feed = synd.getFeeds().matchFeedByUri(url);

    // set correct mime-type
    resp.setContentType("application/" + (url.contains("rss_") ? "rss" : "atom") + "+xml; charset=utf-8");

    // cache handling
    String ttl = feed.getCachingTtl();

    if (Utils.checkVal(ttl)) {
        long ttlLong = Long.parseLong(ttl) * 1000L;
        resp.setHeader("control-cache", "max-age=" + ttl + ", must-revalidate");

        DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        resp.setHeader("Expires", df.format(new Date(System.currentTimeMillis() + ttlLong)));
    }

    try {
        synd.getFeed(url, resp.getWriter());
    } catch (SyndicationException e) {
        handleException(e, resp);
    } catch (URISyntaxException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong URI syntax: " + url);
        return;
    } catch (FeedException e) {
        handleException(e, resp);
    }

}

From source file:eu.rethink.lhcb.broker.servlet.WellKnownServlet.java

private void handleRequest(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    // add header for cross domain stuff
    resp.addHeader("Access-Control-Allow-Origin", "*");
    String host = req.getHeader("X-Forwarded-Host");
    if (host == null)
        host = req.getHeader("Host");

    // setting external host here helps BrokerWebSocketListener to return info about HTTP interface
    // Broker might not know how it is accessible. This is a workaround for it
    LHCBBroker.externalHost = host;/*from  ww w  .j av a 2s.co m*/
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.start(() -> {
        ServletRequest aReq = asyncContext.getRequest();
        String payload = null;
        try {
            payload = IOUtils.toString(aReq.getReader());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String finalPayload = payload;

        Map<String, String[]> params = aReq.getParameterMap();
        LOG.debug("payload: {}\r\nparams: {}", payload, params);

        RequestCallback cb = new RequestCallback() {

            @Override
            public void response(Message msg) {
                resp.setStatus(HttpServletResponse.SC_OK);
                try {
                    asyncContext.getResponse().getWriter().write(msg.toString());
                    asyncContext.getResponse().getWriter().flush();
                    asyncContext.complete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Exception e) {
                String error = "Request failed.\r\npayload: " + finalPayload + "\r\nparams: " + params;
                LOG.error(error + "\r\nreason: " + e.getLocalizedMessage(),
                        e instanceof InvalidMessageException ? null : e);
                if (e instanceof InvalidMessageException) {
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                } else {
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

                }
                completeAsyncContext(asyncContext, error + "\r\nreason: " + e.getLocalizedMessage());
            }
        };

        try {
            Message msg = null;

            if (payload.length() > 0) {
                msg = Message.fromString(payload);
            } else {
                msg = Message.fromParams(params);
            }

            requestHandler.handleRequest(msg, cb);
        } catch (InvalidMessageException e) {
            cb.error(e);
        }
    });
}

From source file:com.bigdata.rdf.sail.webapp.UpdateServlet.java

@Override
protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {

    if (!isWritable(getServletContext(), req, resp)) {
        // Service must be writable.
        return;/*from www .j a  v a2s.co m*/
    }

    final String queryStr = req.getParameter(QueryServlet.ATTR_QUERY);

    final String contentType = req.getContentType();

    if (contentType == null) {

        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    }

    if (queryStr == null) {

        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    }

    doUpdateWithQuery(req, resp);

}

From source file:io.lavagna.web.security.login.PersonaLoginTest.java

@Test
public void verifierWrongAudience() throws IOException {
    prepareSuccessfulPreconditions();//from ww  w. jav a2s . c o  m

    VerifierResponse verifier = new VerifierResponse();
    verifier.setStatus("okay");
    verifier.setAudience("wrongOne");
    when(restTemplate.postForObject(any(String.class), any(), eq(VerifierResponse.class))).thenReturn(verifier);

    Assert.assertTrue(personaLogin.doAction(req, resp));
    verify(resp).setStatus(HttpServletResponse.SC_BAD_REQUEST);
}

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

@RequestMapping(value = Routes.ROOT_METER_READING_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody//from   ww  w.  j  ava  2  s .c o  m
public void show(HttpServletRequest request, HttpServletResponse response, @PathVariable Long meterReadingId,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    Long subscriptionId = getSubscriptionId(request);

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    try {
        exportService.exportMeterReading_Root(subscriptionId, meterReadingId, response.getOutputStream(),
                new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

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

@RequestMapping(value = Routes.RETAIL_CUSTOMER_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody/*from  ww w  . ja v  a 2s.  c  om*/
public void show(HttpServletRequest request, HttpServletResponse response, @PathVariable Long retailCustomerId,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    Long subscriptionId = getSubscriptionId(request);

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    try {
        exportService.exportRetailCustomer(subscriptionId, retailCustomerId, 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.vmware.identity.samlservice.impl.AuthnRequestStateValidator.java

@Override
public ValidationResult validate(AuthnRequestState t) {
    log.debug("Validating request {}", t);

    ValidationResult vr = null;//ww  w.j a  va 2s .c om

    try {
        Validate.notNull(t);

        HttpServletRequest httpRequest = t.getRequest();
        Validate.notNull(httpRequest);

        AuthnRequest request = t.getAuthnRequest();
        Validate.notNull(request);
        Validate.notNull(request.getIssuer());

        IdmAccessor accessor = t.getIdmAccessor();
        Validate.notNull(accessor);
        Validate.notNull(accessor.getTenant());

        // Validate assertion consumer service first, if that is valid, we can send SAML replies
        try {
            boolean validateACSWithMetadata = !this.isRequestSigned(t);
            String acsUrl = accessor.getAcsForRelyingParty(request.getIssuer().getValue(),
                    request.getAssertionConsumerServiceIndex(), request.getAssertionConsumerServiceURL(),
                    request.getProtocolBinding(), validateACSWithMetadata);

            t.setAcsUrl(acsUrl);
        } catch (IllegalStateException e) {
            // set validation result to 400
            log.debug("Caught illegal state exception while Validating {} returning 400", e.toString());
            vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null);
        }

        // Validate ID
        if (vr == null && request.getID() == null) {
            vr = new ValidationResult(OasisNames.REQUESTER);
            log.debug("Validation FAILED - Request ID is missing");
        }

        // Validate version
        if (vr == null) {
            SAMLVersion version = request.getVersion();
            if ((version.getMajorVersion() > Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                    || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                            && version.getMinorVersion() > Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
                // version too high
                vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_HIGH);
                log.debug("Validation FAILED - Version is too high");
            } else if ((version.getMajorVersion() < Shared.REQUIRED_SAML_VERSION.getMajorVersion())
                    || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                            && version.getMinorVersion() < Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
                // version too low
                vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_LOW);
                log.debug("Validation FAILED - Version is too low");
            }
        }

        // Validate IssueInstant only if this is a new request (i.e. it had not pass been validated)
        if (vr == null && !t.isExistingRequest()) {
            DateTime dtPlus = request.getIssueInstant();
            DateTime dtMinus = request.getIssueInstant();
            DateTime instant = new DateTime();
            long clockTolerance = accessor.getClockTolerance();
            if (dtPlus == null) {
                vr = new ValidationResult(OasisNames.REQUESTER);
                log.debug("Validation FAILED - Issue Instant is missing");
            } else {
                dtPlus = dtPlus.plus(clockTolerance);
                dtMinus = dtMinus.minus(clockTolerance);
                // dtPlus must be after now and dtMinus must be before now
                //   in order to satisfy clock tolerance
                if (dtPlus.isBefore(instant) || dtMinus.isAfter(instant)) {
                    vr = new ValidationResult(OasisNames.REQUESTER);
                    log.debug("Validation FAILED - Issue Instant outside of clock tolerance");
                    log.debug("clockTolerance {}", clockTolerance);
                    log.debug("now {}", instant);
                    log.debug("dtPlus {}", dtPlus.toString());
                    log.debug("dtMinus {}", dtMinus.toString());
                }
            }
        }

        // Destination URL skipped, this is already done by OpenSAML when parsing

        // validate scoping if presenet
        if (vr == null) {
            vr = validateScoping(t);
        }

        // signature must NOT be included
        if (vr == null) {
            if (request.getSignature() != null) {
                log.debug("Validation FAILED - Signature MUST NOT be present");
                vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.REQUEST_UNSUPPORTED);
            }
        }

        // ensure that we don't accept unsigned requests if configuration requires signing
        if (vr == null) {

            try {
                boolean mustBeSigned = accessor
                        .getAuthnRequestsSignedForRelyingParty(request.getIssuer().getValue());
                this.validateSigning(mustBeSigned, t);
            } catch (IllegalStateException e) {
                // set validation result to request denied
                log.error("Validation FAILED - unsigned request detected, signing required");
                vr = new ValidationResult(OasisNames.RESPONDER, OasisNames.REQUEST_DENIED);
            }
        }

        // validate NameIDPolicy if present
        if (vr == null) {
            NameIDPolicy policy = request.getNameIDPolicy();
            if (policy != null) {
                String format = policy.getFormat();
                if (format != null && !format.equals(OasisNames.PERSISTENT)
                        && !format.equals(OasisNames.EMAIL_ADDRESS)
                        && !format.equals(SAMLNames.IDFORMAT_VAL_UPN.toString())) {
                    log.error("Validation FAILED - unknown NameIDPolicy Format");
                    vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.INVALID_NAMEID_POLICY);
                }
            }
        }

        // validate conditions
        if (vr == null) {
            Conditions conditions = request.getConditions();
            if (conditions != null) {
                // notBefore processing
                DateTime notBefore = conditions.getNotBefore();
                if (notBefore != null) {
                    // no additional validation, we'll use whatever client wants
                    t.setStartTime(notBefore.toDate());
                }
                // delegable and renewable conditions
                for (Condition c : conditions.getConditions()) {
                    if (c == null) {
                        continue;
                    }
                    if (c instanceof RenewableType) {
                        t.setRenewable(true);
                    }
                    if (c instanceof DelegableType) {
                        t.setDelegable(true);
                    }
                }
            }
        }
        if (vr == null) {
            computeSupportedAuthnTypes(t, request);
        }

        // validation done
        if (vr == null) {
            log.info("Authentication request validation succeeded");
            vr = new ValidationResult(); // success

            // check if we need to convert a principal into emailAddress
            if (request.getNameIDPolicy() != null && request.getNameIDPolicy().getFormat() != null
                    && request.getNameIDPolicy().getFormat().equals(OasisNames.EMAIL_ADDRESS)) {
                t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_EMAIL_ADDRESS);
            } else {
                t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_UPN);
            }
        }

    } catch (Exception e) {
        vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null);
        log.debug("Caught exception while Validating " + e.toString() + ", returning 400");
    }
    return vr;
}

From source file:de.mpg.escidoc.services.syndication.presentation.RestServlet.java

/**
 * {@inheritDoc}/* w ww.j  a v  a2s  . c om*/
 */
@Override
protected final void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String url = null;
    try {
        url = PropertyReader.getProperty("escidoc.syndication.service.url") + req.getServletPath()
                + req.getPathInfo();
    } catch (Exception e) {
        handleException(e, resp);
    }
    String q = req.getQueryString();

    if (Utils.checkVal(q)) {
        url += "?" + q;
    }

    Feed feed = synd.getFeeds().matchFeedByUri(url);

    //set correct mime-type
    resp.setContentType("application/" + (url.contains("rss_") ? "rss" : "atom") + "+xml; charset=utf-8");

    //cache handling
    String ttl = feed.getCachingTtl();

    if (Utils.checkVal(ttl)) {
        long ttlLong = Long.parseLong(ttl) * 1000L;
        resp.setHeader("control-cache", "max-age=" + ttl + ", must-revalidate");

        DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        resp.setHeader("Expires", df.format(new Date(System.currentTimeMillis() + ttlLong)));
    }

    try {
        synd.getFeed(url, resp.getWriter());
    } catch (SyndicationException e) {
        handleException(e, resp);
    } catch (URISyntaxException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong URI syntax: " + url);
        return;
    } catch (FeedException e) {
        handleException(e, resp);
    }

}