Java Code Examples for org.springframework.http.ResponseEntity

The following are top voted examples for showing how to use org.springframework.http.ResponseEntity. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: C4SG-Obsolete   File: ProjectController.java   Source Code and License 12 votes vote down vote up
@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");
    }
}
 
Example 2
Project: SmartSync   File: TodoListController.java   Source Code and License 9 votes vote down vote up
/**
 * 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);
}
 
Example 3
Project: artifactory-resource   File: HttpArtifactoryBuildRuns.java   Source Code and License 7 votes vote down vote up
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();
}
 
Example 4
Project: sporticus   File: RestControllerAdminOrganisation.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
	}
}
 
Example 5
Project: Mastering-Microservices-with-Java-9-Second-Edition   File: BookingController.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
}
 
Example 6
Project: configx   File: HookEventHandlerSupport.java   Source Code and License 7 votes vote down vote up
/**
 * 执行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);
    }

}
 
Example 7
Project: CommonInformationSpace   File: CISAdaptorConnectorRestController.java   Source Code and License 7 votes vote down vote up
@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);
}
 
Example 8
Project: SmartSync   File: WeatherController.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
}
 
Example 9
Project: Diber-backend   File: OrderController.java   Source Code and License 7 votes vote down vote up
@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);
}
 
Example 10
Project: cfsummiteu2017   File: ServiceInstanceBindingController.java   Source Code and License 7 votes vote down vote up
@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);
}
 
Example 11
Project: bxbot-ui-server   File: EngineConfigController.java   Source Code and License 7 votes vote down vote up
/**
 * Updates the Engine configuration for a bot.
 *
 * @param user         the authenticated user making the request.
 * @param engineConfig the Engine config to update.
 * @param botId        the id of the Bot to update the Engine config for.
 * @return 200 'Ok' HTTP status code with updated Engine config if update successful, some other HTTP status code otherwise.
 */
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "/{botId}" + ENGINE_RESOURCE_PATH, method = RequestMethod.PUT)
public ResponseEntity<?> updateEngine(@AuthenticationPrincipal User user, @RequestBody EngineConfig engineConfig,
                                      @PathVariable String botId) {

    LOG.info("PUT " + CONFIG_ENDPOINT_BASE_URI + botId + ENGINE_RESOURCE_PATH + " - updateEngine() "); //- caller: " + user.getUsername());
    LOG.info("Request: " + engineConfig);

    final EngineConfig updatedConfig = engineConfigService.updateEngineConfig(botId, engineConfig);
    return updatedConfig == null
            ? new ResponseEntity<>(HttpStatus.NOT_FOUND)
            : buildResponseEntity(updatedConfig, HttpStatus.OK);
}
 
Example 12
Project: keti   File: ResourcePrivilegeManagementController.java   Source Code and License 7 votes vote down vote up
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);
    }
}
 
Example 13
Project: sentry   File: UserResource.java   Source Code and License 6 votes vote down vote up
/**
 * 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())));
}
 
Example 14
Project: playground-scenario-generator   File: RestResponseEntityExceptionHandler.java   Source Code and License 6 votes vote down vote up
@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()));
}
 
Example 15
Project: SmartSync   File: ServiceController.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 16
Project: SkillWill   File: UserControllerTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 17
Project: codemotion-2017-taller-de-jhipster   File: TaskResource.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 18
Project: spring-boot-start-current   File: ResponseEntityAspect.java   Source Code and License 6 votes vote down vote up
@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() );


}
 
Example 19
Project: bxbot-ui-server   File: AuthenticationController.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 20
Project: yum   File: FoodsApi.java   Source Code and License 6 votes vote down vote up
@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;
 
Example 21
Project: cf-java-client-sap   File: CloudControllerClientImpl.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 22
Project: open-kilda   File: HealthCheckController.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 23
Project: visitormanagement   File: EmployeeResource.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 24
Project: second-opinion-api   File: UniversityControllerIT.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 25
Project: microservice-email   File: TagApiController.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 26
Project: Mastering-Microservices-with-Java-9-Second-Edition   File: EdgeApp.java   Source Code and License 5 votes vote down vote up
@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() + "]");
    });
}
 
Example 27
Project: qualitoast   File: ApplicationResource.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 28
Project: scancode   File: ScanCodeController.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 29
Project: zhihu-spider   File: QuestionApi.java   Source Code and License 5 votes vote down vote up
@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);
 
Example 30
Project: buenojo   File: TagPoolResource.java   Source Code and License 5 votes vote down vote up
/**
 * 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));
}
 
Example 31
Project: loom   File: RestClientTest.java   Source Code and License 5 votes vote down vote up
@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());
}
 
Example 32
Project: CTUConference   File: AuthController.java   Source Code and License 5 votes vote down vote up
/**
 * 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());
}
 
Example 33
Project: sporticus   File: RestControllerAuth.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 34
Project: java-microservice   File: AccountController.java   Source Code and License 5 votes vote down vote up
@PutMapping("{id}")
public ResponseEntity<?> update(
        @PathVariable long id,
        @RequestBody @Valid Account user
) {
    return ResponseEntity.ok(userService.update(id, user));
}
 
Example 35
Project: buenojo   File: HangManExerciseDelimitedAreaResource.java   Source Code and License 5 votes vote down vote up
/**
 * 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));
}
 
Example 36
Project: Your-Microservice   File: AuthorizationProtectedController.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 37
Project: aop-for-entity-behaviour   File: FollowersController.java   Source Code and License 5 votes vote down vote up
@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());
}
 
Example 38
Project: second-opinion-api   File: CaseService.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 39
Project: buenojo   File: HangManExerciseResource.java   Source Code and License 5 votes vote down vote up
/**
 * 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));
}
 
Example 40
Project: setra   File: ReceiveController.java   Source Code and License 5 votes vote down vote up
/**
 * Download attached file.
 */
@GetMapping("/file/{id:[a-f0-9]{64}}/{key:[a-f0-9]{64}}")
public ResponseEntity<StreamingResponseBody> file(@PathVariable("id") final String id,
                                                  @PathVariable("key") final String keyHex,
                                                  final HttpSession session) {

    final KeyIv keyIv =
        new KeyIv(BaseEncoding.base16().lowerCase().decode(keyHex), resolveFileIv(id, session));

    final DecryptedFile decryptedFile = messageService.resolveStoredFile(id, keyIv);

    final HttpHeaders headers = new HttpHeaders();

    // Set application/octet-stream instead of the original mime type to force download
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    if (decryptedFile.getName() != null) {
        headers.setContentDispositionFormData("attachment", decryptedFile.getName(),
            StandardCharsets.UTF_8);
    }
    headers.setContentLength(decryptedFile.getOriginalFileSize());

    final StreamingResponseBody body = out -> {
        try (final InputStream in = messageService.getStoredFileInputStream(id, keyIv)) {
            ByteStreams.copy(in, out);
            out.flush();
        }

        messageService.burnFile(id);
    };

    return new ResponseEntity<>(body, headers, HttpStatus.OK);
}
 
Example 41
Project: nectar-server   File: QueryController.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@RequestMapping(NectarServerApplication.ROOT_PATH + "/query/queryEventLog")
public ResponseEntity queryEventLog(@RequestParam(value = "token") String jwtRaw, @RequestParam(value = "entryCount") int entryCount,
                                    HttpServletRequest request) {
    ManagementSessionToken token = ManagementSessionToken.fromJSON(Util.getJWTPayload(jwtRaw));
    if(token == null)
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid TOKENTYPE.");

    if(!SessionController.getInstance().checkManagementToken(token)) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Token expired/not valid.");
    }

    StringBuilder sb = new StringBuilder();

    int lastEntryId;
    synchronized (NectarServerApplication.getEventLog().getEntries()) {
        Iterator<EventLog.Entry> entryIterator = NectarServerApplication.getEventLog().getEntries().iterator();
        for(int i = 0; i < entryCount; i++) { // Only add logs until we reach the amount specified
            if(!entryIterator.hasNext()) break; // Check if there are no more entries
            EventLog.Entry e = entryIterator.next();

            sb.append(e.getDatetime().toString())
                    .append(" [")
                    .append(e.getLevel().name())
                    .append("]: ")
                    .append(e.getMessage())
                    .append("\r\n");
        }

        lastEntryId = NectarServerApplication.getEventLog().getEntries().getLast().getEntryId();
    }

    JSONObject root = new JSONObject();
    root.put("lastEntryId", lastEntryId);
    root.put("entries", sb.toString());

    return ResponseEntity.ok(root.toJSONString());
}
 
Example 42
Project: apollo-custom   File: ConfigControllerIntegrationTest.java   Source Code and License 5 votes vote down vote up
@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"));
}
 
Example 43
Project: scrumtracker2017   File: ApiTaskController.java   Source Code and License 5 votes vote down vote up
@JsonView(JsonViews.Basique.class)
@RequestMapping(value = "/api/task/add", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<Task> sendStory(@RequestBody Task task)
{
    LOGGER.debug("ApiController - sendTask");
    task = taskService.save(task);
    LOGGER.debug("ApiController - sendTask - Task créé");
    return new ResponseEntity<Task>(task, HttpStatus.CREATED);
}
 
Example 44
Project: microservices-tcc-alfa   File: UserController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
	System.out.println("Creating User " + user.getName());
	
	userRepository.save(user);
	HttpHeaders headers = new HttpHeaders();
	headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
	return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
 
Example 45
Project: jhipster-microservices-example   File: TagResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /tags : get all the tags.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of tags in body
 */
@GetMapping("/tags")
@Timed
public ResponseEntity<List<Tag>> getAllTags(@ApiParam Pageable pageable) {
    log.debug("REST request to get a page of Tags");
    Page<Tag> page = tagRepository.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tags");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 46
Project: sentry   File: FlowResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /flows : get all the flows.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of flows in body
 * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
 */
@GetMapping("/flows")
@Timed
@Secured(AuthoritiesConstants.SUPPORT)
public ResponseEntity<List<FlowDTO>> getAllFlows(@ApiParam Pageable pageable)
    throws URISyntaxException {
    log.debug("REST request to get a page of Flows");
    Page<FlowDTO> page = flowService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/flows");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 47
Project: homer   File: ContributorRestController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value="/contributors/{id}", method=RequestMethod.DELETE, produces={ MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<Contributor> deleteContributor(@PathVariable(value="id") Integer contributorId) {
    Contributor contributor = contributorRepository.findOne(contributorId);
    if(contributor == null) return ResponseEntity.notFound().build();
    contributorRepository.delete(contributor);
    return ResponseEntity.ok().build();
}
 
Example 48
Project: acmeair   File: BookingsRESTTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getsBookingWithUnderlyingService() {
    when(bookingService.getBooking(userId, bookingId)).thenReturn(booking);

    ResponseEntity<BookingInfo> responseEntity = restTemplate.getForEntity(
            "/rest/api/bookings/bybookingnumber/{userid}/{number}",
            BookingInfo.class,
            userId,
            bookingId);

    assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
    assertThat(responseEntity.getBody(), is(new BookingInfo(booking)));
}
 
Example 49
Project: ingest-core   File: ProtocolController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(path = "/protocols/{id}" + Links.PROCESSING_URL, method = RequestMethod.PUT)
HttpEntity<?> processingProtocol(@PathVariable("id") Protocol protocol) {
    Event event = this.getStateEngine().advanceStateOfMetadataDocument(
            getProtocolService().getProtocolRepository(),
            protocol,
            ValidationState.PROCESSING);

    return ResponseEntity.accepted().body(event);
}
 
Example 50
Project: CommonInformationSpace   File: CISCoreConnectorRestController.java   Source Code and License 5 votes vote down vote up
@ApiOperation(value = "getParticipantFromCGOR", nickname = "getParticipantFromCGOR")
@RequestMapping(value = "/CISCore/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 = cisCore.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);
}
 
Example 51
Project: user-task   File: TaskResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDelete() throws Exception {
    final Task task = taskService.getRepository().findAll().get(0);
    ResponseEntity<String> response = restTemplate
            .exchange(BASE_PATH + "/" + task.getId(),
                    HttpMethod.DELETE, null, String.class);
    assertThat(response.getStatusCode())
            .isEqualTo(HttpStatus.NO_CONTENT);
    assertThat(taskService.read(task.getId()).isPresent()).isFalse();
}
 
Example 52
Project: pact-spring-mvc   File: DefaultPactResolver.java   Source Code and License 5 votes vote down vote up
protected ResponseEntity<String> downloadPact(PactDefinition pactDefinition, String version) {
    PactBrokerUrlSource pactBrokerUrlSource = new PactBrokerUrlSource();

    for (String eachUrl : pactBrokerUrlSource.getPactUrlsToDownloadPacts()) {
        try {
            LOG.info(String.format("Downloading pact [%s] from broker at: %s", version, eachUrl));
            return createRestTemplate().getForEntity(pactUrl(pactDefinition, version, eachUrl), String.class);
        } catch (RestClientException e) {
            LOG.warn(String.format("Couldn't download pact [%s] from url: %s", version, eachUrl), e);
        }
    }

    return null;
}
 
Example 53
Project: Spring-Boot-MongoDB-JWT   File: AuthenticationController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> authenticate(@RequestBody final LoginDTO dto) {
    final String token = tokenService.getToken(dto.getUsername(), dto.getPassword());
    if (token != null) {
        final TokenDTO response = new TokenDTO();
        response.setToken(token);
        return new ResponseEntity<>(response, HttpStatus.OK);
    } else {
        return new ResponseEntity<>("Authentication failed", HttpStatus.BAD_REQUEST);
    }
}
 
Example 54
Project: acmeair   File: FlightsRESTTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getsFlightsWithUnderlyingService() {
    when(flightService.getFlightByAirportsAndDate(
            departFlight.getFlightSegment().getOriginPort(),
            departFlight.getFlightSegment().getDestPort(),
            departFlight.getScheduledDepartureTime())).thenReturn(singletonList(departFlight));

    when(flightService.getFlightByAirportsAndDate(
            departFlight.getFlightSegment().getDestPort(),
            departFlight.getFlightSegment().getOriginPort(),
            returnFlight.getScheduledDepartureTime())).thenReturn(singletonList(returnFlight));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add("fromAirport", departFlight.getFlightSegment().getOriginPort());
    form.add("toAirport", departFlight.getFlightSegment().getDestPort());
    form.add("fromDate", isoDateTime(departFlight.getScheduledDepartureTime()));
    form.add("returnDate", isoDateTime(returnFlight.getScheduledDepartureTime()));
    form.add("oneWay", String.valueOf(false));

    ResponseEntity<TripFlightOptions> responseEntity = restTemplate.exchange(
            "/rest/api/flights/queryflights",
            HttpMethod.POST,
            new HttpEntity<>(form, headers),
            TripFlightOptions.class
    );

    assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));

    TripFlightOptions flightOptions = responseEntity.getBody();
    assertThat(flightOptions.getTripLegs(), is(2));

    List<TripLegInfo> tripFlights = flightOptions.getTripFlights();
    assertThat(tripFlights.get(0).getFlightsOptions(), contains(toFlightInfo(departFlight)));
    assertThat(tripFlights.get(1).getFlightsOptions(), contains(toFlightInfo(returnFlight)));
}
 
Example 55
Project: yum   File: UsersApiController.java   Source Code and License 5 votes vote down vote up
@Override
@PreAuthorize("hasAuthority('admin')")
public ResponseEntity<Object> usersIdDelete(@ApiParam(value = "", required = true ) @PathVariable("id") Long id,
        @ApiParam(value = "") @RequestParam(value = "force", required = false) Boolean force) throws ApiException, Exception {
    //Call method to delete one user, from class UsersService.
    userService.usersIdDelete(id, force);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
Example 56
Project: multi-tenant-rest-api   File: ResourcesController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value="/company/{companyid}/user", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserDTO> createCompanyUser(
		Principal principal,
		@PathVariable String companyid,
		@RequestBody UserDTO userDTO) {
	
	// Check for SUPERADMIN and COMPANYADMIN role
	RoleChecker.hasValidRole(principal, companyid);
	
	userDTO = userService.create(userDTO);
	
	return new ResponseEntity<UserDTO>(userDTO, HttpStatus.CREATED);
}
 
Example 57
Project: sentry   File: GameServerResource.java   Source Code and License 5 votes vote down vote up
/**
 * DELETE  /game-servers/:id : delete the "id" gameServer.
 *
 * @param id the id of the gameServerDTO to delete
 * @return the ResponseEntity with status 200 (OK)
 */
@DeleteMapping("/game-servers/{id}")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<Void> deleteGameServer(@PathVariable String id) {
    log.debug("REST request to delete GameServer : {}", id);
    gameServerService.delete(id);
    return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("gameServer", id)).build();
}
 
Example 58
Project: ecommerce-checkout-api-server   File: CheckoutApi.java   Source Code and License 5 votes vote down vote up
@ApiOperation(value = "Create a possibly empty shopping cart", notes = "", response = Checkout.class, tags={ "cart", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "The shopping cart", response = Checkout.class),
    @ApiResponse(code = 400, message = "Invalid input", response = Checkout.class) })
@RequestMapping(value = "/checkout",
    produces = { "application/json" }, 
    consumes = { "application/json" },
    method = RequestMethod.POST)
ResponseEntity<Checkout> createCart(@ApiParam(value = "Includes billing and products info" ,required=true ) @RequestBody Cart cart);
 
Example 59
Project: yum   File: UsersApi.java   Source Code and License 5 votes vote down vote up
@ApiOperation(value = "", notes = "creates a new user", response = Void.class, authorizations = {
    @Authorization(value = "Bearer")
}, tags={ "admin", })
@ApiResponses(value = { 
    @ApiResponse(code = 201, message = "User Created Successfully", response = Void.class),
    @ApiResponse(code = 400, message = "An unexpected error occured.", response = Void.class),
    @ApiResponse(code = 412, message = "user already exists", response = Void.class),
    @ApiResponse(code = 500, message = "An unexpected error occured.", response = Void.class) })
@RequestMapping(value = "/users",
    produces = { "application/json" }, 
    method = RequestMethod.POST)
@CrossOrigin 
ResponseEntity<Object> usersPost(@ApiParam(value = "The user to save"  )@Valid @RequestBody UserReg user, Errors errors) throws ApiException, Exception;
 
Example 60
Project: Code4Health-Platform   File: AccountResource.java   Source Code and License 5 votes vote down vote up
/**
 * POST   /account/reset_password/init : Send an e-mail to reset the password of the user
 *
 * @param mail the mail of the user
 * @return the ResponseEntity with status 200 (OK) if the e-mail was sent, or status 400 (Bad Request) if the e-mail address is not registered
 */
@PostMapping(path = "/account/reset_password/init",
    produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity requestPasswordReset(@RequestBody String mail) {
    return userService.requestPasswordReset(mail)
        .map(user -> {
            mailService.sendPasswordResetMail(user);
            return new ResponseEntity<>("e-mail was sent", HttpStatus.OK);
        }).orElse(new ResponseEntity<>("e-mail address not registered", HttpStatus.BAD_REQUEST));
}