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:elw.web.StudentController.java

protected HashMap<String, Object> auth(final HttpServletRequest req, final HttpServletResponse resp,
        final boolean page, final boolean verified) throws IOException {
    final HashMap<String, Object> model = super.auth(req, resp, page, verified);

    if (model == null) {
        return null;
    }/*from   w  ww.  j  av  a2s. co  m*/

    final Auth auth = auth(model);
    final Group group = auth.getGroup();
    final Student student = auth.getStudent();
    final Admin admin = auth.getAdmin();

    Ctx ctx = Ctx.fromString(req.getParameter(R_CTX));
    ctx.resolve(queries);
    if (ctx.getGroup() == null) {
        ctx = ctx.extendGroup(group);
    }
    if (ctx.getStudent() == null) {
        ctx = ctx.extendStudent(student);
    }
    if (!ctx.resolved(Ctx.STATE_GS)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "context path problem, please check the logs");
        return null;
    }

    if (admin == null) {
        if (!ctx.getGroup().getId().equals(group.getId())) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "context path refers to another group");
            return null;
        }
        if (!ctx.getStudent().getId().equals(student.getId())) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "context path refers to another student");
            return null;
        }
    }

    model.put(R_CTX, ctx);
    //  LATER nobody knows what's this and whether it's needed at all
    model.put("expandTriggers", req.getSession().getAttribute("viewToExpandTriggers"));

    return model;

}

From source file:eu.eubrazilcc.lvl.oauth2.rest.OAuth2TokenRevocation.java

@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response revoke(final @Context HttpServletRequest request, final MultivaluedMap<String, String> form)
        throws OAuthSystemException {
    try {/*from   w  ww  .  j a  va  2  s  . c  o m*/
        final OAuthTokenRevocationRequest oauthRequest = new OAuthTokenRevocationRequest(
                new OAuth2RequestWrapper(request, form, null));

        // check if client id is valid
        if (!CLIENT_APP_DAO.isValid(oauthRequest.getClientId())) {
            final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                    .setErrorDescription(INVALID_CLIENT_DESCRIPTION).buildJSONMessage();
            return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
        }

        // check if client secret is valid
        if (!CLIENT_APP_DAO.isValid(oauthRequest.getClientId(), oauthRequest.getClientSecret())) {
            final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                    .setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)
                    .setErrorDescription(INVALID_CLIENT_DESCRIPTION).buildJSONMessage();
            return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
        }

        // do revoking for different token types
        if (isEmpty(oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN_TYPE_HINT))
                || oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN_TYPE_HINT)
                        .equals(OAuthTokenRevocationRequest.ACCESS_TOKEN)) {
            TOKEN_DAO.delete(oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN));
        } else if (oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN_TYPE_HINT)
                .equals(OAuthTokenRevocationRequest.REFRESH_TOKEN)) {
            // refresh token is not supported in this implementation
            final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(UNSUPPORTED_TOKEN_TYPE_ERROR)
                    .setErrorDescription("refresh token is not supported in this implementation")
                    .buildJSONMessage();
            return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
        } else {
            final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(UNSUPPORTED_TOKEN_TYPE_ERROR)
                    .setErrorDescription("unsupported token type: "
                            + oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN_TYPE_HINT))
                    .buildJSONMessage();
            return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
        }

        return Response.status(HttpServletResponse.SC_OK).build();
    } catch (OAuthProblemException e) {
        final OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                .buildJSONMessage();
        return Response.status(res.getResponseStatus()).entity(res.getBody()).build();
    }
}

From source file:com.oneops.cms.ws.rest.DpmtRestController.java

@ExceptionHandler(DJException.class)
public void handleDJExceptions(DJException e, HttpServletResponse response) throws IOException {
    logger.error("handle DJException", e);
    sendError(response, HttpServletResponse.SC_BAD_REQUEST, e);
}

From source file:com.thoughtworks.go.domain.DirHandler.java

public boolean handleResult(int httpCode, GoPublisher goPublisher) {
    checksumValidationPublisher.publish(httpCode, destOnAgent, goPublisher);
    return httpCode < HttpServletResponse.SC_BAD_REQUEST;
}

From source file:com.hp.autonomy.frontend.find.hod.view.HodViewController.java

@ExceptionHandler
public ModelAndView handleHodErrorException(final HodErrorException e, final HttpServletRequest request,
        final HttpServletResponse response) {
    response.reset();/*w w w .j  a v a 2  s . co m*/

    log.error("HodErrorException thrown while viewing document", e);

    final String errorKey = HOD_ERROR_MESSAGE_CODE_PREFIX + e.getErrorCode();
    String hodErrorMessage;

    try {
        hodErrorMessage = controllerUtils.getMessage(errorKey, null);
    } catch (final NoSuchMessageException ignored) {
        // we don't have a key in the bundle for this error code
        hodErrorMessage = controllerUtils.getMessage(HOD_ERROR_MESSAGE_CODE_UNKNOWN, null);
    }

    final int errorCode = e.isServerError() ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
            : HttpServletResponse.SC_BAD_REQUEST;

    final String subMessageCode;
    final Object[] subMessageArgs;
    if (hodErrorMessage != null) {
        subMessageCode = HOD_ERROR_MESSAGE_CODE_SUB;
        subMessageArgs = new String[] { hodErrorMessage };
    } else {
        subMessageCode = HOD_ERROR_MESSAGE_CODE_SUB_NULL;
        subMessageArgs = null;
    }

    response.setStatus(errorCode);

    return controllerUtils.buildErrorModelAndView(new ErrorModelAndViewInfo.Builder().setRequest(request)
            .setMainMessageCode(HOD_ERROR_MESSAGE_CODE_MAIN).setSubMessageCode(subMessageCode)
            .setSubMessageArguments(subMessageArgs).setStatusCode(errorCode).setContactSupport(true)
            .setException(e).build());
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.hooks.BitbucketSCMSourcePushHookReceiver.java

/**
 * Receives Bitbucket push notifications.
 *
 * @param req Stapler request. It contains the payload in the body content
 *          and a header param "X-Event-Key" pointing to the event type.
 * @return the HTTP response object//w  ww .  j a va 2 s.  c  om
 * @throws IOException if there is any issue reading the HTTP content payload.
 */
public HttpResponse doNotify(StaplerRequest req) throws IOException {
    String origin = SCMEvent.originOf(req);
    String body = IOUtils.toString(req.getInputStream());
    String eventKey = req.getHeader("X-Event-Key");
    if (eventKey == null) {
        return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, "X-Event-Key HTTP header not found");
    }
    HookEventType type = HookEventType.fromString(eventKey);
    if (type == null) {
        LOGGER.info("Received unknown Bitbucket hook: " + eventKey + ". Skipping.");
        return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST,
                "X-Event-Key HTTP header invalid: " + eventKey);
    }

    String bitbucketKey = req.getHeader("X-Bitbucket-Type");
    String serverUrl = req.getParameter("server_url");
    BitbucketType instanceType = null;
    if (bitbucketKey != null) {
        instanceType = BitbucketType.fromString(bitbucketKey);
    }
    if (instanceType == null && serverUrl != null) {
        LOGGER.log(Level.FINE, "server_url request parameter found. Bitbucket Native Server webhook incoming.");
        instanceType = BitbucketType.SERVER;
    } else {
        LOGGER.log(Level.FINE,
                "X-Bitbucket-Type header / server_url request parameter not found. Bitbucket Cloud webhook incoming.");
    }

    try {
        type.getProcessor().process(type, body, instanceType, origin, serverUrl);
    } catch (AbstractMethodError e) {
        type.getProcessor().process(body, instanceType);
    }
    return HttpResponses.ok();
}

From source file:net.duckling.ddl.web.agent.csp.CspBaseController.java

public void writeError(ErrorMsg msg, HttpServletRequest request, HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    JsonUtil.writeJSONP(request, response, msg, null);
}

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

@RequestMapping(value = "/{variantId}/info", method = RequestMethod.GET)
//    @ApiOperation(httpMethod = "GET", value = "Retrieves the information about a variant", response = QueryResponse.class)
public QueryResponse getVariantById(@PathVariable("variantId") String variantId,
        @RequestParam(name = "studies", required = false) List<String> studies,
        @RequestParam("species") String species, HttpServletResponse response)
        throws IllegalOpenCGACredentialsException, UnknownHostException, IOException {
    initializeQueryOptions();//  w ww  .  j  a va2  s .com

    VariantDBAdaptor variantMongoDbAdaptor = DBAdaptorConnector.getVariantDBAdaptor(species);

    if (studies != null && !studies.isEmpty()) {
        queryOptions.put("studies", studies);
    }

    if (!variantId.contains(":")) { // Query by accession id
        return setQueryResponse(variantMongoDbAdaptor.getVariantById(variantId, queryOptions));
    } else { // Query by chr:pos:ref:alt
        String parts[] = variantId.split(":", -1);
        if (parts.length < 3) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return setQueryResponse(
                    "Invalid position and alleles combination, please use chr:pos:ref or chr:pos:ref:alt");
        }

        Region region = new Region(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[1]));
        queryOptions.put("reference", parts[2]);
        if (parts.length > 3) {
            queryOptions.put("alternate", String.join(":", Arrays.copyOfRange(parts, 3, parts.length)));
        }

        return setQueryResponse(variantMongoDbAdaptor.getAllVariantsByRegion(region, queryOptions));
    }
}

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

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter(SERVICE_PARAMETER) == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request Parameter 'service' is required.");
        return;//  ww w .j ava2  s . co m
    }

    User user = getRegistry().createOrGetUser(new PirasoHttpServletRequest(request));

    if (SERVICE_GET_REGISTRY_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        retrieveRegistry(response);
    } else if (SERVICE_LOG_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        log(request);
        writeResponse(response, PLAIN_CONTENT_TYPE, "OK");
    } else if (SERVICE_REQUEST_ID_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        writeResponse(response, PLAIN_CONTENT_TYPE, String.valueOf(PirasoContextIDGenerator.INSTANCE.next()));
    } else if (SERVICE_START_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        startLoggerService(request, response, user);
    } else if (SERVICE_STOP_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        stopService(response, user);
        writeResponse(response, PLAIN_CONTENT_TYPE, "OK");
    } else if (SERVICE_TEST_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        writeResponse(response, JSON_CONTENT_TYPE, String.format(
                "{\"status\":\"%s\", \"version\":\"%s\", \"bridgeSupported\": true}", STATUS_OK, version));
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                String.format("Request Parameter 'service' with value '%s' is invalid.",
                        request.getParameter(SERVICE_PARAMETER)));
    }
}

From source file:org.wwarn.cms.authentication.LoginCas.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
    // Extract username
    String username = req.getParameter("u");
    if (username == null || username.length() == 0) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
    }//from  w  w  w.j  a v a2s .c o  m
    // Extract CAS ticket
    String ticket = req.getParameter("t");
    if (ticket == null) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Ticket not specified");
    }

    try {
        // Add ticket to model for javascript and template access
        Map<String, Object> model = new HashMap<String, Object>(7, 1.0f);

        // Validate our proxy CAS ticket
        Cas20ProxyTicketValidator tv = new Cas20ProxyTicketValidator(CAS_WEBAPP_URL);
        tv.setAcceptAnyProxy(true);
        String legacyServerServiceUrl = ALFRESCO_WEBAPP_URL;
        Assertion assertion = tv.validate(ticket, legacyServerServiceUrl);
        String cas_username = assertion.getPrincipal().getName();

        // Compare usernames
        if (!username.equals(assertion.getPrincipal().getName())) {
            throw new TicketValidationException("usernames does not match: " + username + "/" + cas_username);
        }

        // Authenticate our user
        authenticationComponent.setCurrentUser(username);

        // Create a new alfresco ticket
        String alfticket = authenticationService.getCurrentTicket();
        model.put("ticket", alfticket);

        return model;
    } catch (AuthenticationException e) {
        throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "Login failed");
    } catch (TicketValidationException ex) {
        ex.printStackTrace();
    } finally {
        authenticationService.clearCurrentSecurityContext();
    }

    return null;
}