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

The following examples show how to use org.springframework.http.HttpStatus#NOT_FOUND . 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: ConfigController.java    From java-trader with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path=URL_PREFIX+"/{configSource}/**",
        method=RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getConfigItem(@PathVariable(value="configSource") String configSourceStr, HttpServletRequest request){
    String requestURI = request.getRequestURI();
    String configItem = requestURI.substring( URL_PREFIX.length()+configSourceStr.length()+1);
    Object obj = null;
    if ( "ALL".equalsIgnoreCase(configSourceStr) ) {
        obj = ConfigUtil.getObject(configItem);
    }else{
        String configSource = configSources.get(configSourceStr.toLowerCase());
        if (configSource==null){
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        obj = ConfigUtil.getObject(configSource, configItem);
    }
    if( logger.isDebugEnabled() ){
        logger.debug("Get config "+configSourceStr+" path \""+configItem+"\" value: \""+obj+"\"");
    }
    if ( obj==null ){
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }else{
        return obj.toString();
    }
}
 
Example 2
Source File: UserServiceImpl.java    From biliob_backend with MIT License 6 votes vote down vote up
/**
 * delete user's favorite video by video id
 *
 * @param aid video's id
 * @return response with message
 */
@Override
public ResponseEntity deleteFavoriteVideoByAid(Long aid) {
    User user = UserUtils.getFullInfo();
    if (user == null) {
        return new ResponseEntity<>(
                new Result(ResultEnum.HAS_NOT_LOGGED_IN), HttpStatus.UNAUTHORIZED);
    }
    ArrayList<Long> aids = user.getFavoriteAid();
    for (int i = 0; i < aids.size(); i++) {
        if (Objects.equals(aids.get(i), aid)) {
            aids.remove(i);
            user.setFavoriteAid(aids);
            userRepository.save(user);
            UserServiceImpl.logger.info("用户:{} 删除了收藏的视频,aid:{}", user.getName(), aid);
            return new ResponseEntity<>(new Result(ResultEnum.DELETE_SUCCEED), HttpStatus.OK);
        }
    }
    UserServiceImpl.logger.warn("用户:{} 试图删除一个不存在的视频", user.getName());
    return new ResponseEntity<>(new Result(ResultEnum.AUTHOR_NOT_FOUND), HttpStatus.NOT_FOUND);
}
 
Example 3
Source File: GenericExceptionHandlers.java    From kork with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(Exception.class)
public void handleException(Exception e, HttpServletResponse response, HttpServletRequest request)
    throws IOException {
  storeException(request, response, e);

  ResponseStatus responseStatus =
      AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class);

  if (responseStatus != null) {
    HttpStatus httpStatus = responseStatus.value();
    if (httpStatus.is5xxServerError()) {
      logger.error(httpStatus.getReasonPhrase(), e);
    } else if (httpStatus != HttpStatus.NOT_FOUND) {
      logger.error(httpStatus.getReasonPhrase() + ": " + e.toString());
    }

    String message = e.getMessage();
    if (message == null || message.trim().isEmpty()) {
      message = responseStatus.reason();
    }
    response.sendError(httpStatus.value(), message);
  } else {
    logger.error("Internal Server Error", e);
    response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
  }
}
 
Example 4
Source File: CheckVerificationProcessor.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
@Before("check()")
public void checkVerification(JoinPoint joinPoint) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    //获取共有value属性,没有就抛异常
    //其实这两个都不会为空,若为空在controller之前就会被拦截
    String value = commonUtil.getFirstMethodArgByAnnotationValueMethodValue(joinPoint, RequestParam.class, "value");
    String vid = commonUtil.getFirstMethodArgByAnnotationValueMethodValue(joinPoint, RequestParam.class, "vid");
    String v = stringRedisTemplate.opsForValue().get(verificationCodeRedisPre + vid);
    if (v == null) {
        throw new VerificationCheckException(HttpStatus.NOT_FOUND, "验证码不存在");
    }
    //进数据库查询
    if (!value.equalsIgnoreCase(v)) {
        throw new VerificationCheckException(HttpStatus.BAD_REQUEST, "验证码错误");
    }
    stringRedisTemplate.delete(verificationCodeRedisPre + vid);
    //放行
}
 
Example 5
Source File: CmServiceImpl.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public CmCiDTO selectOne(Map<String, Object> commandMap) throws Exception{
	CmCiDTO cmCiDTO = new CmCiDTO();
	cmCiDTO = cmDAO.selectOne(commandMap);
	
	// 데이타가 없으면 오류발생시킴
	if (cmCiDTO == null || cmCiDTO.getTnsda_context_model_cmid() == null) {
		throw new UserDefinedException(HttpStatus.NOT_FOUND);
	}

	return cmCiDTO ;
	
}
 
Example 6
Source File: CmiServiceImpl.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<CmiDTO> selectList(Map<String, Object> commandMap) throws Exception {
	List<CmiDTO> list = new ArrayList<CmiDTO>();

	if (list == null || list.size() == 0) {
		throw new UserDefinedException(HttpStatus.NOT_FOUND);
	}

	return list ;
}
 
Example 7
Source File: HdfsController.java    From metron with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Deletes a file from HDFS")
@ApiResponses(value = { @ApiResponse(message = "File was deleted", code = 200),
        @ApiResponse(message = "File was not found in HDFS", code = 404) })
@RequestMapping(method = RequestMethod.DELETE)
ResponseEntity<Boolean> delete(@ApiParam(name = "path", value = "Path to HDFS file", required = true) @RequestParam String path,
                               @ApiParam(name = "recursive", value = "Delete files recursively") @RequestParam(required = false, defaultValue = "false") boolean recursive) throws RestException {
  if (hdfsService.delete(new Path(path), recursive)) {
    return new ResponseEntity<>(HttpStatus.OK);
  } else {
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
  }
}
 
Example 8
Source File: TodoListController.java    From todo-app-java-on-azure with MIT License 5 votes vote down vote up
/**
 * HTTP GET
 */
@RequestMapping(value = "/api/todolist/{index}",
        method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<?> getTodoItem(@PathVariable("index") String index) {
    try {
        return new ResponseEntity<TodoItem>(todoItemRepository.findById(index).get(), HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<String>(index + " not found", HttpStatus.NOT_FOUND);
    }
}
 
Example 9
Source File: EndpointErrorHandler.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorInfo> handleRestaurantNotFoundException(HttpServletRequest request,
    UserNotFoundException ex, Locale locale) {
  ErrorInfo response = new ErrorInfo();
  response.setUrl(request.getRequestURL().toString());
  response.setMessage(messageSource.getMessage(ex.getMessage(), ex.getArgs(), locale));
  return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
 
Example 10
Source File: CustomRestExceptionHandler.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(final NoHandlerFoundException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = "No handler found for " + ex.getHttpMethod() + " " + ex.getRequestURL();

    final ApiError apiError = new ApiError(HttpStatus.NOT_FOUND, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example 11
Source File: JeecgElasticsearchTemplate.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 删除索引
 * <p>
 * 查询地址:DELETE http://{baseUrl}/{indexName}
 */
public boolean removeIndex(String indexName) {
    String url = this.getBaseUrl(indexName).toString();
    try {
        return RestUtil.delete(url).getBoolean("acknowledged");
    } catch (org.springframework.web.client.HttpClientErrorException ex) {
        if (HttpStatus.NOT_FOUND == ex.getStatusCode()) {
            log.warn("索引删除失败:" + indexName + " 不存在,无需删除");
        } else {
            ex.printStackTrace();
        }
    }
    return false;
}
 
Example 12
Source File: TodoListController.java    From spring-todo-app with MIT License 5 votes vote down vote up
/**
 * HTTP PUT UPDATE
 */
@RequestMapping(value = "/api/todolist", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> updateTodoItem(@RequestBody TodoItem item) {
    System.out.println(new Date() + " PUT ======= /api/todolist ======= " + item);
    try {
        todoItemRepository.deleteById(item.getID());
        todoItemRepository.save(item);
        return new ResponseEntity<String>("Entity updated", HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<String>("Entity updating failed", HttpStatus.NOT_FOUND);
    }
}
 
Example 13
Source File: MarketDataController.java    From java-trader with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path=URL_PREFIX+"/producer/{producerId}",
        method=RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
public String getProducer(@PathVariable(value="producerId") String producerId, @RequestParam(name="pretty", required=false) boolean pretty){

    MarketDataProducer producer = marketDataService.getProducer(producerId);
    if ( producer==null ) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }
    return (JsonUtil.json2str(producer.toJson(), pretty));
}
 
Example 14
Source File: ExceptionProcessor.java    From personal_book_library_web_project with MIT License 5 votes vote down vote up
@ExceptionHandler(SQLException.class)
  @ResponseStatus(value = HttpStatus.NOT_FOUND)
  @ResponseBody
  public ServiceExceptionDetails processDataAccessException(HttpServletRequest httpServletRequest, SQLException exception) {
      
String detailedErrorMessage = exception.getMessage();
       
      String errorURL = httpServletRequest.getRequestURL().toString();
       
      return new ServiceExceptionDetails("", detailedErrorMessage, errorURL);
  }
 
Example 15
Source File: TodoListController.java    From spring-todo-app with MIT License 5 votes vote down vote up
/**
 * HTTP DELETE
 */
@RequestMapping(value = "/api/todolist/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteTodoItem(@PathVariable("id") String id) {
    System.out.println(new Date() + " DELETE ======= /api/todolist/{" + id
            + "} ======= ");
    try {
        todoItemRepository.deleteById(id);
        return new ResponseEntity<String>("Entity deleted", HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<String>("Entity deletion failed", HttpStatus.NOT_FOUND);
    }

}
 
Example 16
Source File: ArtistBizService.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
@Cacheable(value = "artist")
public Artist queryArtistById(Integer artistId) throws InterruptedException {
    Artist artist = artistBizMapper.queryArtistById(artistId);
    if (artist == null) {
        waitForPullArtistInfoQueue.offer(artistId);
        throw new BusinessException(HttpStatus.NOT_FOUND, "画师不存在");
    }

    return artist;
}
 
Example 17
Source File: FakeWebServerController.java    From jlineup with Apache License 2.0 4 votes vote down vote up
@GetMapping("/somerootpath")
public ResponseEntity<String> getNotFoundOnRootPath() {
    return new ResponseEntity<>("This is Not Found!", HttpStatus.NOT_FOUND);
}
 
Example 18
Source File: CustomerController.java    From pizzeria with MIT License 4 votes vote down vote up
@ExceptionHandler(CustomerNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public void handleCustomerNotFoundException() {

}
 
Example 19
Source File: NotFoundException.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public static NotFoundException create(boolean with404, String message) {
	HttpStatus httpStatus = with404 ? HttpStatus.NOT_FOUND
			: HttpStatus.SERVICE_UNAVAILABLE;
	return new NotFoundException(httpStatus, message);
}
 
Example 20
Source File: SubscribeServiceImpl.java    From SDA with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void unregist(String cmid) throws Exception {
	String unsubscription_uri = Utils.getSdaProperty("com.pineone.icbms.sda.si.unsubscription_uri");
	Map<String, Object> commandMap;

	// cmid로 삭제 대상 ci목록 가져오기
	commandMap = new HashMap<String, Object>();
	commandMap.put("cmid", cmid);
	List<CiDTO> ciList = subscribeDAO.selectList(commandMap);

	// 데이타가 없으면 오류발생시킴
	if (ciList == null || ciList.size() == 0) {
		throw new UserDefinedException(HttpStatus.NOT_FOUND);
	}

	Gson gson = new Gson();
	CiDTO[] ciDTO = new CiDTO[ciList.size()];
	
	for (int i = 0; i < ciList.size(); i++) {
		ciDTO[i] = ciList.get(i);
	}

	for (int i = 0; i < ciDTO.length; i++) {
		// condition을 JENA에 요청하여 uri목록을 얻음
		List<String> uriList = new ArrayList<String>();
		OneM2MSubscribeUriMapper mapper = new OneM2MSubscribeUriMapper(ciDTO[i].getDomain(),
				ciDTO[i].getConditions());

		uriList = mapper.getSubscribeUri();
		log.debug("uriList to unregist ==> \n" + uriList);

		for (int k = 0; k < uriList.size(); k++) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("_uri", uriList.get(k));

			String jsonMsg = gson.toJson(map);
			log.debug("Request message for unsubscribing  =>  " + jsonMsg);

			ResponseMessage responseMessage = Utils.requestPost(unsubscription_uri, jsonMsg); // POST
			log.debug("responseMessage of unsubscribing from SI : " + responseMessage.toString());
			if (responseMessage.getCode() != 200) {
				throw new RemoteSIException(HttpStatus.valueOf(responseMessage.getCode()),
						responseMessage.getMessage());
			}
				
			// subscribe테이블에서 삭제함(cmid와 ciid 그리고  uri를 키로 이용하여 삭제함)
			commandMap = new HashMap<String, Object>();
			commandMap.put("cmid", cmid);
			commandMap.put("ciid", ciDTO[i].getCiid());
			commandMap.put("uri", uriList.get(k));
			subscribeDAO.deleteByUri(commandMap);

		}
	}
}