org.springframework.http.HttpStatus Java Examples
The following examples show how to use
org.springframework.http.HttpStatus.
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 |
@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: PipelineInitiator.java From echo with Apache License 2.0 | 6 votes |
private static boolean isRetryableError(Throwable error) { if (!(error instanceof RetrofitError)) { return false; } RetrofitError retrofitError = (RetrofitError) error; if (retrofitError.getKind() == Kind.NETWORK) { return true; } if (retrofitError.getKind() == Kind.HTTP) { Response response = retrofitError.getResponse(); return (response != null && response.getStatus() != HttpStatus.BAD_REQUEST.value()); } return false; }
Example #3
Source File: PageRedirectionTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
/** * Test ui instance of staticclient */ @Test @TestsNotMeantForZowe public void uiRouteOfDiscoverableClient() { String location = String.format("%s://%s:%d%s", dcScheme, dcHost, dcPort, BASE_URL); String uiPrefix = "/ui/v1"; String transformedLocation = String.format("%s://%s:%d%s%s", gatewayScheme, gatewayHost, gatewayPort, uiPrefix, "/" + SERVICE_ID); RedirectLocation redirectLocation = new RedirectLocation(location); given() .contentType(JSON) .body(redirectLocation) .when() .post(requestUrl) .then() .statusCode(is(HttpStatus.TEMPORARY_REDIRECT.value())) .header(LOCATION, transformedLocation); }
Example #4
Source File: ErrorController.java From Spring-Security-Third-Edition with MIT License | 6 votes |
@ExceptionHandler(Throwable.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ModelAndView exception(final Throwable throwable, final Model model) { logger.error("Exception during execution of SpringSecurity application", throwable); StringBuffer sb = new StringBuffer(); sb.append("Exception during execution of Spring Security application! "); sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error")); sb.append(", root cause: ").append((throwable != null && throwable.getCause() != null ? throwable.getCause() : "Unknown cause")); model.addAttribute("error", sb.toString()); ModelAndView mav = new ModelAndView(); mav.addObject("error", sb.toString()); mav.setViewName("error"); return mav; }
Example #5
Source File: RestTemplateTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void exchange() throws Exception { mockTextPlainHttpMessageConverter(); HttpHeaders requestHeaders = new HttpHeaders(); mockSentRequest(POST, "https://example.com", requestHeaders); mockResponseStatus(HttpStatus.OK); String expected = "42"; mockResponseBody(expected, MediaType.TEXT_PLAIN); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.set("MyHeader", "MyValue"); HttpEntity<String> entity = new HttpEntity<>("Hello World", entityHeaders); ResponseEntity<String> result = template.exchange("https://example.com", POST, entity, String.class); assertEquals("Invalid POST result", expected, result.getBody()); assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader")); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); verify(response).close(); }
Example #6
Source File: AnnotationsApiController.java From oncokb with GNU Affero General Public License v3.0 | 6 votes |
@PublicApi @PremiumPublicApi @ApiOperation(value = "", notes = "Annotate mutations by genomic change.", response = IndicatorQueryResp.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = IndicatorQueryResp.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Error, error message will be given.", response = String.class)}) @RequestMapping(value = "/annotate/mutations/byHGVSg", consumes = {"application/json"}, produces = {"application/json"}, method = RequestMethod.POST) public ResponseEntity<List<IndicatorQueryResp>> annotateMutationsByHGVSgPost( @ApiParam(value = "List of queries. Please see swagger.json for request body format.", required = true) @RequestBody() List<AnnotateMutationByHGVSgQuery> body ) { HttpStatus status = HttpStatus.OK; List<IndicatorQueryResp> result = new ArrayList<>(); if (body == null) { status = HttpStatus.BAD_REQUEST; } else { for (AnnotateMutationByHGVSgQuery query : body) { result.add(IndicatorUtils.processQuery(new Query(query), null, false, query.getEvidenceTypes())); } } return new ResponseEntity<>(result, status); }
Example #7
Source File: AccountController.java From cf-SpringBootTrader with Apache License 2.0 | 6 votes |
/** * REST call to decrease the balance in the account. Decreases the balance * of the account if the new balance is not lower than zero. Returns HTTP OK * and the new balance if the decrease was successful, or HTTP * EXPECTATION_FAILED if the new balance would be negative and the * old/current balance. * * @param userId * The id of the account. * @param amount * The amount to decrease the balance by. * @return The new balance of the account with HTTP OK. */ @RequestMapping(value = "/accounts/{userId}/decreaseBalance/{amount}", method = RequestMethod.GET) public ResponseEntity<Double> decreaseBalance(@PathVariable("userId") final String userId, @PathVariable("amount") final double amount) { logger.debug("AccountController.decreaseBalance: id='" + userId + "', amount='" + amount + "'"); Account accountResponse = this.service.findAccount(userId); BigDecimal currentBalance = accountResponse.getBalance(); BigDecimal newBalance = currentBalance.subtract(new BigDecimal(amount)); if (newBalance.compareTo(BigDecimal.ZERO) >= 0) { accountResponse.setBalance(newBalance); this.service.saveAccount(accountResponse); return new ResponseEntity<Double>(accountResponse.getBalance().doubleValue(), getNoCacheHeaders(), HttpStatus.OK); } else { // no sufficient founds available return new ResponseEntity<Double>(accountResponse.getBalance().doubleValue(), getNoCacheHeaders(), HttpStatus.EXPECTATION_FAILED); } }
Example #8
Source File: AmqpMessageHandlerServiceTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Test @Description("Tests that an download request is denied for an artifact which is not assigned to the requested target") public void authenticationRequestDeniedForArtifactWhichIsNotAssignedToTarget() { final MessageProperties messageProperties = createMessageProperties(null); final DmfTenantSecurityToken securityToken = new DmfTenantSecurityToken(TENANT, TENANT_ID, CONTROLLER_ID, TARGET_ID, FileResource.createFileResourceBySha1("12345")); final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken, messageProperties); final Artifact localArtifactMock = mock(Artifact.class); when(artifactManagementMock.findFirstBySHA1(anyString())).thenReturn(Optional.of(localArtifactMock)); // test final Message onMessage = amqpAuthenticationMessageHandlerService.onAuthenticationRequest(message); // verify final DmfDownloadResponse downloadResponse = (DmfDownloadResponse) messageConverter.fromMessage(onMessage); assertThat(downloadResponse).as("Message body should not null").isNotNull(); assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong") .isEqualTo(HttpStatus.NOT_FOUND.value()); }
Example #9
Source File: DeviceFirmwareUpdateRestControllerTest.java From konker-platform with Apache License 2.0 | 5 votes |
@Test public void shouldReturnInternalErrorWhenListDeviceFirmwaresVersionUpdates() throws Exception { List<DeviceFirmware> firmwares = new ArrayList<>(); firmwares.add(deviceFirmwareNew); firmwares.add(deviceFirmwareNew); List<DeviceFwUpdate> firmwaresUpdates = new ArrayList<>(); firmwaresUpdates.add(deviceFwUpdatePendingRequest); firmwaresUpdates.add(deviceFwUpdatePendingRequest); when(deviceRegisterService.getByDeviceGuid(tenant, application, device.getGuid())) .thenReturn(ServiceResponseBuilder.<Device>ok().withResult(device).build()); when(deviceFirmwareService.findByVersion(tenant, application, device.getDeviceModel(), deviceFwUpdatePendingUpdate.getVersion())) .thenReturn(ServiceResponseBuilder.<DeviceFirmware>ok().withResult(deviceFirmwareNew).build()); when(deviceFirmwareUpdateService.findByDeviceFirmware(tenant, application, deviceFirmwareNew)) .thenReturn(ServiceResponseBuilder.<List<DeviceFwUpdate>> error() .withMessage(DeviceFirmwareUpdateService.Validations.FIRMWARE_UPDATE_NOT_FOUND.getCode()).build()); getMockMvc().perform(MockMvcRequestBuilders .get(MessageFormat.format("/{0}/{1}/", application.getName(), BASEPATH_UPDATE)) .param("deviceGuid", device.getGuid()) .param("version", deviceFwUpdatePendingUpdate.getVersion()) .contentType(MediaType.MULTIPART_FORM_DATA) .accept(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(status().is5xxServerError()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.code", is(HttpStatus.INTERNAL_SERVER_ERROR.value()))) .andExpect(jsonPath("$.status", is("error"))) .andExpect(jsonPath("$.timestamp", greaterThan(1400000000))) .andExpect(jsonPath("$.messages[0]", is("Firmware update process not found"))) .andExpect(jsonPath("$.result").doesNotExist()); }
Example #10
Source File: BookingController.java From Mastering-Microservices-with-Java-9-Second-Edition with MIT License | 5 votes |
/** * Fetch bookings with the given id. * <code>http://.../v1/bookings/{id}</code> will return booking with given * id. * * @param id * @return A non-null, non-empty collection of bookings. */ @RequestMapping(value = "/{id}", method = RequestMethod.GET) public ResponseEntity<Entity> findById(@PathVariable("id") String id) { logger.info(String.format("booking-service findById() invoked:{} for {} ", bookingService.getClass().getName(), id)); id = id.trim(); Entity booking; try { booking = bookingService.findById(id); } catch (Exception ex) { logger.log(Level.WARNING, "Exception raised findById REST Call {0}", ex); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } return booking != null ? new ResponseEntity<>(booking, HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NO_CONTENT); }
Example #11
Source File: TodoListApi_IT.java From syndesis with Apache License 2.0 | 5 votes |
@Test @CitrusTest public void testGetOpenApiSpec(@CitrusResource TestCaseRunner runner) { cleanupDatabase(runner); runner.given(waitFor().http() .method(HttpMethod.GET.name()) .seconds(10L) .status(HttpStatus.OK.value()) .url(String.format("http://localhost:%s/actuator/health", integrationContainer.getManagementPort()))); runner.when(http().client(todoListApiClient) .send() .get("/openapi.json")); runner.then(http().client(todoListApiClient) .receive() .response(HttpStatus.OK) .contentType(VND_OAI_OPENAPI_JSON) .payload(new ClassPathResource("todolist-api.json", TodoApi_IT.class))); }
Example #12
Source File: ProductController.java From logging-log4j-audit with Apache License 2.0 | 5 votes |
@PostMapping(value = "/create") public ResponseEntity<Map<String, Object>> createProduct(@RequestBody Product product) { Map<String, Object> response = new HashMap<>(); try { ProductModel model = productConverter.convert(product); model = productService.saveProduct(model); response.put("Result", "OK"); response.put("Records", productModelConverter.convert(model)); } catch (Exception ex) { response.put("Result", "FAILURE"); } return new ResponseEntity<>(response, HttpStatus.OK); }
Example #13
Source File: ZoneController.java From kaif with Apache License 2.0 | 5 votes |
private Object resolveZone(HttpServletRequest request, String decodedRawZone, Function<ZoneInfo, ModelAndView> onZoneInfo) { // note that decodedRawZone already do http url decode, and PathVariable already trim() // space of value return Zone.tryFallback(decodedRawZone).map(zone -> { if (!zone.value().equals(decodedRawZone)) { String orgUrl = request.getRequestURL().toString(); // replace pattern is combine of fallback pattern and valid pattern // TODO refactor replace rule to Zone String location = orgUrl.replaceFirst("/z/[a-zA-Z0-9_\\-]+", "/z/" + zone); //check if fallback success, this prevent infinite redirect loop if (!location.equals(orgUrl)) { RedirectView redirectView = new RedirectView(location); redirectView.setPropagateQueryParams(true); redirectView.setExpandUriTemplateVariables(false); redirectView.setExposeModelAttributes(false); redirectView.setExposeContextBeansAsAttributes(false); redirectView.setExposePathVariables(false); redirectView.setContextRelative(true); redirectView.setStatusCode(HttpStatus.PERMANENT_REDIRECT); return redirectView; } } return onZoneInfo.apply(zoneService.loadZone(zone)); }).orElseThrow(() -> new EmptyResultDataAccessException("no such zone: " + decodedRawZone, 1)); }
Example #14
Source File: GlobalExceptionAdvice.java From fw-cloud-framework with MIT License | 5 votes |
@ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public R<Exception> exception(Exception e) { log.info("全局异常信息: {}", e.getMessage(), e); return new R<Exception>().data(e).failure("全局异常信息"); }
Example #15
Source File: AppsApi.java From swagger-aem with Apache License 2.0 | 5 votes |
@ApiOperation(value = "", nickname = "postConfigApacheSlingDavExServlet", notes = "", authorizations = { @Authorization(value = "aemAuth") }, tags={ "sling", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Default response") }) @RequestMapping(value = "/apps/system/config/org.apache.sling.jcr.davex.impl.servlets.SlingDavExServlet", method = RequestMethod.POST) default ResponseEntity<Void> postConfigApacheSlingDavExServlet(@ApiParam(value = "") @Valid @RequestParam(value = "alias", required = false) String alias,@ApiParam(value = "") @Valid @RequestParam(value = "alias@TypeHint", required = false) String aliasAtTypeHint,@ApiParam(value = "") @Valid @RequestParam(value = "dav.create-absolute-uri", required = false) Boolean davCreateAbsoluteUri,@ApiParam(value = "") @Valid @RequestParam(value = "dav.create-absolute-uri@TypeHint", required = false) String davCreateAbsoluteUriAtTypeHint) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); }
Example #16
Source File: EndpointErrorHandler.java From Mastering-Microservices-with-Java-Third-Edition with MIT License | 5 votes |
@ExceptionHandler(RestaurantNotFoundException.class) public ResponseEntity<ErrorInfo> handleRestaurantNotFoundException(HttpServletRequest request, RestaurantNotFoundException 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 #17
Source File: UpdateController.java From metron with Apache License 2.0 | 5 votes |
@ApiOperation(value = "Update a document with a patch") @ApiResponse(message = "Returns the complete patched document.", code = 200) @RequestMapping(value = "/patch", method = RequestMethod.PATCH) ResponseEntity<Document> patch( final @ApiParam(name = "request", value = "Patch request", required = true) @RequestBody PatchRequest request ) throws RestException { try { return new ResponseEntity<>(service.patch(request), HttpStatus.OK); } catch (OriginalNotFoundException e) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } }
Example #18
Source File: RaceParticipantResource.java From gpmr with Apache License 2.0 | 5 votes |
/** * GET /race-participants : get all the raceParticipants. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of raceParticipants in body * @throws URISyntaxException if there is an error to generate the pagination HTTP headers */ @RequestMapping(value = "/race-participants", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<List<RaceParticipant>> getAllRaceParticipants(Pageable pageable) throws URISyntaxException { log.debug("REST request to get a page of RaceParticipants"); Page<RaceParticipant> page = raceParticipantRepository.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/race-participants"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); }
Example #19
Source File: JavametricsRestController.java From javametrics with Apache License 2.0 | 5 votes |
@RequestMapping(produces = "application/json", path = "/collections/{id}", method = RequestMethod.DELETE) public ResponseEntity<?> deleteCollection(@PathVariable("id") int id) { if (!mp.removeContext(id)) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(HttpStatus.NO_CONTENT); }
Example #20
Source File: GlobalExceptionHandler.java From Guns with GNU Lesser General Public License v3.0 | 5 votes |
/** * 认证异常--没有访问权限 */ @ExceptionHandler(PermissionException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody public ErrorResponseData permissionExpection(PermissionException e) { return new ErrorResponseData(e.getCode(), e.getMessage()); }
Example #21
Source File: MetaMtmCascadeExtController.java From youran with Apache License 2.0 | 5 votes |
@Override @PostMapping(value = "/save") @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<MetaMtmCascadeExtShowVO> save(@Valid @RequestBody MetaMtmCascadeExtAddDTO metaMtmCascadeExtAddDTO) throws Exception { MetaMtmCascadeExtPO metaMtmCascadeExt = metaMtmCascadeExtService.save(metaMtmCascadeExtAddDTO); return ResponseEntity.created(new URI(apiPath + "/metaMtmCascadeExt/" + metaMtmCascadeExt.getMtmCascadeExtId())) .body(MetaMtmCascadeExtMapper.INSTANCE.toShowVO(metaMtmCascadeExt)); }
Example #22
Source File: BrowserSecurityController.java From SpringAll with MIT License | 5 votes |
@GetMapping("/authentication/require") @ResponseStatus(HttpStatus.UNAUTHORIZED) public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { SavedRequest savedRequest = requestCache.getRequest(request, response); if (savedRequest != null) { String targetUrl = savedRequest.getRedirectUrl(); if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) redirectStrategy.sendRedirect(request, response, "/login.html"); } return "访问的资源需要身份认证!"; }
Example #23
Source File: SpringCloudInfoRestController.java From spring-cloud-release-tools with Apache License 2.0 | 5 votes |
@GetMapping("/bomversions/{bomVersion}") public Map<String, String> bomVersions(@PathVariable String bomVersion) throws IOException { try { return versionService.getReleaseVersions(bomVersion); } catch (SpringCloudVersionNotFoundException e) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage()); } }
Example #24
Source File: DetectionTest.java From weslang with Apache License 2.0 | 5 votes |
@Test public void testDetectionEnglishPost() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity req = new HttpEntity<>("q=this is a text in english", headers); ResponseEntity<DetectionResult> response = this.rest.postForEntity( getUrl("/detect"), req, DetectionResult.class); assertEquals(HttpStatus.OK, response.getStatusCode()); DetectionResult result = response.getBody(); assertEquals("en", result.getLanguage()); assertTrue(result.getConfidence() > 0.8); }
Example #25
Source File: BookingController.java From Microservices-Building-Scalable-Software with MIT License | 5 votes |
/** * Fetch bookings with the specified name. A partial case-insensitive match * is supported. So <code>http://.../booking/rest</code> will find any * bookings with upper or lower case 'rest' in their name. * * @param name * @return A non-null, non-empty collection of bookings. */ @RequestMapping(method = RequestMethod.GET) public ResponseEntity<Collection<Booking>> findByName(@RequestParam("name") String name) { logger.info(String.format("booking-service findByName() invoked:{} for {} ", bookingService.getClass().getName(), name)); name = name.trim().toLowerCase(); Collection<Booking> bookings; try { bookings = bookingService.findByName(name); } catch (Exception ex) { logger.log(Level.SEVERE, "Exception raised findByName REST Call", ex); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } return bookings.size() > 0 ? new ResponseEntity<>(bookings, HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NO_CONTENT); }
Example #26
Source File: NotAcceptableAdviceTraitTest.java From problem-spring-web with MIT License | 5 votes |
@Test void notAcceptableNoProblem() { Problem problem = webTestClient().get().uri("http://localhost/api/handler-ok") .accept(MediaType.IMAGE_PNG) .exchange() .expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE) .expectHeader().contentType(MediaTypes.PROBLEM) .expectBody(Problem.class).returnResult().getResponseBody(); assertThat(problem.getType().toString(), is("about:blank")); assertThat(problem.getTitle(), is("Not Acceptable")); assertThat(problem.getStatus(), is(Status.NOT_ACCEPTABLE)); assertThat(problem.getDetail(), containsString("Could not find acceptable representation")); }
Example #27
Source File: ChaosMonkeyRestEndpoint.java From chaos-monkey-spring-boot with Apache License 2.0 | 5 votes |
@GetMapping("/status") public ResponseEntity<String> getStatus() { if (this.chaosMonkeySettings.getChaosMonkeyProperties().isEnabled()) { return ResponseEntity.status(HttpStatus.OK).body("Ready to be evil!"); } else { return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("You switched me off!"); } }
Example #28
Source File: AbstractRestaurantControllerTests.java From Microservices-Building-Scalable-Software with MIT License | 5 votes |
/** * Test method for findById method */ @Test public void validResturantById() { Logger.getGlobal().info("Start validResturantById test"); ResponseEntity<Entity> restaurant = restaurantController.findById(RESTAURANT); Assert.assertEquals(HttpStatus.OK, restaurant.getStatusCode()); Assert.assertTrue(restaurant.hasBody()); Assert.assertNotNull(restaurant.getBody()); Assert.assertEquals(RESTAURANT, restaurant.getBody().getId()); Assert.assertEquals(RESTAURANT_NAME, restaurant.getBody().getName()); Logger.getGlobal().info("End validResturantById test"); }
Example #29
Source File: StoreCouponIssueController.java From yshopmall with Apache License 2.0 | 5 votes |
@Log("删除") @ApiOperation(value = "删除") @DeleteMapping(value = "/yxStoreCouponIssue/{id}") @PreAuthorize("@el.check('admin','YXSTORECOUPONISSUE_ALL','YXSTORECOUPONISSUE_DELETE')") public ResponseEntity delete(@PathVariable Integer id){ YxStoreCouponIssue resources = new YxStoreCouponIssue(); resources.setId(id); resources.setIsDel(1); yxStoreCouponIssueService.saveOrUpdate(resources); return new ResponseEntity(HttpStatus.OK); }
Example #30
Source File: UserController.java From spring-boot-study with MIT License | 5 votes |
/** * 编辑一个用户对象 * 幂等性 * */ @PutMapping("/users/{id}") @ResponseStatus(HttpStatus.CREATED) public Object editUser(@PathVariable("id") String id,@RequestBody UserDO user){ List<UserDO> list= getData(); for (UserDO userDO1:list ) { if(id.equals(userDO1.getUserId().toString())){ userDO1=user; break; } } return user; }