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.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController.java

@ExceptionHandler(ValidationException.class)
@ResponseBody//from  ww  w.ja v a2s. co  m
public SimpleObject validationExceptionHandler(ValidationException validationException,
        HttpServletRequest request, HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return RestUtil.wrapValidationErrorResponse(validationException);
}

From source file:de.drv.dsrv.spoc.web.webservice.spring.SpocMessageDispatcherServlet.java

@Override
protected void doService(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    try {/*from  w ww  . j  av a  2  s  . c  om*/
        if (LOG.isDebugEnabled()) {
            LOG.debug("Request eingegangen, Spring-WS-Verarbeitung wird aufgerufen.");
        }
        super.doService(request, response);
    } catch (final SaajSoapEnvelopeException ex) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Behandlung von Exception - exTRa-Error wird generiert: ", ex);
        }
        // Request enthaelt gueltiges XML, ist aber keine SOAP-Nachricht
        createExtraErrorAndWriteResponse(response, getWebApplicationContext()
                .getMessage(Messages.ERROR_REQUEST_NO_SOAP, null, request.getLocale()));
    }

    // Falls das XML im Request ungueltig ist, "verschluckt" der
    // WebServiceMessageReceiverHandlerAdapter
    // die Exception und setzt den HTTP Status auf 400.
    // Ganz sicher koennen wir hier aber nicht sein, ob das tatsaechlich die
    // Ursache ist.
    if (response.getStatus() == HttpServletResponse.SC_BAD_REQUEST) {
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("HTTP-Status 400 - exTRa-Error wird generiert.");
            }
            createExtraErrorAndWriteResponse(response, getWebApplicationContext()
                    .getMessage(Messages.ERROR_REQUEST_NO_XML, null, request.getLocale()));
        } catch (final Exception ignored) {
            // Evtl. kann nicht mehr in die Response geschrieben werden,
            // weil das vorher schon geschehen ist.
            LOG.warn("Exception beim Versuch, einen eigenen Extra-Error in die HttpResponse zu schreiben.",
                    ignored);
        }
    }
}

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

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

From source file:org.n52.ar.layar.LayarServlet.java

/**
 * http://layar.com/documentation/browser/api/getpois-request/
 *//*from w w w.  java 2  s  .  co  m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userAgent = request.getHeader("User-agent");
    log.debug("User-agent={}", userAgent);

    /*
     * mandatory:
     */
    String userId = request.getParameter("userId");
    String version = request.getParameter("version");
    String countryCode = request.getParameter("countryCode");
    String lang = request.getParameter("lang");

    String action = request.getParameter("action");
    if (action == null) {
        // response.sendError(HttpServletResponse.SC_BAD_REQUEST,
        // "Missing parameter 'action'");
        // return;
        log.debug("No action given.");
    }

    String latParam = request.getParameter("lat");
    if (latParam == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter 'lat'");
        return;
    }

    String lonParam = request.getParameter("lon");
    if (lonParam == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter 'lon'");
        return;
    }

    String radiusParam = request.getParameter("radius");
    if (radiusParam == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter 'radius'");
        return;
    }

    /*
     * optional:
     */
    String accurary = request.getParameter("accuracy");
    String pageKey = request.getParameter("pageKey");
    // String oauth_consumer_key =
    // request.getParameter("oauth_consumer_key");
    // String oauth_signature_method =
    // request.getParameter("oauth_signature_method");
    String radiolist = request.getParameter("RADIOLIST");
    String searchbox = request.getParameter("SEARCHBOX");
    String custom_slider = request.getParameter("CUSTOM_SLIDER");
    String checkboxlist = request.getParameter("CHECKBOXLIST");
    String localCountryCode = request.getParameter("localCountryCode");
    String alt = request.getParameter("alt"); // current altitude
    String recognizedReferenceImage = request.getParameter("recognizedReferenceImage");

    // convert parameters
    float lat = Float.parseFloat(latParam);
    float lon = Float.parseFloat(lonParam);
    double[] center = new double[] { lat, lon };
    float radius = Float.parseFloat(radiusParam);

    // get nearby sensors
    LayarResponse layarResponse = new LayarResponse();
    layarResponse.layer = request.getParameter("layerName");
    if (layarResponse.layer == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter 'layerName'");
        return;
    }

    response.setContentType("application/json; charset=utf-8");
    JsonGenerator generator = this.factory.createJsonGenerator(response.getWriter());
    generator.useDefaultPrettyPrinter();

    // query SIR
    try {
        Collection<SirPOI> pois = querySIR(center, radius, REQUEST_FORMAT);

        for (SirPOI sirPOI : pois) {
            if (sirPOI instanceof Hotspot) {
                Hotspot h = (Hotspot) sirPOI;
                layarResponse.hotspots.add(h);
            }
        }
    } catch (Exception e) {
        log.error("Error querying SIR.", e);
        layarResponse.errorCode = LayarResponse.CODE_ERROR;
        layarResponse.errorString = e.toString() + ": " + e.getMessage();
        layarResponse.showMessage = "Server side exception!";
    }

    // write response
    layarResponse.toJSON(generator);

    // clean up
    generator.close();
    response.flushBuffer();
}

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

@ExceptionHandler(CIValidationException.class)
public void handleCIValidationExceptions(CIValidationException e, HttpServletResponse response)
        throws IOException {
    sendError(response, HttpServletResponse.SC_BAD_REQUEST, e);
}

From source file:org.magnum.mobilecloud.video.VideoLikeController.java

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike", method = RequestMethod.POST)
public void unlikeVideo(@PathVariable("id") long id, Principal p, HttpServletResponse resp) {
    Video v = videos.findOne(id);//from  w  ww.j a  va2 s .  c  o m
    if (v == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {
        Set<String> likedUsernames = v.getLikedUsernames();
        String username = p.getName();
        if (!likedUsernames.contains(username)) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            likedUsernames.remove(username);
            v.setLikedUsernames(likedUsernames);
            v.setLikes(likedUsernames.size());
            videos.save(v);
        }
    }
}

From source file:io.github.howiefh.jeews.modules.oauth2.shiro.filter.TokenFilter.java

@Override
protected boolean onAccessDenied(ServletRequest req, ServletResponse resp) throws Exception {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    try {/*from  w w w.ja  v  a2 s  .  c  o m*/
        // OAuth?
        OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request,
                ParameterStyle.HEADER);
        // ?Access Token
        String accessToken = oauthRequest.getAccessToken();

        // ?Access Token
        if (!oAuthService.checkAccessToken(accessToken)) {
            // ?/???
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                    .setRealm(Constants.RESOURCE_SERVER_NAME)
                    .setError(OAuthError.ResourceResponse.INVALID_TOKEN).buildHeaderMessage();

            response.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                    oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    } catch (OAuthProblemException e) {
        // ??
        String errorCode = e.getError();
        if (OAuthUtils.isEmpty(errorCode)) {
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                    .setRealm(Constants.RESOURCE_SERVER_NAME).buildHeaderMessage();

            response.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                    oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                .setRealm(Constants.RESOURCE_SERVER_NAME).setError(e.getError())
                .setErrorDescription(e.getDescription()).setErrorUri(e.getUri()).buildHeaderMessage();

        response.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return false;
    }

}

From source file:org.clothocad.phagebook.controllers.LabController.java

@RequestMapping(value = "/addPIToLab", method = RequestMethod.POST)
protected void addPIToLab(@RequestParam Map<String, String> params, HttpServletResponse response)
        throws ServletException, IOException {

    //at most we'd add like 10 PIs to a lab...
    Object pLabId = params.get("lab");
    String labId = pLabId != null ? (String) pLabId : "";

    Object pUserId = params.get("userId");
    String userId = pUserId != null ? (String) pUserId : "";

    boolean isValid = false;

    if (!labId.equals("") && !userId.equals("")) {
        isValid = true;// w  w w  . java2 s.  c om
    }

    if (isValid) {
        ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
        Clotho clothoObject = new Clotho(conn);
        String username = this.backendPhagebookUser;
        String password = this.backendPhagebookPassword;
        Map loginMap = new HashMap();
        loginMap.put("username", username);
        loginMap.put("credentials", password);
        clothoObject.login(loginMap);
        // able to query now. 
        Lab lab = ClothoAdapter.getLab(labId, clothoObject); //Lab
        //Person person = ClothoAdapter.getPerson(userId, clothoObject); //if we ever wanted to use more props check priviledge maybe?
        List<String> labPIList = lab.getLeadPIs(); // to change
        JSONObject responseJSON = new JSONObject();

        if (!labPIList.contains(pLabId)) {
            labPIList.add(userId);
            responseJSON.put("message", "new PI added!");
        } else {
            responseJSON.put("message", "Person is already a PI!");
        }

        lab.setLeadPIs(labPIList);

        ClothoAdapter.setLab(lab, clothoObject);

        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);
        conn.closeConnection();
        PrintWriter out = response.getWriter();
        out.print(responseJSON);
        out.flush();

    } else {
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        JSONObject responseJSON = new JSONObject();
        responseJSON.put("message", "Lab or User Id cannot be blank.");
        PrintWriter out = response.getWriter();
        out.print(responseJSON);
        out.flush();
    }
}

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

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

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

From source file:net.scran24.staff.server.services.UploadUserInfoService.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");
    ServletOutputStream outputStream = resp.getOutputStream();
    PrintWriter writer = new PrintWriter(outputStream);

    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } else {/*from w w w  . j  a  v a 2 s .  c  o m*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

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

            InputStream file = null;
            String role = null;
            Set<String> permissions = new HashSet<String>();
            String surveyId = req.getParameter("surveyId");

            for (FileItem i : items) {
                if (i.getFieldName().equals("file"))
                    file = i.getInputStream();
                else if (i.getFieldName().equals("role"))
                    role = i.getString();
                else if (i.getFieldName().equals("permission"))
                    permissions.add(i.getString());
            }

            if (file == null)
                throw new ServletException("file field not specified");
            if (role == null)
                throw new ServletException("role field not specified");
            if (surveyId == null)
                throw new ServletException("surveyId field not specified");

            List<UserRecord> userRecords = UserRecordCSV.fromCSV(file);

            try {
                Set<String> roles = new HashSet<String>();
                roles.add(role);

                dataStore.saveUsers(surveyId, mapToSecureUserRecords(userRecords, roles, permissions));
                writer.print("OK");
            } catch (DataStoreException e) {
                writer.print("ERR:" + e.getMessage());
            } catch (DuplicateKeyException e) {
                writer.print("ERR:" + e.getMessage());
            }

        } catch (FileUploadException e) {
            writer.print("ERR:" + e.getMessage());
        } catch (IOException e) {
            writer.print("ERR:" + e.getMessage());
        }
    }

    writer.close();
}