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.myjerry.evenstar.web.feed.FeedController.java

public ModelAndView view(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String uri = request.getRequestURI();
    FeedFormat feedFormat = null;//from  ww w  .  j a v  a  2  s.  com

    // strip off the 'feeds/' from the URI
    uri = uri.substring(7);
    int extIndex = uri.lastIndexOf(".");
    if (extIndex != -1) {
        String extension = uri.substring(extIndex + 1);
        uri = uri.substring(0, extIndex);
        feedFormat = FeedFormat.getFeedFormat(extension);
    }

    if (feedFormat == null) {
        // bad request
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    Long blogID = this.blogService.getBlogIDForServerName(request.getServerName());
    if (blogID == null) {
        // try and see if the URI contains the blog ID
        String alias = uri;
        int index = uri.indexOf("/");
        if (index != -1) {
            alias = uri.substring(0, index);
        }
        Long id = this.blogService.getBlogIDForAlias(alias);
        if (id != null) {
            blogID = id;
            uri = uri.substring(index + 1);
        } else {
            // just can't do anything now
            // no feed found
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }
    }

    // decipher the type of feed
    if ("posts/default".equals(uri)) {
        return blogPostsFeed(feedFormat, blogID);
    } else if ("comments/default".equals(uri)) {
        return blogCommentsFeed(feedFormat, blogID);
    } else if (uri.startsWith("posts/")) {
        // try and get the post ID from this
        uri = uri.substring(6);
        int index = uri.indexOf("/");
        if (index != -1) {
            Long postID = StringUtils.getLong(uri.substring(0, index));
            if (postID != null) {
                uri = uri.substring(index + 1);
                if ("default".equals(uri)) {
                    return blogPostFeed(feedFormat, blogID, postID);
                } else if ("comments".equals(uri)) {
                    return blogPostCommentFeed(feedFormat, blogID, postID);
                }
            }
        }
    }

    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return null;
}

From source file:com.cloudera.oryx.als.serving.web.RecommendToAnonymousServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
        return;//w  ww.  j a  va 2 s.com
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    Pair<String[], float[]> itemIDsAndValue;
    try {
        itemIDsAndValue = parseItemValuePairs(pathComponents);
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    }

    if (itemIDsAndValue.getFirst().length == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No items");
        return;
    }

    String[] itemIDs = itemIDsAndValue.getFirst();
    float[] values = itemIDsAndValue.getSecond();

    OryxRecommender recommender = getRecommender();
    RescorerProvider rescorerProvider = getRescorerProvider();
    try {
        Rescorer rescorer = rescorerProvider == null ? null
                : rescorerProvider.getRecommendToAnonymousRescorer(itemIDs, recommender,
                        getRescorerParams(request));
        output(response, recommender.recommendToAnonymous(itemIDs, values, getHowMany(request), rescorer));
    } catch (NotReadyException nre) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (NoSuchItemException nsie) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
    }
}

From source file:com.quancheng.saluki.gateway.zuul.filter.LimitAccessFilter.java

@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    String auth = request.getHeader("Authorization");
    String accessToken = auth.split(" ")[1];
    ctx.set("LimitAccess", Boolean.TRUE);
    try {/* ww w.j av a  2  s.c o  m*/
        Triple<Long, String, Long> clientTriple = databaseUserDetailService.loadClientByToken(accessToken);
        String user = clientTriple.getMiddle();
        Long intervalInMills = clientTriple.getLeft();
        Long limits = clientTriple.getRight();
        if (intervalInMills != null && intervalInMills != 0l && limits != null && limits != 0l) {
            if (!access(user, intervalInMills, limits)) {
                ctx.set("LimitAccess", Boolean.FALSE);
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(HttpServletResponse.SC_BAD_REQUEST);
                ctx.setResponseBody("The times of usage is limited");
            }
        }
    } catch (Throwable e) {
    }
    return null;
}

From source file:com.imaginary.home.cloud.api.call.RelayCall.java

@Override
public void post(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {//from w  w  w .  j ava  2  s. co m
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());

        if (!object.has("pairingCode") || object.isNull("pairingCode")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        String code = object.getString("pairingCode");

        if (code.equalsIgnoreCase("null")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        Location location = Location.findForPairing(code);

        if (location == null) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PAIRING_CODE,
                    "Invalid pairing code; pairing did not occur");
        }
        String relayName;

        if (object.has("name") && !object.isNull("name")) {
            relayName = object.getString("name");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA,
                    "Missing relay name from JSON");
        }
        ControllerRelay relay = location.pair(code, relayName);

        if (relay == null) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.PAIRING_FAILURE,
                    "Pairing failed due to an invalid pairing code or expired pairing code");
        }
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("apiKeyId", relay.getControllerRelayId());
        json.put("apiKeySecret", Configuration.decrypt(location.getLocationId(), relay.getApiKeySecret()));
        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.getWriter().println((new JSONObject(json)).toString());
        resp.getWriter().flush();
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in body");
    } catch (PersistenceException e) {
        e.printStackTrace();
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                "Internal database error");
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.web.template.ExportActivitiesController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String identifier = extractIdentifier(request.getPathInfo(), ID_PATTERN);
    String fullPath = request.getPathInfo();
    String extension = fullPath.substring(fullPath.lastIndexOf(".") + 1).toLowerCase();

    if (identifier == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not extract study identifier");
        return null;
    }/*from  www  .  ja va 2 s.  c  o  m*/
    Source source = sourceDao.getByName(identifier);
    if (source == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
    if (!(extension.equals("csv") || extension.equals("xls") || extension.equals("xml"))) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong extension type");
        return null;
    }
    String elt;

    if (extension.equals("xml")) {
        response.setContentType("text/xml");
        elt = activitySourceXmlSerializer.createDocumentString(source);
    } else {
        if (extension.equals("csv")) {
            response.setContentType("text/plain");
            elt = sourceSerializer.createDocumentString(source, ',');
        } else {
            response.setContentType("text");
            elt = sourceSerializer.createDocumentString(source, '\t');
        }
    }

    byte[] content = elt.getBytes();
    response.setContentLength(content.length);
    response.setHeader("Content-Disposition", "attachment");
    FileCopyUtils.copy(content, response.getOutputStream());
    return null;
}

From source file:net.myrrix.web.servlets.IngestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    MyrrixRecommender recommender = getRecommender();

    boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data");

    Reader reader;/*from w ww .j av a  2  s  . c  o m*/
    if (fromBrowserUpload) {

        Collection<Part> parts = request.getParts();
        if (parts == null || parts.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data");
            return;
        }
        Part part = parts.iterator().next();
        String partContentType = part.getContentType();
        InputStream in = part.getInputStream();
        if ("application/zip".equals(partContentType)) {
            in = new ZipInputStream(in);
        } else if ("application/gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/x-gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        } else if ("application/x-bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        }
        reader = new InputStreamReader(in, Charsets.UTF_8);

    } else {

        String charEncodingName = request.getCharacterEncoding();
        Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName);
        String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);
        if (contentEncoding == null) {
            reader = request.getReader();
        } else if ("gzip".equals(contentEncoding)) {
            reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding);
        } else if ("zip".equals(contentEncoding)) {
            reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding);
        } else if ("bzip2".equals(contentEncoding)) {
            reader = new InputStreamReader(new BZip2CompressorInputStream(request.getInputStream()),
                    charEncoding);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding");
            return;
        }

    }

    try {
        recommender.ingest(reader);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
        return;
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
        return;
    }

    String referer = request.getHeader(HttpHeaders.REFERER);
    if (fromBrowserUpload && referer != null) {
        // Parsing avoids response splitting
        response.sendRedirect(new URL(referer).toString());
    }

}

From source file:org.piraso.web.base.PirasoResponseWrapperTest.java

@Test
public void testSendError() throws Exception {
    wrapper.sendError(HttpServletResponse.SC_BAD_REQUEST);
    assertEquals(HttpServletResponse.SC_BAD_REQUEST, entry.getStatus());
}

From source file:org.dataconservancy.dcs.access.server.FileUploadServlet.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Error: Request type not supported.");
        return;/*  w  w w.  jav  a2  s.  c  om*/
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> items = upload.parseRequest(req);

        String depositurl = null;

        for (FileItem item : items) {
            if (item.getFieldName() != null && item.getFieldName().equals("depositurl")) {
                depositurl = item.getString();
            }
        }

        if (depositurl == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required paremeter: depositurl");
            return;
        }

        for (FileItem item : items) {
            String name = item.getName();

            if (item.isFormField() || name == null || name.isEmpty()) {
                continue;
            }

            uploadfile(depositurl, name, item.getInputStream(), resp);
        }
    } catch (IOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error: " + e.getMessage());
        return;
    } catch (FileUploadException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error: " + e.getMessage());
        return;
    }
}

From source file:com.conwet.silbops.connectors.comet.handlers.SubscribeResponse.java

@Override
protected void reply(HttpServletRequest req, HttpServletResponse res, PrintWriter writer,
        HttpEndPoint httpEndPoint, EndPoint connection) {
    try {//  ww w  . j  a  v  a  2  s  . co m
        String subscription = retriveParameter(req, "subscription");
        JSONObject jsonSubscription = (JSONObject) JSONValue.parseWithException(subscription);

        if (jsonSubscription.isEmpty()) {

            writeOut(writer, httpEndPoint.getEndPoint(), "subscription is empty");

        } else {

            SubscribeMsg msg = new SubscribeMsg();
            msg.setSubscription(Subscription.fromJSON(jsonSubscription));

            logger.debug("Endpoint {}, Subscribe: {}", httpEndPoint, msg);
            broker.receiveMessage(msg, connection);
            writeOut(writer, httpEndPoint.getEndPoint(), "subscribe success");
        }
    } catch (Exception ex) {
        logger.warn("subscribe exception: {}", ex.getMessage());

        try {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException ex1) {
            logger.warn("subscribe reply exception: {}", ex1.getMessage());
        }
    }
}

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

@RequestMapping("/authentication")
public Object authorize(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
    try {//  ww w  . j a  va2s.  c  om

        // OAuth ?
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);

        // id?
        if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
            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()));
        }

        Subject subject = SecurityUtils.getSubject();
        // ?
        if (!subject.isAuthenticated()) {
            if (!login(subject, request)) {// ?
                // TODO
                HttpHeaders headers = new HttpHeaders();
                headers.setLocation(new URI(loginUrl));
                return new ResponseEntity<Object>(headers, HttpStatus.UNAUTHORIZED);
            }
        }

        String username = (String) subject.getPrincipal();
        // ???
        String authorizationCode = null;
        // responseType??CODE?TOKEN
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        // OAuth?
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);
        if (responseType.equals(ResponseType.CODE.toString())) {
            authorizationCode = oauthIssuerImpl.authorizationCode();
            oAuthService.addAuthCode(authorizationCode, username);
            // ??
            builder.setCode(authorizationCode);
        } else if (responseType.equals(ResponseType.TOKEN.toString())) {
            final String accessToken = oauthIssuerImpl.accessToken();
            oAuthService.addAccessToken(accessToken, username);
            builder.setAccessToken(accessToken);
            builder.setParam("token_type", TokenType.BEARER.toString());
            builder.setExpiresIn(oAuthService.getExpireIn());
        }

        // ???
        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

        // ?
        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();

        // ?OAuthResponseResponseEntity?
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        // ?
        String redirectUri = e.getRedirectUri();
        if (OAuthUtils.isEmpty(redirectUri)) {
            // redirectUri
            return new ResponseEntity<String>("OAuth callback url needs to be provided by client!!!",
                    HttpStatus.NOT_FOUND);
        }

        // ??error=
        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e)
                .location(redirectUri).buildQueryMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    }
}