org.springframework.http.ResponseEntity.badRequest()

Here are the examples of the java api org.springframework.http.ResponseEntity.badRequest() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

384 Examples 7

19 View Source File : SysUserController.java
License : GNU Affero General Public License v3.0
Project Creator : zycSummer

/**
 * 修改登录用户密码
 */
@SysLog("修改密码")
@PostMapping("/preplacedword")
@ApiOperation(value = "修改密码", notes = "修改当前登陆用户的密码")
public ResponseEnreplacedy<String> preplacedword(@RequestBody @Valid UpdatePreplacedwordDto param) {
    Long userId = SecurityUtils.getSysUser().getUserId();
    SysUser dbUser = sysUserService.getSysUserById(userId);
    if (!preplacedwordEncoder.matches(param.getPreplacedword(), dbUser.getPreplacedword())) {
        return ResponseEnreplacedy.badRequest().body("原密码不正确");
    }
    // 新密码
    String newPreplacedword = preplacedwordEncoder.encode(param.getNewPreplacedword());
    // 更新密码
    sysUserService.updatePreplacedwordByUserId(userId, newPreplacedword);
    return ResponseEnreplacedy.ok().build();
}

19 View Source File : SysMenuController.java
License : GNU Affero General Public License v3.0
Project Creator : zycSummer

/**
 * 修改
 */
@SysLog("修改菜单")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys:menu:update')")
public ResponseEnreplacedy<String> update(@Valid @RequestBody SysMenu menu) {
    // 数据校验
    verifyForm(menu);
    if (menu.getType() == MenuType.MENU.getValue()) {
        if (StrUtil.isBlank(menu.getUrl())) {
            return ResponseEnreplacedy.badRequest().body("菜单URL不能为空");
        }
    }
    sysMenuService.updateById(menu);
    return ResponseEnreplacedy.ok().build();
}

19 View Source File : SysMenuController.java
License : GNU Affero General Public License v3.0
Project Creator : zycSummer

/**
 * 删除
 */
@SysLog("删除菜单")
@DeleteMapping("/{menuId}")
@PreAuthorize("@pms.hasPermission('sys:menu:delete')")
public ResponseEnreplacedy<String> delete(@PathVariable Long menuId) {
    if (menuId <= Constant.SYS_MENU_MAX_ID) {
        return ResponseEnreplacedy.badRequest().body("系统菜单,不能删除");
    }
    // 判断是否有子菜单或按钮
    List<SysMenu> menuList = sysMenuService.listChildrenMenuByParentId(menuId);
    if (menuList.size() > 0) {
        return ResponseEnreplacedy.badRequest().body("请先删除子菜单或按钮");
    }
    sysMenuService.deleteMenuAndRoleMenu(menuId);
    return ResponseEnreplacedy.ok().build();
}

19 View Source File : AddrController.java
License : GNU Affero General Public License v3.0
Project Creator : zycSummer

/**
 * 删除订单配送地址
 */
@DeleteMapping("/deleteAddr/{addrId}")
@ApiOperation(value = "删除订单用户地址", notes = "根据地址id,删除用户地址")
@ApiImplicitParam(name = "addrId", value = "地址ID", required = true, dataType = "Long")
public ResponseEnreplacedy<String> deleteDvy(@PathVariable("addrId") Long addrId) {
    String userId = SecurityUtils.getUser().getUserId();
    UserAddr userAddr = userAddrService.getUserAddrByUserId(addrId, userId);
    if (userAddr == null) {
        return ResponseEnreplacedy.badRequest().body("该地址已被删除");
    }
    if (userAddr.getCommonAddr() == 1) {
        return ResponseEnreplacedy.badRequest().body("默认地址无法删除");
    }
    userAddrService.removeById(addrId);
    userAddrService.removeUserAddrByUserId(addrId, userId);
    return ResponseEnreplacedy.ok("删除地址成功");
}

19 View Source File : AddrController.java
License : GNU Affero General Public License v3.0
Project Creator : zycSummer

/**
 * 修改订单配送地址
 */
@PutMapping("/updateAddr")
@ApiOperation(value = "修改订单用户地址", notes = "修改用户地址")
public ResponseEnreplacedy<String> updateAddr(@Valid @RequestBody AddrParam addrParam) {
    String userId = SecurityUtils.getUser().getUserId();
    UserAddr dbUserAddr = userAddrService.getUserAddrByUserId(addrParam.getAddrId(), userId);
    if (dbUserAddr == null) {
        return ResponseEnreplacedy.badRequest().body("该地址已被删除");
    }
    UserAddr userAddr = mapperFacade.map(addrParam, UserAddr.clreplaced);
    userAddr.setUserId(userId);
    userAddr.setUpdateTime(new Date());
    userAddrService.updateById(userAddr);
    // 清除当前地址缓存
    userAddrService.removeUserAddrByUserId(addrParam.getAddrId(), userId);
    // 清除默认地址缓存
    userAddrService.removeUserAddrByUserId(0L, userId);
    return ResponseEnreplacedy.ok("修改地址成功");
}

19 View Source File : AddrController.java
License : GNU Affero General Public License v3.0
Project Creator : zycSummer

@PostMapping("/addAddr")
@ApiOperation(value = "新增用户地址", notes = "新增用户地址")
public ResponseEnreplacedy<String> addAddr(@Valid @RequestBody AddrParam addrParam) {
    String userId = SecurityUtils.getUser().getUserId();
    if (addrParam.getAddrId() != null && addrParam.getAddrId() != 0) {
        return ResponseEnreplacedy.badRequest().body("该地址已存在");
    }
    int addrCount = userAddrService.count(new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId, userId));
    UserAddr userAddr = mapperFacade.map(addrParam, UserAddr.clreplaced);
    if (addrCount == 0) {
        userAddr.setCommonAddr(1);
    } else {
        userAddr.setCommonAddr(0);
    }
    userAddr.setUserId(userId);
    userAddr.setStatus(1);
    userAddr.setCreateTime(new Date());
    userAddr.setUpdateTime(new Date());
    userAddrService.save(userAddr);
    if (userAddr.getCommonAddr() == 1) {
        // 清除默认地址缓存
        userAddrService.removeUserAddrByUserId(0L, userId);
    }
    return ResponseEnreplacedy.ok("添加地址成功");
}

19 View Source File : CategoryController.java
License : GNU Affero General Public License v3.0
Project Creator : zycSummer

/**
 * 更新分类
 */
@SysLog("更新分类")
@PutMapping
@PreAuthorize("@pms.hasPermission('prod:category:update')")
public ResponseEnreplacedy<String> update(@RequestBody Category category) {
    category.setShopId(SecurityUtils.getSysUser().getShopId());
    if (Objects.equals(category.getParentId(), category.getCategoryId())) {
        return ResponseEnreplacedy.badRequest().body("分类的上级不能是自己本身");
    }
    categoryService.updateCategroy(category);
    return ResponseEnreplacedy.ok().build();
}

19 View Source File : ValidateAdvice.java
License : Apache License 2.0
Project Creator : zhouxx

@ExceptionHandler({ MethodArgumentNotValidException.clreplaced })
@ResponseBody
public ResponseEnreplacedy handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    if (validateHandler != null) {
        ResponseEnreplacedy responseEnreplacedy = validateHandler.handle(e);
        if (responseEnreplacedy != null) {
            return responseEnreplacedy;
        }
    }
    ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
    return ResponseEnreplacedy.badRequest().header(WebConfiguration.TIP_KEY, UnicodeUtils.stringToUnicode(objectError.getDefaultMessage())).build();
}

19 View Source File : ValidateAdvice.java
License : Apache License 2.0
Project Creator : zhouxx

@ExceptionHandler({ ValidateException.clreplaced })
@ResponseBody
public ResponseEnreplacedy handleValidateException(ValidateException e) {
    if (validateHandler != null) {
        ResponseEnreplacedy responseEnreplacedy = validateHandler.handle(e);
        if (responseEnreplacedy != null) {
            return responseEnreplacedy;
        }
    }
    return ResponseEnreplacedy.badRequest().header(WebConfiguration.TIP_KEY, UnicodeUtils.stringToUnicode(e.getMessage())).build();
}

19 View Source File : ValidateAdvice.java
License : Apache License 2.0
Project Creator : zhouxx

@ExceptionHandler({ BindException.clreplaced })
@ResponseBody
public ResponseEnreplacedy handleBindException(BindException e) {
    if (validateHandler != null) {
        ResponseEnreplacedy responseEnreplacedy = validateHandler.handle(e);
        if (responseEnreplacedy != null) {
            return responseEnreplacedy;
        }
    }
    ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
    return ResponseEnreplacedy.badRequest().header(WebConfiguration.TIP_KEY, UnicodeUtils.stringToUnicode(objectError.getDefaultMessage())).build();
}

19 View Source File : ValidateAdvice.java
License : Apache License 2.0
Project Creator : zhouxx

@ExceptionHandler({ MissingServletRequestParameterException.clreplaced, MissingPathVariableException.clreplaced, HttpMessageNotReadableException.clreplaced })
@ResponseBody
public ResponseEnreplacedy handleServletRequestBindingException(Exception e) {
    if (validateHandler != null) {
        ResponseEnreplacedy responseEnreplacedy = validateHandler.handle(e);
        if (responseEnreplacedy != null) {
            return responseEnreplacedy;
        }
    }
    return ResponseEnreplacedy.badRequest().header(WebConfiguration.TIP_KEY, UnicodeUtils.stringToUnicode(e.getMessage())).build();
}

19 View Source File : WxStorageController.java
License : GNU General Public License v3.0
Project Creator : zcbin

/**
 * 访问存储对象
 *
 * @param key 存储对象key
 * @return
 */
@GetMapping("/fetch/{key:.+}")
public ResponseEnreplacedy<Resource> fetch(@PathVariable String key) {
    Storage litemallStorage = mallStorageService.findByKey(key);
    if (key == null) {
        return ResponseEnreplacedy.notFound().build();
    }
    if (key.contains("../")) {
        return ResponseEnreplacedy.badRequest().build();
    }
    String type = litemallStorage.getType();
    MediaType mediaType = MediaType.parseMediaType(type);
    Resource file = storageService.loadAsResource(key);
    if (file == null) {
        return ResponseEnreplacedy.notFound().build();
    }
    return ResponseEnreplacedy.ok().contentType(mediaType).body(file);
}

19 View Source File : ExampleControllerAdvice.java
License : Apache License 2.0
Project Creator : yuanmabiji

@ExceptionHandler(NoHandlerFoundException.clreplaced)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEnreplacedy<String> noHandlerFoundHandler(NoHandlerFoundException exception) {
    return ResponseEnreplacedy.badRequest().body("Invalid request: " + exception.getRequestURL());
}

19 View Source File : ClientResource.java
License : Apache License 2.0
Project Creator : xm-online

/**
 * POST /clients : Create a new client.
 * @param client the client to create
 * @return the ResponseEnreplacedy with status 201 (Created) and with body the new client, or with
 *         status 400 (Bad Request) if the client has already an ID
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PostMapping("/clients")
@Timed
@PreAuthorize("hasPermission({'client': #client}, 'CLIENT.CREATE')")
@PrivilegeDescription("Privilege to create a new client")
public ResponseEnreplacedy<Void> createClient(@RequestBody ClientDTO client) throws URISyntaxException {
    if (client.getId() != null) {
        return ResponseEnreplacedy.badRequest().headers(HeaderUtil.createFailureAlert(ENreplacedY_NAME, "idexists", "A new client cannot already have an ID")).body(null);
    }
    Client result = clientService.createClient(client);
    return ResponseEnreplacedy.created(new URI("/api/clients/" + result.getId())).headers(HeaderUtil.createEnreplacedyCreationAlert(ENreplacedY_NAME, result.getId().toString())).build();
}

19 View Source File : CustomerController.java
License : Apache License 2.0
Project Creator : wkorando

@DeleteMapping("/{id}")
public ResponseEnreplacedy<?> deleteCustomer(@PathVariable("id") long id) {
    boolean customerDelete = service.deleteResource(id);
    if (customerDelete) {
        return ResponseEnreplacedy.noContent().build();
    } else {
        List<String> errorMessages = new ArrayList<>();
        errorMessages.add("Resource does not exist or has already been deleted.");
        return ResponseEnreplacedy.badRequest().body(new ErrorResponse(errorMessages));
    }
}

19 View Source File : CustomerController.java
License : Apache License 2.0
Project Creator : wkorando

@PutMapping("/{id}")
public ResponseEnreplacedy<?> updateCustomer(@PathVariable("id") long id, @RequestBody Customer customer) {
    try {
        service.saveCustomer(customer);
        return ResponseEnreplacedy.noContent().build();
    } catch (RoomServiceException e) {
        return ResponseEnreplacedy.badRequest().body(new ErrorResponse(e.getErrorMessages()));
    }
}

19 View Source File : CustomerController.java
License : Apache License 2.0
Project Creator : wkorando

@PostMapping(consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public ResponseEnreplacedy<?> createNewCustomer(@RequestBody Customer customer) throws URISyntaxException {
    try {
        Customer newCustomer = service.saveCustomer(customer);
        return ResponseEnreplacedy.created(new URI("/customers/" + newCustomer.getId())).build();
    } catch (RoomServiceException e) {
        return ResponseEnreplacedy.badRequest().body(new ErrorResponse(e.getErrorMessages()));
    }
}

19 View Source File : ConnectionTypeResource.java
License : Apache License 2.0
Project Creator : viz-centric

/**
 * POST  /connection-types : Create a new connectionType.
 *
 * @param connectionTypeDTO the connectionTypeDTO to create
 * @return the ResponseEnreplacedy with status 201 (Created) and with body the new connectionTypeDTO, or with status 400 (Bad Request) if the connectionType has already an ID
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PostMapping("/connection-types")
@Timed
public ResponseEnreplacedy<ConnectionTypeDTO> createConnectionType(@Valid @RequestBody ConnectionTypeDTO connectionTypeDTO) throws URISyntaxException {
    log.debug("REST request to save ConnectionType : {}", connectionTypeDTO);
    if (connectionTypeDTO.getId() != null) {
        return ResponseEnreplacedy.badRequest().headers(HeaderUtil.createFailureAlert(ENreplacedY_NAME, "idexists", "A new connectionType cannot already have an ID")).body(null);
    }
    ConnectionTypeDTO result = connectionTypeService.save(connectionTypeDTO);
    return ResponseEnreplacedy.created(new URI("/api/connection-types/" + result.getId())).headers(HeaderUtil.createEnreplacedyCreationAlert(ENreplacedY_NAME, result.getId().toString())).body(result);
}

19 View Source File : ConnectionResource.java
License : Apache License 2.0
Project Creator : viz-centric

/**
 * POST  /connections : Create a new connection.
 *
 * @param connectionDTO the connectionDTO to create
 * @return the ResponseEnreplacedy with status 201 (Created) and with body the new connectionDTO, or with status 400 (Bad Request) if the connection has already an ID
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PostMapping("/connections")
@Timed
public ResponseEnreplacedy<ConnectionDTO> createConnection(@Valid @RequestBody ConnectionDTO connectionDTO) throws URISyntaxException {
    log.debug("REST request to save Connection : {}", connectionDTO);
    if (connectionDTO.getId() != null) {
        return ResponseEnreplacedy.badRequest().headers(HeaderUtil.createFailureAlert(ENreplacedY_NAME, "idexists", "A new connection cannot already have an ID")).body(null);
    }
    ConnectionDTO result = connectionService.save(connectionDTO);
    return ResponseEnreplacedy.created(new URI("/api/connections/" + result.getId())).headers(HeaderUtil.createEnreplacedyCreationAlert(ENreplacedY_NAME, result.getId().toString())).body(result);
}

19 View Source File : ConnectionResource.java
License : Apache License 2.0
Project Creator : viz-centric

/**
 * PUT  /connections : Updates an existing connection.
 *
 * @param connectionDTO the connectionDTO to update
 * @return the ResponseEnreplacedy with status 200 (OK) and with body the updated connectionDTO,
 * or with status 400 (Bad Request) if the connectionDTO is not valid,
 * or with status 500 (Internal Server Error) if the connectionDTO couldn't be updated
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PutMapping("/connections")
@Timed
public ResponseEnreplacedy<ConnectionDTO> updateConnection(@Valid @RequestBody UpdateConnectionDTO connectionDTO) throws URISyntaxException {
    log.debug("REST request to update Connection : {}", connectionDTO);
    if (connectionDTO.getId() == null) {
        return ResponseEnreplacedy.badRequest().body(null);
    }
    ConnectionDTO result = connectionService.updateConnection(connectionDTO);
    return ResponseEnreplacedy.ok().headers(HeaderUtil.createEnreplacedyUpdateAlert(ENreplacedY_NAME, connectionDTO.getId().toString())).body(result);
}

19 View Source File : AccountResource.java
License : Apache License 2.0
Project Creator : viz-centric

/**
 * POST  /account : update the current user information.
 *
 * @param userDTO the current user information
 * @return the ResponseEnreplacedy with status 200 (OK), or status 400 (Bad Request) or 500 (Internal Server Error) if the user couldn't be updated
 */
@PostMapping("/account")
@Timed
public ResponseEnreplacedy saveAccount(@Valid @RequestBody UserDTO userDTO) {
    final String userLogin = SecurityUtils.getCurrentUserLogin();
    Optional<User> existingUser = userRepository.findOneByEmail(userDTO.getEmail());
    if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) {
        return ResponseEnreplacedy.badRequest().headers(HeaderUtil.createFailureAlert("user-management", "emailexists", "Email already in use")).body(null);
    }
    return userRepository.findOneByLogin(userLogin).map(u -> {
        userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey(), userDTO.getImageUrl());
        return new ResponseEnreplacedy(HttpStatus.OK);
    }).orElseGet(() -> new ResponseEnreplacedy<>(HttpStatus.INTERNAL_SERVER_ERROR));
}

19 View Source File : WebMvcMovieController.java
License : Apache License 2.0
Project Creator : toedter

@GetMapping("/error")
public ResponseEnreplacedy<?> error() {
    // tag::errors-builder[]
    return ResponseEnreplacedy.badRequest().body(JsonApiErrors.create().withError(JsonApiError.create().withAboutLink("http://movie-db.com/problem").withreplacedle("Movie-based problem").withStatus(HttpStatus.BAD_REQUEST.toString()).withDetail("This is a test case")));
// end::errors-builder[]
}

19 View Source File : WebFluxMovieController.java
License : Apache License 2.0
Project Creator : toedter

@GetMapping("/error")
public ResponseEnreplacedy<?> error() {
    JsonApiErrors body = JsonApiErrors.create().withError(JsonApiError.create().withAboutLink("http://movie-db.com/problem").withreplacedle("Movie-based problem").withStatus(HttpStatus.BAD_REQUEST.toString()).withDetail("This is a test case"));
    return ResponseEnreplacedy.badRequest().body(body);
}

19 View Source File : MovieController.java
License : Apache License 2.0
Project Creator : toedter

@PostMapping("/movies")
public ResponseEnreplacedy<?> newMovie(@RequestBody EnreplacedyModel<Movie> movieModel) {
    Movie movie = movieModel.getContent();
    movieRepository.save(movie);
    List<Director> directorsWithIds = movie.getDirectors();
    List<Director> directors = new ArrayList<>();
    movie.setDirectors(directors);
    for (Director directorWithId : directorsWithIds) {
        directorRepository.findById(directorWithId.getId()).map(director -> {
            director.addMovie(movie);
            directorRepository.save(director);
            movie.addDirector(director);
            return director;
        });
    }
    movieRepository.save(movie);
    final RepresentationModel<?> movieRepresentationModel = movieModelreplacedembler.toJsonApiModel(movie, null);
    return movieRepresentationModel.getLink(IreplacedinkRelations.SELF).map(Link::getHref).map(href -> {
        try {
            return new URI(href);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }).map(uri -> ResponseEnreplacedy.created(uri).build()).orElse(ResponseEnreplacedy.badRequest().body("Unable to create " + movie));
}

19 View Source File : MovieController.java
License : Apache License 2.0
Project Creator : toedter

@PatchMapping("/movies/{id}")
public ResponseEnreplacedy<?> updateMoviePartially(@RequestBody Movie movie, @PathVariable Long id) {
    Movie existingMovie = movieRepository.findById(id).orElseThrow(() -> new EnreplacedyNotFoundException(id.toString()));
    existingMovie.update(movie);
    movieRepository.save(existingMovie);
    final RepresentationModel<?> movieRepresentationModel = movieModelreplacedembler.toJsonApiModel(movie, null);
    return movieRepresentationModel.getLink(IreplacedinkRelations.SELF).map(Link::getHref).map(href -> {
        try {
            return new URI(href);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }).map(// 
    uri -> ResponseEnreplacedy.noContent().location(uri).build()).orElse(ResponseEnreplacedy.badRequest().body("Unable to update " + existingMovie + " partially"));
}

19 View Source File : UserResource.java
License : MIT License
Project Creator : tillias

/**
 * {@code GET /users} : get all users.
 *
 * @param pageable the pagination information.
 * @return the {@link ResponseEnreplacedy} with status {@code 200 (OK)} and with body all users.
 */
@GetMapping("/users")
public ResponseEnreplacedy<List<UserDTO>> getAllUsers(Pageable pageable) {
    if (!onlyContainsAllowedProperties(pageable)) {
        return ResponseEnreplacedy.badRequest().build();
    }
    final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
    return new ResponseEnreplacedy<>(page.getContent(), headers, HttpStatus.OK);
}

19 View Source File : ConnectorsEndpoint.java
License : Apache License 2.0
Project Creator : syndesisio

@WriteOperation
public Object connector(Connector connector) {
    try {
        updateConnector(connector);
        return ResponseEnreplacedy.ok().build();
    } catch (Exception ex) {
        LOG.error("Error while updating the connector", ex);
        return ResponseEnreplacedy.badRequest().build();
    }
}

19 View Source File : ExceptionHandlers.java
License : MIT License
Project Creator : srcclr

/**
 * Mainly to deal with the fact that we use FreeBuilder for our API requests and if any compulsory fields
 * are missing, FreeBuilder's exception will result in a 500 Internal Server Error when it is a 400 Bad Request.
 */
@ExceptionHandler(HttpMessageConversionException.clreplaced)
public ResponseEnreplacedy<String> httpMessageConversionException(Exception ex) throws Exception {
    return ResponseEnreplacedy.badRequest().contentType(MediaType.APPLICATION_JSON).body(buildJsonStringMessage("Bad Request", ex.getMessage()));
}

19 View Source File : EmployeeController.java
License : Apache License 2.0
Project Creator : springdoc

@PostMapping("/employees")
@ResponseStatus(HttpStatus.CREATED)
ResponseEnreplacedy<EnreplacedyModel<Employee>> newEmployee(@RequestBody Employee employee) {
    try {
        Employee savedEmployee = repository.save(employee);
        EnreplacedyModel<Employee> employeeResource = new // 
        EnreplacedyModel<>(// 
        savedEmployee, linkTo(methodOn(EmployeeController.clreplaced).findOne(savedEmployee.getId())).withSelfRel());
        return // 
        ResponseEnreplacedy.created(// 
        new URI(employeeResource.getRequiredLink(IreplacedinkRelations.SELF).getHref())).body(employeeResource);
    } catch (URISyntaxException e) {
        return ResponseEnreplacedy.badRequest().body(null);
    }
}

19 View Source File : EmployeeController.java
License : Apache License 2.0
Project Creator : springdoc

@PostMapping("/employees")
ResponseEnreplacedy<EnreplacedyModel<Employee>> newEmployee(@RequestBody Employee employee) {
    try {
        Employee savedEmployee = repository.save(employee);
        EnreplacedyModel<Employee> employeeResource = new // 
        EnreplacedyModel<>(// 
        savedEmployee, linkTo(methodOn(EmployeeController.clreplaced).findOne(savedEmployee.getId())).withSelfRel());
        return // 
        ResponseEnreplacedy.created(// 
        new URI(employeeResource.getRequiredLink(IreplacedinkRelations.SELF).getHref())).body(employeeResource);
    } catch (URISyntaxException e) {
        return ResponseEnreplacedy.badRequest().body(null);
    }
}

19 View Source File : CustomOrderController.java
License : Apache License 2.0
Project Creator : spring-projects

@PostMapping("/orders/{id}/fulfill")
ResponseEnreplacedy<?> fulfill(@PathVariable Long id) {
    Order order = this.repository.findById(id).orElseThrow(() -> new OrderNotFoundException(id));
    if (valid(order.getOrderStatus(), OrderStatus.FULFILLED)) {
        order.setOrderStatus(OrderStatus.FULFILLED);
        return ResponseEnreplacedy.ok(repository.save(order));
    }
    return ResponseEnreplacedy.badRequest().body("Transitioning from " + order.getOrderStatus() + " to " + OrderStatus.FULFILLED + " is not valid.");
}

19 View Source File : CustomOrderController.java
License : Apache License 2.0
Project Creator : spring-projects

@PostMapping("/orders/{id}/pay")
ResponseEnreplacedy<?> pay(@PathVariable Long id) {
    Order order = this.repository.findById(id).orElseThrow(() -> new OrderNotFoundException(id));
    if (valid(order.getOrderStatus(), OrderStatus.PAID_FOR)) {
        order.setOrderStatus(OrderStatus.PAID_FOR);
        return ResponseEnreplacedy.ok(repository.save(order));
    }
    return ResponseEnreplacedy.badRequest().body("Transitioning from " + order.getOrderStatus() + " to " + OrderStatus.PAID_FOR + " is not valid.");
}

19 View Source File : EmployeeController.java
License : Apache License 2.0
Project Creator : spring-projects

@PostMapping("/employees")
ResponseEnreplacedy<?> newEmployee(@RequestBody Employee employee) {
    try {
        Employee savedEmployee = repository.save(employee);
        EnreplacedyModel<Employee> employeeResource = // 
        EnreplacedyModel.of(// 
        savedEmployee, linkTo(methodOn(EmployeeController.clreplaced).findOne(savedEmployee.getId())).withSelfRel());
        return // 
        ResponseEnreplacedy.created(// 
        new URI(employeeResource.getRequiredLink(IreplacedinkRelations.SELF).getHref())).body(employeeResource);
    } catch (URISyntaxException e) {
        return ResponseEnreplacedy.badRequest().body("Unable to create " + employee);
    }
}

19 View Source File : EmployeeController.java
License : Apache License 2.0
Project Creator : spring-projects

@PostMapping("/employees")
ResponseEnreplacedy<?> newEmployee(@RequestBody Employee employee) {
    Employee savedEmployee = repository.save(employee);
    return EnreplacedyModel.of(savedEmployee, linkTo(methodOn(EmployeeController.clreplaced).findOne(savedEmployee.getId())).withSelfRel().andAffordance(afford(methodOn(EmployeeController.clreplaced).updateEmployee(null, savedEmployee.getId()))).andAffordance(afford(methodOn(EmployeeController.clreplaced).deleteEmployee(savedEmployee.getId()))), linkTo(methodOn(EmployeeController.clreplaced).findAll()).withRel("employees")).getLink(IreplacedinkRelations.SELF).map(// 
    Link::getHref).map(href -> {
        try {
            return new URI(href);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }).map(uri -> ResponseEnreplacedy.noContent().location(uri).build()).orElse(ResponseEnreplacedy.badRequest().body("Unable to create " + employee));
}

19 View Source File : EmployeeController.java
License : Apache License 2.0
Project Creator : spring-projects

@PutMapping("/employees/{id}")
ResponseEnreplacedy<?> updateEmployee(@RequestBody Employee employee, @PathVariable long id) {
    Employee employeeToUpdate = employee;
    employeeToUpdate.setId(id);
    Employee updatedEmployee = repository.save(employeeToUpdate);
    return EnreplacedyModel.of(updatedEmployee, linkTo(methodOn(EmployeeController.clreplaced).findOne(updatedEmployee.getId())).withSelfRel().andAffordance(afford(methodOn(EmployeeController.clreplaced).updateEmployee(null, updatedEmployee.getId()))).andAffordance(afford(methodOn(EmployeeController.clreplaced).deleteEmployee(updatedEmployee.getId()))), linkTo(methodOn(EmployeeController.clreplaced).findAll()).withRel("employees")).getLink(IreplacedinkRelations.SELF).map(Link::getHref).map(href -> {
        try {
            return new URI(href);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }).map(// 
    uri -> ResponseEnreplacedy.noContent().location(uri).build()).orElse(ResponseEnreplacedy.badRequest().body("Unable to update " + employeeToUpdate));
}

19 View Source File : ExceptionControllerAdvice.java
License : Apache License 2.0
Project Creator : spring-petclinic

@ExceptionHandler(Exception.clreplaced)
public ResponseEnreplacedy<String> exception(Exception e) {
    ObjectMapper mapper = new ObjectMapper();
    ErrorInfo errorInfo = new ErrorInfo(e);
    String respJSONstring = "{}";
    try {
        respJSONstring = mapper.writeValuereplacedtring(errorInfo);
    } catch (JsonProcessingException e1) {
        e1.printStackTrace();
    }
    return ResponseEnreplacedy.badRequest().body(respJSONstring);
}

19 View Source File : LeaderController.java
License : Apache License 2.0
Project Creator : spring-cloud

/**
 * PUT request to try and revoke a leadership of this instance. If the instance is not
 * a leader, leadership cannot be revoked. Thus "HTTP Bad Request" response. If the
 * instance is a leader, it must have a leadership context instance which can be used
 * to give up the leadership.
 * @return info about leadership
 */
@PutMapping
public ResponseEnreplacedy<String> revokeLeadership() {
    if (this.context == null) {
        String message = String.format("Cannot revoke leadership because '%s' is not a leader", this.host);
        return ResponseEnreplacedy.badRequest().body(message);
    }
    this.context.yield();
    String message = String.format("Leadership revoked for '%s'", this.host);
    return ResponseEnreplacedy.ok(message);
}

19 View Source File : ChatController.java
License : MIT License
Project Creator : rybalkinsd

/**
 * curl -i localhost:8080/chat/chat
 */
@RequestMapping(path = "chat", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEnreplacedy<String> chat() {
    return ResponseEnreplacedy.badRequest().build();
}

@Override
public ResponseEnreplacedy<?> renewAuthenticationToken(HttpServletRequest request) {
    String token = request.getHeader(tokenHeader);
    if (jwtTokenUtil.canTokenBeRefreshed(token)) {
        String refreshedToken = jwtTokenUtil.refreshToken(token);
        return ResponseEnreplacedy.ok(new JwtAuthenticationResponse(refreshedToken));
    } else {
        return ResponseEnreplacedy.badRequest().body(null);
    }
}

19 View Source File : RestExceptionHandler.java
License : Apache License 2.0
Project Creator : rancho00

/**
 * 处理badRequestException异常
 * @param badRequestException
 * @return
 */
@ExceptionHandler(BadRequestException.clreplaced)
public ResponseEnreplacedy<CommonResult> handleBadRequestException(BadRequestException badRequestException) {
    log.error("错误请求异常-------->:{}", badRequestException.getResultCode().getMessage());
    return ResponseEnreplacedy.badRequest().body(new CommonResult(badRequestException.getResultCode().getCode(), badRequestException.getResultCode().getMessage()));
}

19 View Source File : RestExceptionHandler.java
License : Apache License 2.0
Project Creator : rancho00

/**
 * 处理 @RequestBody参数校验异常
 * @param e
 * @return
 */
@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
public ResponseEnreplacedy<CommonResult> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    String errorMsg = e.getBindingResult().getAllErrors().stream().map(objectError -> ((FieldError) objectError).getDefaultMessage()).collect(Collectors.joining(","));
    log.error("RequestBody参数绑定异常-------->:{}", errorMsg);
    return ResponseEnreplacedy.badRequest().body(CommonResult.badRequest(errorMsg));
}

19 View Source File : RestExceptionHandler.java
License : Apache License 2.0
Project Creator : rancho00

/**
 * 处理不带任何注解的参数绑定校验异常
 * @param e
 * @return
 */
@ExceptionHandler(BindException.clreplaced)
public ResponseEnreplacedy<CommonResult> handleBingException(BindException e) {
    String errorMsg = e.getBindingResult().getAllErrors().stream().map(objectError -> ((FieldError) objectError).getField() + ((FieldError) objectError).getDefaultMessage()).collect(Collectors.joining(","));
    // "errorMsg": "name不能为空,age最小不能小于18"
    log.error("参数绑定异常-------->:{}", errorMsg);
    return ResponseEnreplacedy.badRequest().body(CommonResult.badRequest(errorMsg));
}

19 View Source File : AdminExceptionHandler.java
License : GNU Affero General Public License v3.0
Project Creator : ramostear

@ExceptionHandler(BadRequestException.clreplaced)
public ResponseEnreplacedy<Object> badRequestExceptionHandler(BadRequestException e) {
    log.info(e.getMessage());
    return ResponseEnreplacedy.badRequest().build();
}

19 View Source File : GaenV2Controller.java
License : Mozilla Public License 2.0
Project Creator : RadarCOVID

@ExceptionHandler({ IllegalArgumentException.clreplaced, InvalidDateException.clreplaced, JsonProcessingException.clreplaced, MethodArgumentNotValidException.clreplaced, BadBatchReleaseTimeException.clreplaced, DateTimeParseException.clreplaced, ClaimIsBeforeOnsetException.clreplaced, KeyFormatException.clreplaced })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEnreplacedy<Object> invalidArguments() {
    return ResponseEnreplacedy.badRequest().build();
}

19 View Source File : GaenController.java
License : Mozilla Public License 2.0
Project Creator : RadarCOVID

@ExceptionHandler({ DelayedKeyDateIsInvalid.clreplaced })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEnreplacedy<String> delayedKeyDateIsInvalid(Exception ex) {
    logger.error("Exception ({}): {}", ex.getClreplaced().getSimpleName(), ex.getMessage());
    return ResponseEnreplacedy.badRequest().body("DelayedKeyDate must be between yesterday and tomorrow");
}

19 View Source File : GaenController.java
License : Mozilla Public License 2.0
Project Creator : RadarCOVID

@ExceptionHandler({ IllegalArgumentException.clreplaced, InvalidDateException.clreplaced, JsonProcessingException.clreplaced, MethodArgumentNotValidException.clreplaced, BadBatchReleaseTimeException.clreplaced, DateTimeParseException.clreplaced, ClaimIsBeforeOnsetException.clreplaced, KeyFormatException.clreplaced })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEnreplacedy<Object> invalidArguments(Exception ex) {
    logger.error("Exception ({}): {}", ex.getClreplaced().getSimpleName(), ex.getMessage());
    return ResponseEnreplacedy.badRequest().build();
}

19 View Source File : GaenController.java
License : Mozilla Public License 2.0
Project Creator : RadarCOVID

@ExceptionHandler({ DelayedKeyDateClaimIsMissing.clreplaced })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEnreplacedy<String> delayedClaimIsWrong(Exception ex) {
    logger.error("Exception ({}): {}", ex.getClreplaced().getSimpleName(), ex.getMessage());
    return ResponseEnreplacedy.badRequest().body("DelayedKeyDateClaim is wrong");
}

19 View Source File : WxStorageController.java
License : GNU Lesser General Public License v3.0
Project Creator : qiguliuxing

/**
 * 访问存储对象
 *
 * @param key
 *            存储对象key
 * @return
 */
@GetMapping("/fetch/{key:.+}")
public ResponseEnreplacedy<Resource> fetch(@PathVariable String key) {
    // logger.info("【请求开始】访问存储对象,请求参数,key:{}", key);
    DtsStorage DtsStorage = DtsStorageService.findByKey(key);
    if (key == null) {
        return ResponseEnreplacedy.notFound().build();
    }
    if (key.contains("../")) {
        return ResponseEnreplacedy.badRequest().build();
    }
    String type = DtsStorage.getType();
    MediaType mediaType = MediaType.parseMediaType(type);
    Resource file = storageService.loadAsResource(key);
    if (file == null) {
        return ResponseEnreplacedy.notFound().build();
    }
    // logger.info("【请求结束】访问存储对象,响应结果:{}","成功");
    return ResponseEnreplacedy.ok().contentType(mediaType).body(file);
}

19 View Source File : WxStorageController.java
License : GNU Lesser General Public License v3.0
Project Creator : qiguliuxing

/**
 * 访问存储对象
 *
 * @param key
 *            存储对象key
 * @return
 */
@GetMapping("/download/{key:.+}")
public ResponseEnreplacedy<Resource> download(@PathVariable String key) {
    // logger.info("【请求开始】访问存储对象,请求参数,key:{}", key);
    DtsStorage DtsStorage = DtsStorageService.findByKey(key);
    if (key == null) {
        return ResponseEnreplacedy.notFound().build();
    }
    if (key.contains("../")) {
        return ResponseEnreplacedy.badRequest().build();
    }
    String type = DtsStorage.getType();
    MediaType mediaType = MediaType.parseMediaType(type);
    Resource file = storageService.loadAsResource(key);
    if (file == null) {
        return ResponseEnreplacedy.notFound().build();
    }
    // logger.info("【请求结束】访问存储对象,响应结果:{}","成功");
    return ResponseEnreplacedy.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
}

19 View Source File : CountryLanguageAPIController.java
License : MIT License
Project Creator : PacktPublishing

@PostMapping("/{countryCode}")
public ResponseEnreplacedy<?> addLanguage(@PathVariable String countryCode, @Valid @RequestBody CountryLanguage language) {
    try {
        if (cLanguageDao.languageExists(countryCode, language.getLanguage())) {
            return ResponseEnreplacedy.badRequest().body("Language already exists for country");
        }
        cLanguageDao.addLanguage(countryCode, language);
        return ResponseEnreplacedy.ok(language);
    } catch (Exception ex) {
        System.out.println("Error while adding language: {} to country: {}" + language + countryCode + ex);
        return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error while adding language");
    }
}

See More Examples