当前位置: 首页>>代码示例>>Java>>正文


Java ResponseEntity类代码示例

本文整理汇总了Java中org.springframework.http.ResponseEntity的典型用法代码示例。如果您正苦于以下问题:Java ResponseEntity类的具体用法?Java ResponseEntity怎么用?Java ResponseEntity使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ResponseEntity类属于org.springframework.http包,在下文中一共展示了ResponseEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getApplicants

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
@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");
    }
}
 
开发者ID:Code4SocialGood,项目名称:C4SG-Obsolete,代码行数:17,代码来源:ProjectController.java

示例2: getAllWeatherInformation

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:jackcmeyer,项目名称:SmartSync,代码行数:11,代码来源:WeatherController.java

示例3: addOrder

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
@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);
}
 
开发者ID:atereshkov,项目名称:Diber-backend,代码行数:9,代码来源:OrderController.java

示例4: bindServiceInstance

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
@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);
}
 
开发者ID:evoila,项目名称:cfsummiteu2017,代码行数:20,代码来源:ServiceInstanceBindingController.java

示例5: create

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
/**
 * 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);
	}
}
 
开发者ID:howma03,项目名称:sporticus,代码行数:20,代码来源:RestControllerAdminOrganisation.java

示例6: doPost

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
/**
 * 执行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);
    }

}
 
开发者ID:zouzhirong,项目名称:configx,代码行数:28,代码来源:HookEventHandlerSupport.java

示例7: getParticipantFromCGOR

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
@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);
}
 
开发者ID:DRIVER-EU,项目名称:CommonInformationSpace,代码行数:28,代码来源:CISAdaptorConnectorRestController.java

示例8: doPutResource

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
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);
    }
}
 
开发者ID:eclipse,项目名称:keti,代码行数:17,代码来源:ResourcePrivilegeManagementController.java

示例9: getAllIndividualTodoListsForUser

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:jackcmeyer,项目名称:SmartSync,代码行数:23,代码来源:TodoListController.java

示例10: add

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
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();
}
 
开发者ID:spring-io,项目名称:artifactory-resource,代码行数:9,代码来源:HttpArtifactoryBuildRuns.java

示例11: updateUser

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
/**
 * 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())));
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:30,代码来源:UserResource.java

示例12: add

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Microservices-with-Java-9-Second-Edition,代码行数:21,代码来源:BookingController.java

示例13: addServiceType

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:jackcmeyer,项目名称:SmartSync,代码行数:31,代码来源:ServiceController.java

示例14: testModifySkillsSkillUnknown

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
@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());
}
 
开发者ID:sinnerschrader,项目名称:SkillWill,代码行数:8,代码来源:UserControllerTest.java

示例15: deleteTask

import org.springframework.http.ResponseEntity; //导入依赖的package包/类
/**
 * 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();
}
 
开发者ID:asanzdiego,项目名称:codemotion-2017-taller-de-jhipster,代码行数:19,代码来源:TaskResource.java


注:本文中的org.springframework.http.ResponseEntity类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。