Java Code Examples for org.springframework.http.HttpStatus#BAD_REQUEST

The following examples show how to use org.springframework.http.HttpStatus#BAD_REQUEST . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SolaceController.java    From solace-samples-cloudfoundry-java with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/subscription/{subscriptionName}", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteSubscription(@PathVariable("subscriptionName") String subscriptionTopic) {
	logger.info("Deleting a subscription to topic: " + subscriptionTopic);

	if ( !this.listenerContainersMap.containsKey(subscriptionTopic) ) {
		// Not subscribed
		logger.error("Not subscribed to topic " + subscriptionTopic);
		return new ResponseEntity<>("{'description': 'Was not subscribed'}", HttpStatus.BAD_REQUEST);
	}

	try {
		DefaultMessageListenerContainer listenercontainer = this.listenerContainersMap.get(subscriptionTopic);
		listenercontainer.stop();
        listenercontainer.destroy();
        this.listenerContainersMap.remove(subscriptionTopic);

	} catch (Exception e) {
		logger.error("Service Creation failed.", e);
		return new ResponseEntity<>("{'description': '" + e.getMessage() + "'}", HttpStatus.BAD_REQUEST);
	}
	logger.info("Finished Deleting a subscription to topic: " + subscriptionTopic);
	return new ResponseEntity<>("{}", HttpStatus.OK);
}
 
Example 2
Source File: VocabularyCapture.java    From epcis with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> post(@RequestBody String inputString, @RequestParam(required = false) Integer gcpLength) {
	Configuration.logger.info(" EPCIS Masterdata Document Capture Started.... ");

	JSONObject retMsg = new JSONObject();
	if (Configuration.isCaptureVerfificationOn == true) {
		InputStream validateStream = CaptureUtil.getXMLDocumentInputStream(inputString);
		// Parsing and Validating data
		boolean isValidated = CaptureUtil.validate(validateStream,
				Configuration.wsdlPath + "/EPCglobal-epcis-masterdata-1_2.xsd");
		if (isValidated == false) {
			return new ResponseEntity<>(new String("Error: EPCIS Masterdata Document is not validated"),
					HttpStatus.BAD_REQUEST);
		}
	}

	InputStream epcisStream = CaptureUtil.getXMLDocumentInputStream(inputString);
	EPCISMasterDataDocumentType epcisMasterDataDocument = JAXB.unmarshal(epcisStream,
			EPCISMasterDataDocumentType.class);
	CaptureService cs = new CaptureService();
	retMsg = cs.capture(epcisMasterDataDocument, gcpLength);
	Configuration.logger.info(" EPCIS Masterdata Document : Captured ");

	if (retMsg.isNull("error") == true)
		return new ResponseEntity<>(retMsg.toString(), HttpStatus.OK);
	else
		return new ResponseEntity<>(retMsg.toString(), HttpStatus.BAD_REQUEST);
}
 
Example 3
Source File: AdminController.java    From fiware-cepheus with GNU General Public License v2.0 5 votes vote down vote up
@ExceptionHandler({HttpMessageNotReadableException.class})
public ResponseEntity<Object> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) {
    logger.error("Request not readable: {}", exception.toString());
    StatusCode statusCode = new StatusCode();
    statusCode.setCode("400");
    statusCode.setReasonPhrase(exception.getMessage());
    if (exception.getCause() != null) {
        statusCode.setDetail(exception.getCause().getMessage());
    }
    return new ResponseEntity<>(statusCode, HttpStatus.BAD_REQUEST);
}
 
Example 4
Source File: FakeClassnameTags123Api.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * To test class name in snake case
 * To test class name in snake case
 * <p><b>200</b> - successful operation
 * @param body client model (required)
 * @return ResponseEntity&lt;Client&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Client> testClassnameWithHttpInfo(Client body) throws RestClientException {
    Object postBody = body;
    
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling testClassname");
    }
    
    String path = apiClient.expandPath("/fake_classname_test", Collections.<String, Object>emptyMap());

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap formParams = new LinkedMultiValueMap();

    final String[] accepts = { 
        "application/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { 
        "application/json"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] { "api_key_query" };

    ParameterizedTypeReference<Client> returnType = new ParameterizedTypeReference<Client>() {};
    return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 5
Source File: IndexController.java    From Mahuta with Apache License 2.0 5 votes vote down vote up
@PostMapping(value = "${mahuta.api-spec.v1.persistence.index.cid}", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody IndexingResponse indexFile(@RequestBody @NotNull CIDIndexingRequest request) {
    
    try {
        return mahuta.prepareCIDndexing(request).execute();
    } catch (NoIndexException ex) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, ex.getMessage(), ex);
    }
}
 
Example 6
Source File: JobController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 删除定时任务
 */
@DeleteMapping
public ResponseEntity<ApiResponse> deleteJob(JobForm form) throws SchedulerException {
    if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
        return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST);
    }

    jobService.deleteJob(form);
    return new ResponseEntity<>(ApiResponse.msg("删除成功"), HttpStatus.OK);
}
 
Example 7
Source File: ArticleEditController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody
RestValidationErrorModel bindException(BindException e) {
	logger.debug("BindException", e);
	return RestValidationErrorModel.fromBindingResult(e.getBindingResult(), messageSourceAccessor);
}
 
Example 8
Source File: ControllerExceptionHandler.java    From biliob_backend with MIT License 5 votes vote down vote up
/**
 * 处理非法输入异常
 *
 * @param httpMessageNotReadableException 非法输入异常的详细内容
 * @return 返回异常信息
 */
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ExceptionResult handlerHttpMessageNotReadableException(
        HttpMessageNotReadableException httpMessageNotReadableException) {
    ExceptionResult ex = new ExceptionResult();
    ex.setCode(400);
    ex.setMsg("非法输入");
    return ex;
}
 
Example 9
Source File: RestErrorHandler.java    From metamodel-membrane with Apache License 2.0 5 votes vote down vote up
/**
 * DataSource invalid exception handler method - mapped to BAD_REQUEST.
 * 
 * @param ex
 * @return
 */
@ExceptionHandler(InvalidDataSourceException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public RestErrorResponse processDataSourceNotUpdateable(InvalidDataSourceException ex) {
    return new RestErrorResponse(HttpStatus.BAD_REQUEST.value(), "DataSource invalid: " + ex.getMessage());
}
 
Example 10
Source File: ExceptionHandlers.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBody handleMissingServletRequestParameterException(HttpServletRequest request,
                                                                  MissingServletRequestParameterException e) {
    ApiResponse response = new ApiResponse(ApiResponse.INVALID_PARAMS);
    response.setRemedialAction(
        String.format("Add missing parameter '%s' of type '%s'", e.getParameterName(), e.getParameterType()));
    return handleExceptionInternal(request, e, response);
}
 
Example 11
Source File: RestExceptionHandler.java    From POC with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * Handle MethodArgumentNotValidException. Triggered when an object fails @Valid
 * validation.
 */
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
		HttpHeaders headers, HttpStatus status, WebRequest request) {
	final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
	apiError.setMessage("Validation error");
	apiError.addValidationErrors(ex.getBindingResult().getFieldErrors());
	apiError.addValidationError(ex.getBindingResult().getGlobalErrors());
	return buildResponseEntity(apiError);
}
 
Example 12
Source File: ServletInvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void responseStatus() {
}
 
Example 13
Source File: JavaScriptController.java    From Spring-Boot-2-Fundamentals with MIT License 4 votes vote down vote up
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleArgument(IllegalArgumentException e) {
    return e.getMessage();
}
 
Example 14
Source File: TeiidRSProvider.java    From teiid-spring-boot with Apache License 2.0 4 votes vote down vote up
private Object convertToRuntimeType(Class<?> runtimeType, final MultipartFile part) {
    try {
        if (SQLXML.class.isAssignableFrom(runtimeType)) {
            SQLXMLImpl xml = new SQLXMLImpl(new InputStreamFactory() {
                @Override
                public InputStream getInputStream() throws IOException {
                    return part.getInputStream();
                }
            });
            if (charset(part) != null) {
                xml.setEncoding(charset(part));
            }
            return xml;
        } else if (Blob.class.isAssignableFrom(runtimeType)) {
            return new BlobImpl(new InputStreamFactory() {
                @Override
                public InputStream getInputStream() throws IOException {
                    return part.getInputStream();
                }
            });
        } else if (Clob.class.isAssignableFrom(runtimeType)) {
            ClobImpl clob = new ClobImpl(new InputStreamFactory() {
                @Override
                public InputStream getInputStream() throws IOException {
                    return part.getInputStream();
                }
            }, -1);
            if (charset(part) != null) {
                clob.setEncoding(charset(part));
            }
            return clob;
        } else if (DataTypeManager.DefaultDataClasses.VARBINARY.isAssignableFrom(runtimeType)) {
            return Base64.decode(new String(part.getBytes()));
        } else if (DataTypeManager.isTransformable(String.class, runtimeType)) {
            return DataTypeManager.transformValue(new String(part.getBytes()), runtimeType);
        }
        return new String(part.getBytes());
    } catch (IOException | TransformationException e) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                "Failed to convert input into runtime types required by the engine", e);
    }
}
 
Example 15
Source File: RequestMappingHandlerAdapterTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
public ResponseEntity<String> handleBadRequest() {
	return new ResponseEntity<>("body", HttpStatus.BAD_REQUEST);
}
 
Example 16
Source File: ResponseStatusExceptionHandlerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void handleNestedResponseStatusException() {
	Throwable ex = new Exception(new ResponseStatusException(HttpStatus.BAD_REQUEST, ""));
	this.handler.handle(this.exchange, ex).block(Duration.ofSeconds(5));
	assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode());
}
 
Example 17
Source File: HodCombinedRequestController.java    From find with MIT License 4 votes vote down vote up
@ExceptionHandler(InvalidOriginException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleInvalidRedirectUrl(final InvalidOriginException exception) {
    return new ErrorResponse("Origin of redirect URL " + exception.getUrl() + " is not allowed");
}
 
Example 18
Source File: ResponseStatusExceptionResolverTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test  // SPR-15524
public void responseStatusExceptionWithReason() throws Exception {
	ResponseStatusException ex = new ResponseStatusException(HttpStatus.BAD_REQUEST, "The reason");
	ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
	assertResolved(mav, 400, "The reason");
}
 
Example 19
Source File: FileGroupController.java    From full-teaching with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/delete/file/{fileId}/file-group/{fileGroupId}/course/{courseId}", method = RequestMethod.DELETE)
public ResponseEntity<Object> deleteFile(
		@PathVariable(value="fileId") String fileId,
		@PathVariable(value="fileGroupId") String fileGroupId,
		@PathVariable(value="courseId") String courseId
) {
	
	ResponseEntity<Object> authorized = authorizationService.checkBackendLogged();
	if (authorized != null){
		return authorized;
	};
	
	long id_file = -1;
	long id_fileGroup = -1;
	long id_course = -1;
	try{
		id_file = Long.parseLong(fileId);
		id_fileGroup = Long.parseLong(fileGroupId);
		id_course = Long.parseLong(courseId);
	}catch(NumberFormatException e){
		return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
	}
	
	
	Course c = courseRepository.findOne(id_course);
	
	ResponseEntity<Object> teacherAuthorized = authorizationService.checkAuthorization(c, c.getTeacher());
	if (teacherAuthorized != null) { // If the user is not the teacher of the course
		return teacherAuthorized;
	} else {
	
		FileGroup fg = fileGroupRepository.findOne(id_fileGroup);
		
		if (fg != null){
			File file = null;
			for(File f : fg.getFiles()) {
		        if(f.getId() == id_file) {
		            file = f;
		            break;
		        }
		    }
			if (file != null){
				
				if (this.isProductionStage()){
					//ONLY ON PRODUCTION
					//Deleting S3 stored file...
					this.productionFileDeletion(file.getNameIdent(), "/files");
					//ONLY ON PRODUCTION
				} else {
					//ONLY ON DEVELOPMENT
					//Deleting locally stored file...
					this.deleteStoredFile(file.getNameIdent());
					//ONLY ON DEVELOPMENT
				}
				
				fg.getFiles().remove(file);
				fg.updateFileIndexOrder();
				
				fileGroupRepository.save(fg);
				return new ResponseEntity<>(file, HttpStatus.OK);
				
			}else{
				//The file to delete does not exist or does not have a fileGroup parent
				fileRepository.delete(id_file);
				return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
			}
		}else{
			//The fileGroup parent does not exist
			fileRepository.delete(id_file);
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		}
	}
}
 
Example 20
Source File: ExceptionAdviceHandler.java    From oauth-boot with MIT License 4 votes vote down vote up
/**
 * 400错误 类型不匹配
 */
@ExceptionHandler({TypeMismatchException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public BaseResponse requestTypeMismatch() {
    return this.argumentsError();
}