@CrossOrigin @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Find applicants of a given project", notes = "Returns a collection of projects") @ApiResponses(value = { @ApiResponse(code = 404, message = "Applicants not found") }) public ResponseEntity<List<UserDTO>> getApplicants(@ApiParam(value = "ID of project", required = true) @PathVariable("id") Integer projectId) { List<UserDTO> applicants = userService.getApplicants(projectId); if (!applicants.isEmpty()) { return ResponseEntity.ok().body(applicants); }else{ throw new NotFoundException("Applicants not found"); } }
@RequestMapping(method = RequestMethod.POST) @ResponseBody public ResponseEntity<?> addOrder(@RequestBody OrderDto orderDto) { LOGGER.info("Start addOrder: {}", orderDto); Order order = Order.toEntity(orderDto); orderService.saveOrUpdate(order); return new ResponseEntity<>(OrderDto.toDto(order), HttpStatus.CREATED); }
@RequestMapping(value = "/{instanceId}/service_bindings/{bindingId}", method = RequestMethod.PUT) public ResponseEntity<ServiceInstanceBindingResponse> bindServiceInstance( @PathVariable("instanceId") String instanceId, @PathVariable("bindingId") String bindingId, @Valid @RequestBody ServiceInstanceBindingRequest request) throws ServiceInstanceDoesNotExistException, ServiceInstanceBindingExistsException, ServiceBrokerException, ServiceDefinitionDoesNotExistException { log.debug("PUT: " + SERVICE_INSTANCE_BINDING_BASE_PATH + "/{bindingId}" + ", bindServiceInstance(), instanceId = " + instanceId + ", bindingId = " + bindingId); Map<String, String> bindResource = request.getBindResource(); String route = (bindResource != null) ? bindResource.get("route") : null; ServiceInstanceBindingResponse response = bindingService.createServiceInstanceBinding(bindingId, instanceId, request.getServiceDefinitionId(), request.getPlanId(), (request.getAppGuid() == null), route); log.debug("ServiceInstanceBinding Created: " + bindingId); return new ResponseEntity<ServiceInstanceBindingResponse>(response, HttpStatus.CREATED); }
/** * 执行POST请求 * * @param url * @param contentType * @param requestBody * @return */ protected WebhookRequestResponse doPost(String url, String contentType, Object requestBody) { // 请求头 HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.parseMediaType(contentType)); HttpEntity<?> requestEntity = new HttpEntity(requestBody, requestHeaders); try { // 执行请求 ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); // 返回响应结果 return new WebhookRequestResponse(requestHeaders, requestBody, responseEntity); } catch (Exception e) { return new WebhookRequestResponse(requestHeaders, requestBody, e); } }
private ResponseEntity<BaseResource> doPutResource(final BaseResource resource, final String resourceIdentifier) { try { boolean createdResource = this.service.upsertResource(resource); URI resourceUri = UriTemplateUtils.expand(MANAGED_RESOURCE_URL, "resourceIdentifier:" + resourceIdentifier); if (createdResource) { return created(resourceUri.getPath(), false); } // CHECK if path returns the right info return created(resourceUri.getPath(), true); } catch (Exception e) { throw new RestApiException(HttpStatus.UNPROCESSABLE_ENTITY, e); } }
/** * Gets all individual to do lists for a user * @param userId the uesr id to find by * @return the response entity with the to do lists */ @RequestMapping(method = RequestMethod.GET, value = "/individual/users/{userId}", produces = "application/json") public ResponseEntity getAllIndividualTodoListsForUser(@PathVariable("userId") Long userId) { // check if the user for the to do list exists UserServiceCommunication userServiceCommunication = new UserServiceCommunication(); UserPOJO userPOJO = userServiceCommunication.getUser(userId); if(userPOJO == null) { String message = "Could not find user with id " + userId; String url = "todolist/individual"; throw new UserNotFoundException(message, url); } List<TodoList> todoLists = this.todoListService.getIndividualTodoListsForUser(userId); return ResponseEntity.ok(todoLists); }
private void add(BuildInfo buildInfo) { URI uri = UriComponentsBuilder.fromUriString(this.uri).path("api/build") .buildAndExpand(NO_VARIABLES).encode().toUri(); RequestEntity<BuildInfo> request = RequestEntity.put(uri) .contentType(MediaType.APPLICATION_JSON).body(buildInfo); ResponseEntity<Void> exchange = this.restTemplate.exchange(request, Void.class); exchange.getBody(); }
/** * PUT /users : Updates an existing User. * * @param managedUserVM the user to update * @return the ResponseEntity with status 200 (OK) and with body the updated user, * or with status 400 (Bad Request) if the login or email is already in use, * or with status 500 (Internal Server Error) if the user couldn't be updated */ @PutMapping("/users") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<ManagedUserVM> updateUser(@RequestBody ManagedUserVM managedUserVM) { log.debug("REST request to update User : {}", managedUserVM); Optional<User> existingUser = userRepository.findOneByEmail(managedUserVM.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("userManagement", "emailexists", "E-mail already in use")).body(null); } existingUser = userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("userManagement", "userexists", "Login already in use")).body(null); } userService.updateUser(managedUserVM.getId(), managedUserVM.getLogin(), managedUserVM.getFirstName(), managedUserVM.getLastName(), managedUserVM.getEmail(), managedUserVM.isActivated(), managedUserVM.getLangKey(), managedUserVM.getAuthorities()); return ResponseEntity.ok() .headers(HeaderUtil.createAlert("A user is updated with identifier " + managedUserVM.getLogin(), managedUserVM.getLogin())) .body(new ManagedUserVM(userService.getUserWithAuthorities(managedUserVM.getId()))); }
/** * Add booking with the specified information. * * @param bookingVO * @return A non-null booking. */ @RequestMapping(method = RequestMethod.POST) public ResponseEntity<Booking> add(@RequestBody BookingVO bookingVO) { logger.info(String.format("booking-service add() invoked: %s for %s", bookingService.getClass().getName(), bookingVO.getName())); System.out.println(bookingVO); Booking booking = new Booking(null, null, null, null, null, null, null); BeanUtils.copyProperties(bookingVO, booking); try { bookingService.add(booking); } catch (Exception ex) { logger.log(Level.WARNING, "Exception raised add Booking REST Call {0}", ex); return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); } return new ResponseEntity<>(HttpStatus.CREATED); }
/** * Adds a new service type to the database * * @param serviceTypeDTO the user dto to add * @param errors the errors list * * @return the service that was added */ @RequestMapping(method = RequestMethod.POST, value = "/types", produces = "application/json") public ResponseEntity addServiceType(@RequestBody ServiceTypeDTO serviceTypeDTO, Errors errors) { logger.info("Adding new service type: " + serviceTypeDTO); ServiceTypeValidator serviceTypeValidator = new ServiceTypeValidator(); serviceTypeValidator.validate(serviceTypeDTO, errors); ValidationError validationError = ValidationErrorBuilder.fromBindErrors(errors); if(errors.hasErrors()) { logger.error("Service type could not be created: " + validationError.getErrors()); throw new IllegalRequestFormatException("Could not add service type.", "/service/type/", validationError); } ServiceType serviceType = new ServiceType(serviceTypeDTO); ServiceType savedServiceType = this.serviceTypeService.addServiceType(serviceType); logger.info("Successfully created new service type: " + savedServiceType); return ResponseEntity.ok(savedServiceType); }
@Test public void testModifySkillsSkillUnknown() { ResponseEntity<String> res = userController.updateSkills("aaaaaa", "UnknownSkill", "0", "0", false, "YWFhLmFhYUBleGFtcGxlLmNvbQ==|foo|bar"); assertEquals(HttpStatus.BAD_REQUEST, res.getStatusCode()); assertEquals(2, personRepo.findByIdIgnoreCase("aaaaaa").getSkillsExcludeHidden().get(0).getSkillLevel()); assertEquals(3, personRepo.findByIdIgnoreCase("aaaaaa").getSkillsExcludeHidden().get(0).getWillLevel()); }
@Test @Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/integration-test/test-release-public-default-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void testQueryPublicConfigWithDataCenterNotFoundAndOverride() throws Exception { String someDCNotFound = "someDCNotFound"; ResponseEntity<ApolloConfig> response = restTemplate .getForEntity("{baseurl}/configs/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}", ApolloConfig.class, getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, someDCNotFound); ApolloConfig result = response.getBody(); assertEquals( "TEST-RELEASE-KEY5" + ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR + "TEST-RELEASE-KEY3", result.getReleaseKey()); assertEquals(someAppId, result.getAppId()); assertEquals(someDefaultCluster, result.getCluster()); assertEquals(somePublicNamespace, result.getNamespaceName()); assertEquals("override-v1", result.getConfigurations().get("k1")); assertEquals("default-v2", result.getConfigurations().get("k2")); }
@ApiOperation(value = "getParticipantFromCGOR", nickname = "getParticipantFromCGOR") @RequestMapping(value = "/CISConnector/getParticipantFromCGOR/{cgorName}", method = RequestMethod.GET) @ApiImplicitParams({ @ApiImplicitParam(name = "cgorName", value = "the CGOR name", required = true, dataType = "String", paramType = "path"), @ApiImplicitParam(name = "organisation", value = "the Organisation name", required = true, dataType = "String", paramType = "query") }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = Participant.class), @ApiResponse(code = 400, message = "Bad Request", response = Participant.class), @ApiResponse(code = 500, message = "Failure", response = Participant.class)}) public ResponseEntity<Participant> getParticipantFromCGOR(@PathVariable String cgorName, @QueryParam("organisation") String organisation) { log.info("--> getParticipantFromCGOR: " + cgorName); Participant participant; try { participant = connector.getParticipantFromCGOR(cgorName, organisation); } catch (CISCommunicationException e) { log.error("Error executing the request: Communication Error" , e); participant = null; } HttpHeaders responseHeaders = new HttpHeaders(); log.info("getParticipantFromCGOR -->"); return new ResponseEntity<Participant>(participant, responseHeaders, HttpStatus.OK); }
/** * DELETE /tasks/:id : delete the "id" task. * * @param id the id of the task to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/tasks/{id}") @Timed public ResponseEntity<Void> deleteTask(@PathVariable Long id) { log.debug("REST request to delete Task : {}", id); Task taskSaved = taskRepository.findOne(id); if (taskSaved != null && !SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN) && !SecurityUtils.getCurrentUserLogin().equals(taskSaved.getUser())) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } taskRepository.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); }
/** * Gets all weather information in the database * @return the list of all weather information */ @RequestMapping(method = RequestMethod.GET, value = "/information", produces = "application/json") public ResponseEntity getAllWeatherInformation() { List<WeatherInformation> weatherInformationList = this.weatherInformationService.getAllWeatherInformation(); return ResponseEntity.ok(weatherInformationList); }
@Around( "execution(org.springframework.http.ResponseEntity com.aidijing.*.controller.*Controller.*(..)) )" ) public Object returnValueHandle ( ProceedingJoinPoint joinPoint ) throws Throwable { Object returnValue = joinPoint.proceed(); ResponseEntity responseEntity = ( ResponseEntity ) returnValue; // 用户权限或者用户自定义处理 final RolePermissionResource currentRequestRolePermissionResource = ContextUtils.getCurrentRequestRolePermissionResource(); if ( Objects.isNull( currentRequestRolePermissionResource ) ) { return returnValue; } if ( ResponseEntityPro.WILDCARD_ALL.equals( currentRequestRolePermissionResource.getResourceApiUriShowFields() ) ) { ContextUtils.removeCurrentRequestRolePermissionResource(); return returnValue; } final String resourceApiUriShowFields = currentRequestRolePermissionResource.getResourceApiUriShowFields(); final String filterAfterJsonBody = toFilterJson( responseEntity.getBody() , resourceApiUriShowFields ); final Object filterAfterBody = jsonToType( filterAfterJsonBody , responseEntity.getBody().getClass() ); ContextUtils.removeCurrentRequestRolePermissionResource(); return new ResponseEntity<>( filterAfterBody , responseEntity.getHeaders() , responseEntity.getStatusCode() ); }
/** * Clients should call this in order to refresh a JWT. * * @param request the request from the client. * @return the JWT with an extended expiry time if the client was authenticated, a 400 Bad Request otherwise. */ @RequestMapping(value = "/refresh", method = RequestMethod.GET) public ResponseEntity<?> refreshAuthenticationToken(HttpServletRequest request) { final String authorizationHeader = request.getHeader("Authorization"); final Claims claims = jwtUtils.validateTokenAndGetClaims(authorizationHeader); final String username = jwtUtils.getUsernameFromTokenClaims(claims); final JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username); if (jwtUtils.canTokenBeRefreshed(claims, new Date(user.getLastPasswordResetDate()))) { final String refreshedToken = jwtUtils.refreshToken(authorizationHeader); return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken)); } else { return ResponseEntity.badRequest().body(null); } }
@ApiOperation(value = "Gets all foods, optionally return stats per food", notes = "Return a list of all foods", response = FoodWithStats.class, responseContainer = "List", authorizations = { @Authorization(value = "Bearer") }, tags={ "chef", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "A list of foods", response = FoodWithStats.class), @ApiResponse(code = 500, message = "An unexpected error occured.", response = FoodWithStats.class) }) @RequestMapping(value = "/foods", produces = { "application/json" }, method = RequestMethod.GET) @CrossOrigin ResponseEntity<FoodsPage> foodsGet( @ApiParam(value = "") @RequestParam(value = "stats", required = false) Boolean stats, @ApiParam(value = "Request pagination page") @RequestParam(value = "page", required = false) String page, @ApiParam(value = "Request pagination size / num of foods") @RequestParam(value = "size", required = false) String size, @ApiParam(value = "Request foodType filter") @RequestParam(value = "foodType", required = false) String foodType, @ApiParam(value = "Request archived filter") @RequestParam(value = "archived", required = false) String archived, @ApiParam(value = "Request orderBy filter") @RequestParam(value = "orderBy", required = false) String orderBy, @ApiParam(value = "Request foods version") @RequestParam(value = "foods_version", required = false) @Valid @Digits( integer=9, fraction=0 )Integer foods_version, @ApiParam(value = "Request orderBy filter") @RequestParam(value = "orderDirection", required = false) String orderDirection) throws ApiException, Exception;
@Override public void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback) throws IOException { Assert.notNull(appName, "AppName must not be null"); Assert.notNull(archive, "Archive must not be null"); UUID appId = getAppId(appName); if (callback == null) { callback = UploadStatusCallback.NONE; } CloudResources knownRemoteResources = getKnownRemoteResources(archive); callback.onCheckResources(); callback.onMatchedFileNames(knownRemoteResources.getFilenames()); UploadApplicationPayload payload = new UploadApplicationPayload(archive, knownRemoteResources); callback.onProcessMatchedResources(payload.getTotalUncompressedSize()); HttpEntity<?> entity = generatePartialResourceRequest(payload, knownRemoteResources); ResponseEntity<Map<String, Object>> responseEntity = getRestTemplate().exchange(getUrl("/v2/apps/{guid}/bits?async=true"), HttpMethod.PUT, entity, new ParameterizedTypeReference<Map<String, Object>>() { }, appId); processAsyncJob(responseEntity.getBody(), callback); }
/** * Gets the health-check status. * * @param correlationId request correlation id * @return health-check model entity */ @ApiOperation(value = "Gets health-check status", response = HealthCheck.class) @ApiResponses(value = { @ApiResponse(code = 200, response = HealthCheck.class, message = "Operation is successful"), @ApiResponse(code = 401, response = MessageError.class, message = "Unauthorized"), @ApiResponse(code = 403, response = MessageError.class, message = "Forbidden"), @ApiResponse(code = 404, response = MessageError.class, message = "Not found"), @ApiResponse(code = 503, response = MessageError.class, message = "Service unavailable")}) @RequestMapping(value = "/health-check", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<HealthCheck> getHealthCheck( @RequestHeader(value = CORRELATION_ID, defaultValue = DEFAULT_CORRELATION_ID) String correlationId) { logger.debug("getHealthCheck"); HealthCheck healthCheck = healthCheckService.getHealthCheck(correlationId); HttpStatus status = healthCheck.hasNonOperational() ? HttpStatus.GATEWAY_TIMEOUT : HttpStatus.OK; return new ResponseEntity<>(healthCheck, new HttpHeaders(), status); }
@RequestMapping(value = "/{locId}", method = RequestMethod.GET) @ApiOperation(value = "Fetch employees of specific location.", response = ResponseDTO.class) public ResponseEntity<Map<String, Object>> get(@PathVariable @Valid String locId) { ResponseEntity<Map<String, Object>> result = ResponseEntity.notFound().build(); try { if (StringUtils.isNotBlank(locId)) { List<Employee> employees = employeeService.getByLocation(locId); if (CollectionUtils.isNotEmpty(employees)) { Collection<EmployeeDTO> employeesDTO = employeeConverter.convertToDTO(employees); ResponseDTO responseDTO = new ResponseDTO(ZvisitorResource.employees.name(), employeesDTO); result = ResponseEntity.ok().body(responseDTO.getResponse()); } } } catch(Exception e) { logger.error("Exception while fetching employees.", e); result = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } return result; }
@Test public void should_list_all_hospitals() { //given University university = new University(); university.setName("ITU"); universityRepository.save(university); //when ResponseEntity<List> entity = testRestTemplate .withBasicAuth("1", "1") .getForEntity("/v1/universities", List.class); //then assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody().size()).isEqualTo(1); }
/** * Process PUT /tags/{id}?id= request * Update a tag * * @param id tag ID * @return response entity */ @Override public ResponseEntity<Void> updateTag(@ApiParam(value = "tag ID", required = true) @PathVariable("id") String id, @ApiParam(value = "Tag", required = true) @RequestBody Tag tag) { // Get tag in database TagEntity entity = tagRepository.findOne(Long.valueOf(id)); // Update tag in database if (entity != null) { entity.setName(tag.getName()); entity.setTemplates(tag.getTemplates()); tagRepository.save(entity); return ResponseEntity.ok().build(); } else { return ResponseEntity.notFound().build(); } }
/** * PUT /user/logins : Updates an existing User logins. * @param user the user to update * @return the ResponseEntity with status 200 (OK) and with body the updated user, or with * status 400 (Bad Request) if the login or email is already in use, or with status 500 * (Internal Server Error) if the user couldn't be updated */ @PutMapping("/users/logins") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<UserDTO> updateUserLogins(@Valid @RequestBody UserDTO user) { user.getLogins().forEach(userLogin -> userLoginRepository.findOneByLoginIgnoreCaseAndUserIdNot(userLogin.getLogin(), user.getId()) .ifPresent(s -> { throw new BusinessException(Constants.LOGIN_IS_USED_ERROR_TEXT); }) ); Optional<UserDTO> updatedUser = userService.updateUserLogins(user.getUserKey(), user.getLogins()); updatedUser.ifPresent(userDTO -> produceEvent(userDTO, Constants.UPDATE_PROFILE_EVENT_TYPE)); return ResponseUtil.wrapOrNotFound(updatedUser, HeaderUtil.createAlert("userManagement.updated", user.getUserKey())); }
@Override public void run(String... strings) throws Exception { System.out.println("\n\n\n start RestTemplate client..."); ResponseEntity<Collection<Restaurant>> exchange = this.restTemplate.exchange( "http://restaurant-service/v1/restaurants?name=o", HttpMethod.GET, null, new ParameterizedTypeReference<Collection<Restaurant>>() { }, (Object) "restaurants"); exchange.getBody().forEach((Restaurant restaurant) -> { System.out.println("\n\n\n[ " + restaurant.getId() + " " + restaurant.getName() + "]"); }); }
/** * GET /applications : get all the applications. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of applications in body */ @GetMapping("/applications") @Timed public ResponseEntity<List<Application>> getAllApplications(Pageable pageable) { log.debug("REST request to get a page of Applications"); Page<Application> page = applicationService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/applications"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); }
@RequestMapping(value = "/scanCode", method = RequestMethod.POST) public ResponseEntity<ScanResult> scanCode(@RequestBody Map<String, Object> map) { if (!map.containsKey("apiKey") || !map.containsKey("image")) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } String base64 = (String)map.get("image"); String userApiKey = (String)map.get("apiKey"); if (API_KEY.equals(userApiKey)) { // Authorised access try { Image myImage = new Image(base64); CornerAnalyzer analyzer = new CornerAnalyzer(new PictureUtils(myImage.getImage())); analyzer.scanCorners(); Code code = new Code(myImage, new ArrayList<Point<Double>>() {{ add(new Point<>((double) analyzer.getTopLeft().getY(), (double)analyzer.getTopLeft().getX())); add(new Point<>((double) analyzer.getTopRight().getY(), (double)analyzer.getTopRight().getX())); add(new Point<>((double) analyzer.getBottomLeft().getY(), (double)analyzer.getBottomLeft().getX())); add(new Point<>((double) analyzer.getBottomRight().getY(), (double)analyzer.getBottomRight().getX())); }}); return new ResponseEntity<>( new ScanResult(storage.getData(code.getCode())), HttpStatus.OK); } catch (IOException e) { Logger.getGlobal().log(Level.SEVERE, String.valueOf(e)); } } return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); }
/** * Function to create an Organisation * * Only a system administrator cna create an Organisation * * @param organisation * @return ResponseEntity */ @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> create(@RequestBody final DtoOrganisation organisation) { try { LOGGER.debug(() -> "Creating Organisation " + organisation.getName()); IUser actor = getLoggedInUser(); return new ResponseEntity<>(convertToDtoOrganisation(actor, serviceOrganisation.createOrganisation(actor, organisation)), HttpStatus.OK); } catch (ServiceOrganisationExceptionNotAllowed ex) { return new ResponseEntity<>(ex, HttpStatus.FORBIDDEN); } }
@ApiOperation(value = "知乎问题", notes = "知乎问题列表", response = ResultDTO.class, tags = { "ZhihuQuestion", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "返回知乎问题信息列表", response = ResultDTO.class), @ApiResponse(code = 200, message = "返回错误信息", response = ResultDTO.class) }) @RequestMapping(value = "/question/list", produces = { "application/json" }, method = RequestMethod.GET) public ResponseEntity<ResultDTO> questionListGet( @NotNull @ApiParam(value = "起始页", required = true, defaultValue = "1") @RequestParam(value = "start", required = true) int start, @NotNull @ApiParam(value = "页展示数", required = true, defaultValue = "6") @RequestParam(value = "size", required = true) int size);
/** * GET /tagPools/:id -> get the "id" tagPool. */ @RequestMapping(value = "/tagPools/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<TagPool> getTagPool(@PathVariable Long id) { log.debug("REST request to get TagPool : {}", id); return Optional.ofNullable(tagPoolRepository.findOne(id)) .map(tagPool -> new ResponseEntity<>( tagPool, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); }
@Test public void getPatterns() { PatternDefinitionList patternDefinitionList = new PatternDefinitionList(); ResponseEntity<PatternDefinitionList> response = new ResponseEntity<PatternDefinitionList>(patternDefinitionList, HttpStatus.ACCEPTED); String url = restClient.baseUrl + ApiConfig.PATTERNS_BASE; when(restTemplate.getForEntity(url, PatternDefinitionList.class)).thenReturn(response); assertNotNull(restClient.getPatterns()); Mockito.verify(restTemplate).getForEntity(url, PatternDefinitionList.class); assertEquals(sessionId, restClient.getSessionId()); }
/** * Serves new token for user * @return */ @RequestMapping(path = "/token", method = RequestMethod.GET) public ResponseEntity<String> requestTokenAction() { AppUser appUser = authenticationService.getLoggedUser(); if(appUser == null) { return ResponseEntity.ok(""); } UUID token = UUID.randomUUID(); JsonObject json = new JsonObject(); json.addProperty("token", token.toString()); authTokenCache.addAuthToken(token, appUser); return ResponseEntity.ok(json.toString()); }
@RequestMapping(value = "/authenticate/{username}/{password}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity authenticateGet(@PathVariable("username") String userName, @PathVariable("password") String password) { LOGGER.debug(() -> "GET:/papi/user/authenticate"); final UserDetails userDetails = serviceDetails.loadUserByUsername(userName); if(!ENCODER.matches(password, userDetails.getPassword())){ LOGGER.info(()->"Passwords do not match"); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } // TODO: actually perform the authentication so that we get a token return new ResponseEntity<>(HttpStatus.OK); }
@PutMapping("{id}") public ResponseEntity<?> update( @PathVariable long id, @RequestBody @Valid Account user ) { return ResponseEntity.ok(userService.update(id, user)); }
/** * GET /hangManExerciseDelimitedAreas/:id -> get the "id" hangManExerciseDelimitedArea. */ @RequestMapping(value = "/hangManExerciseDelimitedAreas/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<HangManExerciseDelimitedArea> getHangManExerciseDelimitedArea(@PathVariable Long id) { log.debug("REST request to get HangManExerciseDelimitedArea : {}", id); return Optional.ofNullable(hangManExerciseDelimitedAreaRepository.findOne(id)) .map(hangManExerciseDelimitedArea -> new ResponseEntity<>( hangManExerciseDelimitedArea, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); }
@RequestMapping(value = "/useraccess", method = RequestMethod.GET) @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<?> getUserAccessibleResource() { Map<String, Object> resultMap = new HashMap<>(); resultMap.put("result", 42); resultMap.put("somethingElse", "Another User Accessible Value"); return ResponseEntity.ok(resultMap); }
@ResponseStatus(HttpStatus.FAILED_DEPENDENCY) @ExceptionHandler(ConnectException.class) public ResponseEntity<ErrorResponse> handleConnectExceptions(ResourceAccessException e) { return ResponseEntity.status(HttpStatus.FAILED_DEPENDENCY) .contentType(MediaType.APPLICATION_JSON) .body(new ErrorResponse(e.getMessage())); }
@GetMapping("/users/{followableUserId}/followers") public ResponseEntity<List<GetFollowersResponse.Follower>> getFollowers( @PathVariable("followableUserId") String followableUserId ) { GetFollowersRequest request = new GetFollowersRequest(followableUserId); return ResponseEntity.ok(getFollowersUseCase.execute(request).getFollowers()); }
public ResponseEntity deleteCase(Long caseId) { Case tempCase = caseRepository.findOne(caseId); if (tempCase == null) throw new EntityNotFoundException("entity.notFound"); tempCase.setModelStatus(ModelStatus.DELETED); caseRepository.save(tempCase); return new ResponseEntity<>(HttpStatus.NO_CONTENT); }
/** * GET /hangManExercises/:id -> get the "id" hangManExercise. */ @RequestMapping(value = "/hangManExercises/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<HangManExercise> getHangManExercise(@PathVariable Long id) { log.debug("REST request to get HangManExercise : {}", id); return Optional.ofNullable(hangManExerciseRepository.findOne(id)) .map(hangManExercise -> new ResponseEntity<>( hangManExercise, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); }