List of usage examples for javax.servlet.http HttpServletResponse SC_BAD_REQUEST
int SC_BAD_REQUEST
To view the source code for javax.servlet.http HttpServletResponse SC_BAD_REQUEST.
Click Source Link
From source file:org.magnum.mobilecloud.video.VideoSvc.java
@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST) public @ResponseBody void likeVideo(@PathVariable("id") long id, HttpServletRequest request, HttpServletResponse response) {//from ww w.j a va 2s.c o m Video video = videos.findOne(id); if (video != null) { Set<String> users = video.getLikesUserNames(); String user = request.getRemoteUser(); System.out.println("User: " + user); if (users.contains(user)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { users.add(user); video.setLikesUserNames(users); video.setLikes(users.size()); videos.save(video); response.setStatus(HttpServletResponse.SC_OK); } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.magnum.mobilecloud.video.VideoSvcCtrl.java
@PreAuthorize("hasRole(USER)") @RequestMapping(method = RequestMethod.POST, value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike") public @ResponseBody void unlikeVideo(@PathVariable("id") long id, Principal principal, HttpServletResponse response) {//from w w w . jav a 2 s. co m Video v = videoRepo.findOne(id); if (v != null) { HashSet<String> likers = v.getLikers(); if (likers.contains(principal.getName())) { likers.remove(principal.getName()); videoRepo.save(v); response.setStatus(HttpServletResponse.SC_OK); } else response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else response.setStatus(HttpServletResponse.SC_NOT_FOUND); }
From source file:com.homesnap.webserver.AbstractRestApi.java
protected JSONObject postRequestJSONObject(String urn, String body, int returnCodeExpected) { Client client = Client.create();/*from w ww . j a v a 2 s . c o m*/ WebResource webResource = client.resource("http://" + server + ":" + port + urn); String json = null; try { ClientResponse response = webResource.accept("application/json").post(ClientResponse.class, body); Assert.assertEquals(returnCodeExpected, response.getStatus()); if (returnCodeExpected == HttpServletResponse.SC_NOT_IMPLEMENTED || returnCodeExpected == HttpServletResponse.SC_NOT_ACCEPTABLE || returnCodeExpected == HttpServletResponse.SC_BAD_REQUEST) { return null; } json = response.getEntity(String.class); return JSonTools.fromJson(json); } catch (JSONException e) { e.printStackTrace(); Assert.fail("Problem with JSON [" + json + "] :" + e.getMessage()); } Assert.fail("Problem when call [" + urn + "]."); return null; }
From source file:com.fpmislata.banco.presentation.controladores.SucursalBancariaController.java
@RequestMapping(value = { "/sucursalbancaria" }, method = RequestMethod.POST, consumes = "application/json", produces = "application/json") public void insert(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody String jsonEntrada) { try {//from ww w . ja va 2s . c o m SucursalBancaria sucursalBancaria = (SucursalBancaria) jsonTransformer.fromJsonToObject(jsonEntrada, SucursalBancaria.class); sucursalBancariaService.insert(sucursalBancaria); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/json; charset=UTF-8"); httpServletResponse.getWriter().println(jsonTransformer.ObjectToJson(sucursalBancaria)); } catch (BusinessException ex) { List<BusinessMessage> bussinessMessage = ex.getBusinessMessages(); String jsonSalida = jsonTransformer.ObjectToJson(bussinessMessage); //System.out.println(jsonSalida); httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); httpServletResponse.setContentType("application/json; charset=UTF-8"); try { httpServletResponse.getWriter().println(jsonSalida); } catch (IOException ex1) { Logger.getLogger(SucursalBancariaController.class.getName()).log(Level.SEVERE, "Error devolviendo Lista de Mensajes", ex1); } } catch (Exception ex1) { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpServletResponse.setContentType("text/plain; charset=UTF-8"); try { ex1.printStackTrace(httpServletResponse.getWriter()); } catch (IOException ex2) { Logger.getLogger(SucursalBancariaController.class.getName()).log(Level.SEVERE, "Error devolviendo la traza", ex2); } } }
From source file:com.haulmont.cuba.web.controllers.LogDownloadController.java
protected UserSession getSession(String sessionId, HttpServletResponse response) throws IOException { UUID sessionUUID;//from ww w . j ava 2s . c o m try { sessionUUID = UUID.fromString(sessionId); } catch (Exception e) { log.error("Error parsing sessionId from URL param", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } AppContext.setSecurityContext(new SecurityContext(sessionUUID)); try { UserSession session = userSessionService.getUserSession(sessionUUID); if (session == null) response.sendError(HttpServletResponse.SC_FORBIDDEN); return session; } finally { AppContext.setSecurityContext(null); } }
From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java
private void add(HttpServletRequest request, String pathInfo, HttpServletResponse response) throws Exception { String eventType = pathInfo.substring(pathInfo.lastIndexOf('/') + 1); UTF8InputStreamReaderWrapper reader; if (request.getCharacterEncoding() != null) { reader = new UTF8InputStreamReaderWrapper(request.getInputStream(), request.getCharacterEncoding()); } else {/*w w w . ja v a 2s . c o m*/ reader = new UTF8InputStreamReaderWrapper(request.getInputStream()); } Map<String, Object> values = mapper.readValue(reader, TYPE_FLATMAP); if (validator != null) { ValidationResult result = validator.validate(values, eventType); if (result == null || result.isSuccess()) { JetstreamEvent event = createEvent(values, eventType); inboundChannel.onMessage(event); response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().print(validateReusltWriter.writeValueAsString(result)); } } else { JetstreamEvent event = createEvent(values, eventType); inboundChannel.onMessage(event); response.setStatus(HttpServletResponse.SC_OK); } }
From source file:com.haulmont.cuba.portal.controllers.LogDownloadController.java
protected UserSession getSession(String sessionId, HttpServletResponse response) throws IOException { UUID sessionUUID;// w w w . jav a2 s .c om try { sessionUUID = UUID.fromString(sessionId); } catch (Exception e) { log.error("Error parsing sessionId from URL param", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } AppContext.setSecurityContext(new SecurityContext(sessionUUID)); try { UserSession session = userSessionService.getUserSession(sessionUUID); if (session == null) response.sendError(HttpServletResponse.SC_FORBIDDEN); return session; } finally { AppContext.setSecurityContext(null); } }
From source file:org.energyos.espi.datacustodian.web.api.ApplicationInformationRESTController.java
@RequestMapping(value = Routes.ROOT_APPLICATION_INFORMATION_COLLECTION, method = RequestMethod.POST, consumes = "application/atom+xml", produces = "application/atom+xml") @ResponseBody//from w w w. j a va2 s .c o m public void create(HttpServletResponse response, @RequestParam Map<String, String> params, InputStream stream) throws IOException { response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE); try { ApplicationInformation applicationInformation = this.applicationInformationService .importResource(stream); exportService.exportApplicationInformation(applicationInformation.getId(), response.getOutputStream(), new ExportFilter(params)); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:org.surfnet.oaaas.resource.AbstractResource.java
public Response validateScope(HttpServletRequest request, List<String> requiredScopes) { VerifyTokenResponse verifyTokenResponse = (VerifyTokenResponse) request .getAttribute(AuthorizationServerFilter.VERIFY_TOKEN_RESPONSE); List<String> grantedScopes = verifyTokenResponse.getScopes(); for (String requiredScope : requiredScopes) { if (!grantedScopes.contains(requiredScope)) { LOG.debug("Resource required scopes ({}) which the client has not been granted ({})", requiredScopes, grantedScopes); return Response.status(HttpServletResponse.SC_BAD_REQUEST) .entity(new ErrorResponse(OAuth2Validator.ValidationResponse.SCOPE_NOT_VALID.getValue(), OAuth2Validator.ValidationResponse.SCOPE_NOT_VALID.getDescription())) .build();/*from ww w. j a v a 2s . co m*/ } } return null; }
From source file:edu.indiana.d2i.htrc.oauth2.userinfo.OAuth2UserInfoEndpoint.java
@POST @Path("/") @Consumes("application/x-www-form-urlencoded") @Produces("application/json") public Response getUserInformation(@Context HttpServletRequest request, MultivaluedMap<String, String> paramMap) throws OAuthSystemException { HttpServletRequestWrapper httpRequest = new OAuthUserInfoRequestWrapper(request, paramMap); if (log.isDebugEnabled()) { logUserInfoRequest(httpRequest); }/*from w w w . j a v a 2s. c o m*/ boolean basicAuthUsed = false; if (request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ) != null) { try { String[] clientCredentials = OAuthUIUtil .extractCredentialsFromAuthzHeader(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)); if (paramMap.containsKey(OAuth.OAUTH_CLIENT_ID) && paramMap.containsKey(OAuth.OAUTH_CLIENT_SECRET)) { return handleBasicAuthFailure(); } paramMap.add(OAuth.OAUTH_CLIENT_ID, clientCredentials[0]); paramMap.add(OAuth.OAUTH_CLIENT_SECRET, clientCredentials[1]); basicAuthUsed = true; log.debug("HTTP Authorization Header is available which will take precedence " + "over the client credentials available as request parameters."); } catch (OAuthClientException e) { return handleBasicAuthFailure(); } } try { OAuthUserInfoRequest oauthRequest = new OAuthUserInfoRequest(httpRequest); OAuth2UserInfoClient userInfoClient = new OAuth2UserInfoClient(); // exchange the user information for the Access token. OAuth2UserInfoRespDTO oAuth2UserInfoRespDTO = userInfoClient.getUserInfo(oauthRequest); // if there BE has returned an error if (oAuth2UserInfoRespDTO.getError()) { // if the client has used Basic Auth and if there is an auth failure, HTTP 401 Status // Code should be sent back to the client. if (basicAuthUsed && OAuth2ErrorCodes.INVALID_CLIENT.equals(oAuth2UserInfoRespDTO.getErrorCode())) { return handleBasicAuthFailure(); } // Otherwise send back HTTP 400 Status Code OAuthResponse response = OAuthResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(oAuth2UserInfoRespDTO.getErrorCode()) .setErrorDescription(oAuth2UserInfoRespDTO.getErrorMsg()).buildJSONMessage(); return Response.status(response.getResponseStatus()).entity(response.getBody()).build(); } else { OAuthResponse response = OAuthUserInfoResponse.userInfoResponse(HttpServletResponse.SC_OK) .setAuthroizedUser(oAuth2UserInfoRespDTO.getAuthorizedUser()) .setUserFullName(oAuth2UserInfoRespDTO.getUserFullName()) .setUserEmail(oAuth2UserInfoRespDTO.getUserEmail()).buildJSONMessage(); Response.ResponseBuilder respBuilder = Response.status(response.getResponseStatus()) .header(OAuthConstants.HTTP_RESP_HEADER_CACHE_CONTROL, OAuthConstants.HTTP_RESP_HEADER_VAL_CACHE_CONTROL_NO_STORE) .header(OAuthConstants.HTTP_RESP_HEADER_PRAGMA, OAuthConstants.HTTP_RESP_HEADER_VAL_PRAGMA_NO_CACHE); return respBuilder.entity(response.getBody()).build(); } } catch (OAuthClientException e) { return handleOAuthClientException(); } catch (OAuthProblemException e) { return handleOAuthProblemException(); } }