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

The following examples show how to use org.springframework.http.HttpStatus#FORBIDDEN . 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: StudentGroupingController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "{grouping}/studentsToEnroll")
    public @ResponseBody ResponseEntity<String> getStudentsToEnroll(@PathVariable Grouping grouping) {
        if (!personInGroupingAttends(grouping, AccessControl.getPerson())) {
//            throw new DomainException("error.grouping.notEnroled");
            return new ResponseEntity<>(
                    createErrorJson((new DomainException("error.grouping.notEnroled")).getLocalizedMessage()),
                    HttpStatus.FORBIDDEN);
        }
        if (!groupingIsOpenForEnrollment(grouping)) {
//            throw new DomainException("error.grouping.notOpenToEnrollment");
            return new ResponseEntity<>(
                    createErrorJson((new DomainException("error.studentGroupShift.notOpen")).getLocalizedMessage()),
                    HttpStatus.FORBIDDEN);
        }
        return new ResponseEntity<>(view(grouping
                .getAttendsSet()
                .stream()
                .filter(attends -> grouping.getStudentGroupsSet().stream()
                        .noneMatch(sg -> sg.getAttendsSet().stream().anyMatch(at -> at.equals(attends))))
                .map(Attends::getRegistration).map(Registration::getPerson).collect(Collectors.toList())).toString(), HttpStatus.OK);
    }
 
Example 2
Source File: CollectionService.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
public List<Illustration> queryCollectionIllust(Integer collectionId, Integer page, Integer pageSize) {
    //校验画集是否公开 画集isPublic 或者user是本人
    Collection collection = queryCollectionById(collectionId);
    if (collection == null) {
        throw new BusinessException(HttpStatus.NOT_FOUND, "未找到该画集");
    }
    if (collection.getIsPublic() == 0) {
        Map<String, Object> context = AppContext.get();
        if (context != null && context.get(AuthConstant.USER_ID) != null) {
            if (context.get(AuthConstant.USER_ID) != collection.getUserId()) {
                throw new BusinessException(HttpStatus.FORBIDDEN, "无权限访问");
            }
        }
    }
    List<Integer> illustIdList = collectionMapper.queryCollectionIllustIdList(collectionId, (page - 1) * pageSize, pageSize);
    return illustrationBizService.queryIllustrationByIllustIdList(illustIdList);
}
 
Example 3
Source File: JdbcQueryWs.java    From poli with MIT License 6 votes vote down vote up
@RequestMapping(
        value = "/component/{id}",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<QueryResult> queryComponent(
        @PathVariable("id") long componentId,
        @RequestBody List<FilterParameter> filterParams,
        HttpServletRequest request
) {
    Component component = componentDao.findById(componentId);
    if (component.getJdbcDataSourceId() == 0) {
        return new ResponseEntity(QueryResult.ofError(Constants.ERROR_NO_DATA_SOURCE_FOUND), HttpStatus.OK);
    }

    boolean isAccessValid = isComponentAccessValid(component, request);
    if (isAccessValid) {
        String sql = component.getSqlQuery();
        DataSource dataSource = jdbcDataSourceService.getDataSource(component.getJdbcDataSourceId());
        User user = (User) request.getAttribute(Constants.HTTP_REQUEST_ATTR_USER);
        List<FilterParameter> newFilterParams = addUserAttributesToFilterParams(user.getUserAttributes(), filterParams);
        QueryResult queryResult = jdbcQueryService.queryByParams(dataSource, sql, newFilterParams, Constants.QUERY_RESULT_NOLIMIT);
        return new ResponseEntity(queryResult, HttpStatus.OK);
    }

    return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
 
Example 4
Source File: BookingService.java    From restful-booker-platform with GNU General Public License v3.0 6 votes vote down vote up
public BookingResult updateBooking(int bookingId, Booking bookingToUpdate, String token) throws SQLException {
    if(authRequests.postCheckAuth(token)){
        if(dateCheckValidator.isValid(bookingToUpdate.getBookingDates())) {
            if (bookingDB.checkForBookingConflict(bookingToUpdate)) {
                return new BookingResult(HttpStatus.CONFLICT);
            } else {
                CreatedBooking updatedBooking = bookingDB.update(bookingId, bookingToUpdate);

                if(updatedBooking != null){
                    return new BookingResult(updatedBooking,  HttpStatus.OK);
                } else {
                    return new BookingResult(HttpStatus.NOT_FOUND);
                }
            }
        } else {
            return new BookingResult(HttpStatus.CONFLICT);
        }
    } else {
        return new BookingResult(HttpStatus.FORBIDDEN);
    }
}
 
Example 5
Source File: ExceptionAdvice.java    From spring-ddd-bank with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Converts the given exception to the most suiting HTTP response status.
 * 
 * @return one of HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN,
 *         HttpStatus.BAD_REQUEST, HttpStatus.INTERNAL_SERVER_ERROR
 * @param exc
 *            the exception to be converted
 */
HttpStatus exceptionToStatus(final Exception exc) {
	if (exc instanceof BankService.ClientNotFoundExc) {
		return HttpStatus.NOT_FOUND;
	}
	if (exc instanceof Client.NotManagedAccountExc) {
		return HttpStatus.NOT_FOUND;
	}
	if (exc instanceof Client.NotOwnerExc) {
		return HttpStatus.FORBIDDEN;
	}
	if (exc instanceof Client.WithoutRightExc) {
		return HttpStatus.FORBIDDEN;
	}
	final String excClassName = exc.getClass().getName();
	if (excClassName.startsWith(restInterfacePackagePrefix) || excClassName.startsWith(domainPackagePrefix)) {
		return HttpStatus.BAD_REQUEST;
	}
	return HttpStatus.INTERNAL_SERVER_ERROR;
}
 
Example 6
Source File: ConsoleIndex.java    From eagle with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping("/error")
public String error(HttpServletRequest request, HttpServletResponse response) {

    HttpStatus status = super.getStatus(request);

    if (status == HttpStatus.NOT_FOUND) {
        return "wrong";
    }

    if (status == HttpStatus.FORBIDDEN || status == HttpStatus.UNAUTHORIZED) {
        AuthenticatUtil.needAuthenticate(response);
        return "";
    }

    return "wrong";
}
 
Example 7
Source File: RoomService.java    From restful-booker-platform with GNU General Public License v3.0 5 votes vote down vote up
public RoomResult updateRoom(int roomId, Room roomToUpdate, String token) throws SQLException {
    if(authRequests.postCheckAuth(token)){
        Room updatedRoom = roomDB.update(roomId, roomToUpdate);

        if(updatedRoom != null){
            return new RoomResult(HttpStatus.ACCEPTED, updatedRoom);
        } else {
            return new RoomResult(HttpStatus.NOT_FOUND);
        }
    } else {
        return new RoomResult(HttpStatus.FORBIDDEN);
    }
}
 
Example 8
Source File: ShiroExceptionHandler.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExceptionHandler(AuthorizationException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public Response<Void> handleException(AuthorizationException e) {
    log.error("权限验证未通过 {}",e.getMessage());
    shiroEventListener.afterLogin(currentUserName.get(),false,e.getMessage());
    ShiroExceptionHandler.remove();
    return new Response<>(HttpStatus.FORBIDDEN.value() + "", "当前用户无权限访问", null);
}
 
Example 9
Source File: ManageDepartmentsController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/deleteDepartment", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<String> deleteDepartment(@RequestBody String departmentJson) {
    try {
        departmentService.deleteDepartment(createDepartmentBeanFromJSON(departmentJson));
        return new ResponseEntity<String>(HttpStatus.OK);
    } catch (DomainException dme) {
        return new ResponseEntity<String>(createErrorJson(dme.getLocalizedMessage()), HttpStatus.FORBIDDEN);
    }
}
 
Example 10
Source File: RestExceptionHandler.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(value = EntandoAuthorizationException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorRestResponse processEntandoAuthorizationException(EntandoAuthorizationException ex) {
    logger.debug("Handling {} error", ex.getClass().getSimpleName());
    RestError error = new RestError(RestErrorCodes.UNAUTHORIZED, this.resolveLocalizedErrorMessage("UNAUTHORIZED", new Object[]{ex.getUsername(), ex.getRequestURI(), ex.getMethod()}));
    return new ErrorRestResponse(error);
}
 
Example 11
Source File: ExceptionHandlerAdvice.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
/**
 * AccessDeniedException异常处理返回json
 * 状态码:403
 * @param exception
 * @return
 */
@ExceptionHandler({ AccessDeniedException.class })
@ResponseStatus(HttpStatus.FORBIDDEN)
public Map<String, Object> badMethodExpressException(AccessDeniedException exception) {
	Map<String, Object> data = new HashMap<>();
	data.put("resp_code", HttpStatus.FORBIDDEN.value());
	data.put("resp_msg", exception.getMessage());

	return data;
}
 
Example 12
Source File: TdsErrorHandling.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handle(IllegalArgumentException ex) {
  logger.warn("TDS Error", ex);

  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.setContentType(MediaType.TEXT_PLAIN);
  String mess = ex.getMessage();

  if (mess != null && mess.startsWith("RequestTooLarge")) // RequestTooLargeException only avail in tds module
    return new ResponseEntity<>("Request Too Large: " + htmlEscape(mess), responseHeaders, HttpStatus.FORBIDDEN);
  else
    return new ResponseEntity<>("IllegalArgumentException: " + htmlEscape(mess), responseHeaders,
        HttpStatus.BAD_REQUEST);
}
 
Example 13
Source File: BloodPressureResource.java    From 21-points with Apache License 2.0 5 votes vote down vote up
/**
 * DELETE  /blood-pressures/:id : delete the "id" bloodPressure.
 *
 * @param id the id of the bloodPressure to delete
 * @return the ResponseEntity with status 200 (OK)
 */
@DeleteMapping("/blood-pressures/{id}")
@Timed
public ResponseEntity<?> deleteBloodPressure(@PathVariable Long id) {
    log.debug("REST request to delete BloodPressure : {}", id);
    Optional<BloodPressure> bloodPressure = bloodPressureRepository.findById(id);
    if (bloodPressure.isPresent() && bloodPressure.get().getUser() != null &&
        !bloodPressure.get().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) {
        return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
    }
    bloodPressureRepository.deleteById(id);
    bloodPressureSearchRepository.deleteById(id);
    return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
 
Example 14
Source File: CustomRestExceptionHandler.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler({ AccessDeniedException.class })
public ResponseEntity<Object> handleAccessDeniedException(HttpClientErrorException ex, WebRequest request) {
    final String error = "Digits access authorization failed" ;
    final ApiError apiError = new ApiError(HttpStatus.FORBIDDEN, ex.getLocalizedMessage(), error);

    return new ResponseEntity<Object>(apiError, new HttpHeaders(), HttpStatus.FORBIDDEN);
}
 
Example 15
Source File: HttpClientErrorException.java    From java-technology-stack with MIT License 4 votes vote down vote up
Forbidden(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
	super(HttpStatus.FORBIDDEN, statusText, headers, body, charset);
}
 
Example 16
Source File: ExceptionTranslator.java    From expper with GNU General Public License v3.0 4 votes vote down vote up
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorDTO processAccessDeniedExcpetion(AccessDeniedException e) {
    return new ErrorDTO(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage());
}
 
Example 17
Source File: RestAuthController.java    From CAS with Apache License 2.0 4 votes vote down vote up
/**
 * 1. cas 服务端会通过post请求,并且把用户信息以"用户名:密码"进行Base64编码放在authorization请求头中
 * 2. 返回200状态码并且格式为{"@class":"org.apereo.cas.authentication.principal.SimplePrincipal","id":"casuser","attributes":{}} 是成功的
 * 2. 返回状态码403用户不可用;404账号不存在;423账户被锁定;428过期;其他登录失败
 *
 * @param httpHeaders
 * @return
 */
@PostMapping("/login")
public Object login(@RequestHeader HttpHeaders httpHeaders) {
    LOGGER.info("Rest api login.");
    LOGGER.debug("request headers: {}", httpHeaders);
    SysUser user = null;
    try {
        UserTemp userTemp = obtainUserFormHeader(httpHeaders);
        //尝试查找用户库是否存在
        user = new SysUser();
        user.setUsername("anumbrella");
        user.setPassword("123");
        if (user != null) {
            if (!user.getPassword().equals(userTemp.password)) {
                //密码不匹配
                return new ResponseEntity(HttpStatus.BAD_REQUEST);
            }
            if (user.isDisable()) {
                //禁用 403
                return new ResponseEntity(HttpStatus.FORBIDDEN);
            }
            if (user.isLocked()) {
                //锁定 423
                return new ResponseEntity(HttpStatus.LOCKED);
            }
            if (user.isExpired()) {
                //过期 428
                return new ResponseEntity(HttpStatus.PRECONDITION_REQUIRED);
            }
        } else {
            //不存在 404
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("", e);
        new ResponseEntity(HttpStatus.BAD_REQUEST);
    }
    LOGGER.info("[{}] login is ok", user.getUsername());
    //成功返回json
    return user;
}
 
Example 18
Source File: ExceptionTranslator.java    From ServiceCutter with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorDTO processAccessDeniedExcpetion(AccessDeniedException e) {
    return new ErrorDTO(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage());
}
 
Example 19
Source File: NotificationController.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@ApiResponses(value = {
           @ApiResponse(code = 200, message = "Successfully sent the email"),
           @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
           @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
           @ApiResponse(code = 404, message = "The resource you were trying to reach is not found"),
           @ApiResponse(code = 417, message = "Expectation Failed"),
           @ApiResponse(code = 408, message = "operation timed out")
   }
   )

@ApiOperation(value = "Send a Text Email", response = ResponseEntity.class)
@RequestMapping(value = "/send-plain-text-mail", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Void> sendTextMail(@ApiParam(value = "Provide Mail Message Request Body", required = true) final @RequestBody MailMessageRequestBody mailMessageRequestBody) {
	try {
		log.info("fromAddress==sendMailWithTemplate from config {}",fromAddress);
		log.info("mailTemplateRequestBody.getFrom()===sendMailWithTemplate from param {}",mailMessageRequestBody.getFrom());
		
		mailService.prepareAndSendMail("",mailMessageRequestBody.getFrom(), 
				mailMessageRequestBody.getTo(),
				mailMessageRequestBody.getSubject(), 
				mailMessageRequestBody.getMailBodyAsString(),
				mailMessageRequestBody.getPlaceholderValues(), mailMessageRequestBody.getAttachmentUrl(), true);
		return new ResponseEntity<>(HttpStatus.OK);
	} catch (Exception exception) {
		log.error(EXE_EMAIL_SEND, exception);
		try {
			log.info("fromAddress==sendMailWithTemplate from catch block from config {}",fromAddress);
			log.info("mailTemplateRequestBody.getFrom() from catch block===sendMailWithTemplate from param {}",mailMessageRequestBody.getFrom());
			
			mailService.prepareAndSendMail(mailMessageRequestBody.getFrom(),fromAddress, 
					mailMessageRequestBody.getTo(),
					mailMessageRequestBody.getSubject(), 
					mailMessageRequestBody.getMailBodyAsString(),
					mailMessageRequestBody.getPlaceholderValues(), mailMessageRequestBody.getAttachmentUrl(), true);
			return new ResponseEntity<>(HttpStatus.OK);
		} catch (Exception e) {
			log.error(EXE_EMAIL_SEND, e);
			return new ResponseEntity<>(HttpStatus.FORBIDDEN);
		}
	}
}
 
Example 20
Source File: ExceptionTranslator.java    From tutorials with MIT License 4 votes vote down vote up
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorVM processAccessDeniedException(AccessDeniedException e) {
    return new ErrorVM(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage());
}