OrganizationResourcesDistributor { @VisibleForTesting void checkResourcesAvailability( String suborganizationId, List<? extends Resource> newResourcesCap) throws NotFoundException, ConflictException, ServerException { Map<String, Resource> usedResources = resourceManager .getUsedResources(suborganizationId) .stream() .collect(Collectors.toMap(Resource::getType, Function.identity())); for (Resource resourceToCheck : newResourcesCap) { Resource usedResource = usedResources.get(resourceToCheck.getType()); if (usedResource != null) { try { resourceAggregator.deduct(resourceToCheck, usedResource); } catch (NoEnoughResourcesException e) { throw new ConflictException( "Resources are currently in use. " + getMessage(e.getMissingResources().get(0).getType())); } } } } @Inject  OrganizationResourcesDistributor(
      OrganizationDistributedResourcesDao organizationDistributedResourcesDao,
      OrganizationManager organizationManager,
      ResourcesLocks resourcesLocks,
      ResourceManager resourceManager,
      ResourceAggregator resourceAggregator); @Inject void subscribe(EventService eventService); void capResources(String suborganizationId, List<? extends Resource> resourcesCaps); List<? extends Resource> getResourcesCaps(String suborganizationId); OrganizationDistributedResources get(String suborganizationId); Page<? extends OrganizationDistributedResources> getByParent(
      String organizationId, int maxItems, long skipCount);  }
@Test public void shouldResourceAvailabilityCappingResourcesWhenResourceCapIsLessThanUsedOne() throws Exception { doCallRealMethod().when(manager).checkResourcesAvailability(anyString(), any()); ResourceImpl used = createTestResource(500); doReturn(singletonList(used)).when(resourceManager).getUsedResources(any()); ResourceImpl toCap = createTestResource(700); doReturn(createTestResource(200)).when(resourceAggregator).deduct((Resource) any(), any()); manager.checkResourcesAvailability(ORG_ID, singletonList(toCap)); verify(resourceManager).getUsedResources(ORG_ID); verify(resourceAggregator).deduct(toCap, used); }