Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.vilkivps.service;
- import com.fasterxml.jackson.core.type.TypeReference;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.vilkivps.exception.CommonException;
- import com.vilkivps.exception.NotEnoughMoneyException;
- import com.vilkivps.exception.VMNotFoundException;
- import com.vilkivps.model.ConfigurationPrice;
- import com.vilkivps.model.db.ClientVM;
- import com.vilkivps.model.db.Promo;
- import com.vilkivps.model.db.User;
- import com.vilkivps.model.db.UserBalanceHistory;
- import com.vilkivps.model.enums.ClientVMStatus;
- import com.vilkivps.repository.BalanceRepository;
- import com.vilkivps.repository.VirtualMachineRepository;
- import com.vilkivps.service.db.UserService;
- import com.vilkivps.utils.DateUtils;
- import com.vilkivps.utils.NumberUtils;
- import freemarker.template.TemplateException;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.HttpClientBuilder;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.log4j.Logger;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import javax.mail.MessagingException;
- import java.io.IOException;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- import java.util.*;
- import java.util.concurrent.TimeUnit;
- import java.util.stream.Collectors;
- @Service
- public class ClientService {
- private static final Integer REBOOT_LIMIT = 5;
- private static final Logger LOGGER = Logger.getLogger(ClientService.class);
- private static final String BASE_URL = "http://92.53.91.144";
- private static final String API_KEY = "blabla";
- private static final String EMAIL_NOTIFICATION = "mail@vilki-vps.ru";
- private static final Integer REBOOT_PRICE = 30;
- @Autowired
- private VirtualMachineRepository vmRepository;
- @Autowired
- private BalanceRepository balanceRepository;
- @Autowired
- private UserService userService;
- @Autowired
- private MailService mailService;
- @Autowired
- private PromoService promoService;
- /**
- * Создает виртуалку
- *
- * @param userId
- * @param endDate
- * @return
- * @throws IOException
- */
- protected ClientVM createVirtualMachine(String userId, Date endDate, Integer powerType, String geo, int postponeAllowed) throws IOException {
- LOGGER.info("Создание виртуалки для пользователя ID=" + userId);
- ClientVM vm = new ClientVM(userId, endDate);
- vm.setPostponeAllowed(postponeAllowed);
- vm.setLastDateReset(new Date());
- vm.setCreatingDateStart(new Date());
- vmRepository.insert(vm);
- User user = userService.findById(userId);
- String url = BASE_URL + "/api/vms/new/";
- HttpClient client = HttpClientBuilder.create().build();
- HttpPost post = new HttpPost(url);
- post.addHeader("api-key", API_KEY);
- List<NameValuePair> urlParameters = new ArrayList<>();
- urlParameters.add(new BasicNameValuePair("id", vm.getId()));
- urlParameters.add(new BasicNameValuePair("size", String.valueOf(powerType)));
- urlParameters.add(new BasicNameValuePair("country", geo));
- if (user.getFastCreating() != null) {
- urlParameters.add(new BasicNameValuePair("fastCreating", String.valueOf(user.getFastCreating())));
- }
- post.setEntity(new UrlEncodedFormEntity(urlParameters));
- HttpResponse response = client.execute(post);
- int statusCode = response.getStatusLine().getStatusCode();
- if (statusCode != 202) {
- vmRepository.delete(vm);
- throw new IOException("Что-то пошло не так... Статус ответа: " + statusCode);
- }
- return vm;
- }
- /**
- * Восстанавливает виртуалку
- *
- * @return
- * @throws IOException
- */
- private ClientVM resumeVirtualMachine(ClientVM clientVM) throws IOException {
- LOGGER.info("Восстановление виртуалки для пользователя ID=" + clientVM.getUserId());
- User user = userService.findById(clientVM.getUserId());
- String url = BASE_URL + "/api/vms/new/";
- HttpClient client = HttpClientBuilder.create().build();
- HttpPost post = new HttpPost(url);
- post.addHeader("api-key", API_KEY);
- List<NameValuePair> urlParameters = new ArrayList<>();
- urlParameters.add(new BasicNameValuePair("id", clientVM.getId()));
- urlParameters.add(new BasicNameValuePair("size", String.valueOf(clientVM.getPureSize())));
- urlParameters.add(new BasicNameValuePair("country", clientVM.getCountry()));
- if (user.getFastCreating() != null) {
- urlParameters.add(new BasicNameValuePair("fastCreating", String.valueOf(user.getFastCreating())));
- }
- post.setEntity(new UrlEncodedFormEntity(urlParameters));
- HttpResponse response = client.execute(post);
- int statusCode = response.getStatusLine().getStatusCode();
- if (statusCode != 202) {
- // vmRepository.delete(clientVM);
- throw new IOException("Что-то пошло не так... Статус ответа: " + statusCode);
- }
- return clientVM;
- }
- /**
- * Удаляет виртуалку на сервере, статус удаляемой виртуалки - DELETED
- *
- * @param vmId
- * @throws IOException
- */
- public void closeVirtualMachine(String vmId) throws IOException {
- LOGGER.info("Закрытие виртуалки " + vmId);
- String url = BASE_URL + "/api/vms/delete/";
- HttpClient client = HttpClientBuilder.create().build();
- HttpPost post = new HttpPost(url);
- post.addHeader("api-key", API_KEY);
- List<NameValuePair> urlParameters = new ArrayList<>();
- urlParameters.add(new BasicNameValuePair("id", vmId));
- post.setEntity(new UrlEncodedFormEntity(urlParameters));
- HttpResponse response = client.execute(post);
- int statusCode = response.getStatusLine().getStatusCode();
- if (statusCode != 202)
- throw new IOException("Что-то пошло не так... Статус ответа: " + statusCode);
- ClientVM vm = vmRepository.findOne(vmId);
- vm.setStatus(ClientVMStatus.DELETED);
- vm.setPassword("");
- vm.setLogin("");
- vm.setIp("");
- vmRepository.save(vm);
- }
- public void deleteForPostponeVirtualMachine(String vmId) throws IOException {
- LOGGER.info("Закрытие виртуалки " + vmId);
- String url = BASE_URL + "/api/vms/delete/";
- HttpClient client = HttpClientBuilder.create().build();
- HttpPost post = new HttpPost(url);
- post.addHeader("api-key", API_KEY);
- List<NameValuePair> urlParameters = new ArrayList<>();
- urlParameters.add(new BasicNameValuePair("id", vmId));
- post.setEntity(new UrlEncodedFormEntity(urlParameters));
- HttpResponse response = client.execute(post);
- int statusCode = response.getStatusLine().getStatusCode();
- if (statusCode != 202)
- throw new IOException("Что-то пошло не так... Статус ответа: " + statusCode);
- }
- /**
- * Обновляет статус виртуалки. Закрывает виртуалку, срок действия которой истек.
- * Обновляет счетчик виртуалок
- *
- * @param vm
- */
- public void updateVM(ClientVM vm) throws IOException, VMNotFoundException {
- Date now = new Date();
- if (vm.getStatus() == ClientVMStatus.CREATING || vm.getStatus() == ClientVMStatus.RECREATING) {
- try {
- ClientVMStatus oldStatus = vm.getStatus();
- Map<String, String> infoMap = requestVMInfo(vm.getId());
- vm.setIp(infoMap.get("ip"));
- vm.setLogin(infoMap.get("username"));
- vm.setPassword(infoMap.get("password"));
- vm.setStatus(ClientVMStatus.valueOf(infoMap.get("status")));
- vm.setCountry(infoMap.get("country"));
- vm.setSize(infoMap.get("size"));
- vmRepository.save(vm);
- //По готовности отправляем на почту сообщение
- if (vm.getStatus().equals(ClientVMStatus.READY)) {
- User user = userService.findById(vm.getUserId());
- if (oldStatus.equals(ClientVMStatus.RECREATING)) {
- try {
- mailService.onVmReadyAfterRecreating(user);
- } catch (MessagingException | TemplateException e) {
- e.printStackTrace();
- }
- }
- if (oldStatus.equals(ClientVMStatus.CREATING)) {
- try {
- mailService.onVmReady(user);
- } catch (MessagingException | TemplateException e) {
- e.printStackTrace();
- }
- }
- vm.setCreatingDateStart(null);
- }
- if (vm.getStatus().equals(ClientVMStatus.CREATING) || vm.getStatus().equals(ClientVMStatus.RECREATING)) {
- if (vm.getCreatingDateStart() != null) {
- long minutes = DateUtils.minutesDistance(vm.getCreatingDateStart(), now);
- if (minutes > 61 && !vm.isLongCreationWarnNotify()) {
- try {
- mailService.onVmLongCreation(vm, EMAIL_NOTIFICATION);
- vm.setLongCreationWarnNotify(true);
- vmRepository.save(vm);
- } catch (Exception e) {
- }
- }
- }
- }
- } catch (VMNotFoundException e) {
- // closeVirtualMachine(vm.getId());
- // vm.setStatus(ClientVMStatus.DELETED);
- // vmRepository.save(vm);
- }
- } else if (vm.getStatus() == ClientVMStatus.READY) {
- try {
- Map<String, String> infoMap = requestVMInfo(vm.getId());
- vm.setIp(infoMap.get("ip"));
- vm.setLogin(infoMap.get("username"));
- vm.setPassword(infoMap.get("password"));
- vm.setStatus(ClientVMStatus.valueOf(infoMap.get("status")));
- vm.setCountry(infoMap.get("country"));
- vm.setSize(infoMap.get("size"));
- vmRepository.save(vm);
- } catch (VMNotFoundException e) {
- }
- if (vm.getLastDateReset() == null) {
- vm.setLastDateReset(now);
- vmRepository.save(vm);
- }
- if (vm.getEndDate().before(now)) {
- closeVirtualMachine(vm.getId());
- vm.setStatus(ClientVMStatus.DELETED);
- vmRepository.save(vm);
- } else {
- long hours = DateUtils.hoursDistance(vm.getLastDateReset(), now);
- if (hours >= 24) {
- vm.setLastDateReset(now);
- vm.getRebootDates().clear();
- vmRepository.save(vm);
- }
- }
- long hours = DateUtils.hoursDistance(now, vm.getEndDate());
- if (hours <= 4 && !vm.isOneHourLateNotify()) {
- User user = userService.findById(vm.getUserId());
- try {
- mailService.onVmOneHourLast(vm, user);
- vm.setOneHourLateNotify(true);
- vmRepository.save(vm);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- if (vm.getStatus() == ClientVMStatus.POSTPONED) {
- if (vm.getPostponeEndDate().before(now)) {
- resumeVirtualMachine(vm);
- vm.setStatus(ClientVMStatus.CREATING);
- vm.setPostponeStartDate(null);
- vm.setPostponeInitEndDate(null);
- vm.setPostponeEndDate(null);
- vmRepository.save(vm);
- User user = userService.findById(vm.getUserId());
- try {
- mailService.onVmReady(user);
- } catch (MessagingException | TemplateException e) {
- e.printStackTrace();
- }
- }
- }
- }
- /**
- * Запрашивает данные о виртуалке. IP, login, password, ID, status - ключи мапы.
- *
- * @param vmId
- * @return
- * @throws IOException
- */
- private Map<String, String> requestVMInfo(String vmId) throws IOException, VMNotFoundException {
- String url = BASE_URL + "/api/vms/id/" + vmId;
- HttpClient client = HttpClientBuilder.create().build();
- HttpGet get = new HttpGet(url);
- get.addHeader("api-key", API_KEY);
- HttpResponse response = client.execute(get);
- int statusCode = response.getStatusLine().getStatusCode();
- if (statusCode == 404) {
- throw new VMNotFoundException();
- }
- if (statusCode != 200) {
- throw new IOException("Что-то пошло не так... Статус ответа: " + statusCode);
- }
- ObjectMapper mapper = new ObjectMapper();
- Map<String, String> map = mapper.readValue(response.getEntity().getContent(), new TypeReference<Map<String, String>>() {
- });
- return map;
- }
- /**
- * Очищает виртуалку
- *
- * @param vmId
- * @throws IllegalStateException
- */
- public void rebootVM(String vmId, String userId) throws Exception {
- ClientVM vm = vmRepository.getById(vmId);
- BigDecimal price = new BigDecimal(REBOOT_PRICE);
- if (!vm.getRecreationAllowed()) {
- BigDecimal userBalance = getClientBalance(userId);
- if (price.compareTo(userBalance) > 0) {
- throw new NotEnoughMoneyException();
- }
- // Списание средств
- UserBalanceHistory transaction = new UserBalanceHistory(userId, new BigDecimal(REBOOT_PRICE).negate(), "Дополнительное пересоздание виртуальной машины");
- transaction.setVmId(vmId);
- balanceRepository.save(transaction);
- }
- // статистика пересозданий
- UserBalanceHistory transaction = new UserBalanceHistory(userId, new BigDecimal(0), "Переоздание виртуальной машины");
- transaction.setVmId(vmId);
- balanceRepository.save(transaction);
- recreateVirtualMachine(vm.getId());
- vm.setStatus(ClientVMStatus.RECREATING);
- vm.getRebootDates().add(new Date());
- vm.setCreatingDateStart(new Date());
- vmRepository.save(vm);
- }
- /**
- * Отправляет запрос на пересоздание виртуалки
- *
- * @param vmId
- * @throws IOException
- */
- private void recreateVirtualMachine(String vmId) throws IOException {
- LOGGER.info("Пересоздание виртуалки " + vmId);
- String url = BASE_URL + "/api/vms/recreate/";
- HttpClient client = HttpClientBuilder.create().build();
- HttpPost post = new HttpPost(url);
- post.addHeader("api-key", API_KEY);
- List<NameValuePair> urlParameters = new ArrayList<>();
- urlParameters.add(new BasicNameValuePair("id", vmId));
- post.setEntity(new UrlEncodedFormEntity(urlParameters));
- HttpResponse response = client.execute(post);
- int statusCode = response.getStatusLine().getStatusCode();
- if (statusCode != 202)
- throw new IOException("Что-то пошло не так... Статус ответа: " + statusCode);
- }
- /**
- * Продление виртуалки
- *
- * @throws RuntimeException
- */
- public void continueVirtualMachine(User user, Integer timeType, Integer timeCount, Integer country, Integer powerType, String ip) throws RuntimeException {
- // Проверка баланса
- BigDecimal vmCost = estimateVmCost(timeType, timeCount, powerType, country);
- BigDecimal postpone = estimatePostpone(timeType, country);
- BigDecimal userBalance = getClientBalance(user.getId());
- if (vmCost.compareTo(userBalance) > 0)
- throw new NotEnoughMoneyException();
- int days = 0;
- switch (timeType) {
- case 0:
- days = 1;
- break;
- case 1:
- days = 7;
- break;
- case 2:
- days = 31;
- break;
- }
- days = days * timeCount;
- ClientVM clientVM = vmRepository.getByIp(ip);
- //Продление виртуалки
- Date endDate = DateUtils.addDays(clientVM.getEndDate(), days);
- clientVM.setEndDate(endDate);
- clientVM.setPostponeAllowed(clientVM.getPostponeAllowed() + postpone.intValue());
- vmRepository.save(clientVM);
- // Списание средств
- UserBalanceHistory transaction = new UserBalanceHistory(user.getId(), vmCost.negate(),
- String.format("Продление виртуалки %s на %s дней", powerType.toString(), days));
- transaction.setVmId(clientVM.getId());
- balanceRepository.save(transaction);
- }
- public void buyVirtualMachine(User user, Integer timeType, Integer powerType, Integer country, Integer timeCount, String promo) throws RuntimeException {
- LOGGER.debug(String.format("userId=%s", user.getId()));
- BigDecimal vmCost = estimateVmCost(timeType, 1, powerType, country);
- vmCost = getDiscountForUser(user, promo, vmCost).setScale(0, RoundingMode.CEILING);
- vmCost = getPartnerDiscountForUser(user, vmCost);
- vmCost = getPartnerDiscountForUser(user, vmCost);
- String countryType = mapToCountry(country);
- // Проверка баланса
- BigDecimal userBalance = getClientBalance(user.getId());
- BigDecimal postponeAllowed = estimatePostpone(timeType, country);
- if (vmCost.compareTo(userBalance) > 0)
- throw new NotEnoughMoneyException();
- if (timeCount < 0) {
- throw new CommonException();
- }
- int days = 0;
- switch (timeType) {
- case 0:
- days = 1;
- break;
- case 1:
- days = 7;
- break;
- case 2:
- days = 31;
- break;
- }
- days = days * timeCount;
- // Создание виртуалок
- Date now = new Date();
- now = DateUtils.addHours(now, 1);
- Date endDate = DateUtils.addDays(now, days);
- ClientVM vm = null;
- powerType = mapToPower(powerType);
- try {
- vm = createVirtualMachine(user.getId(), endDate, powerType, countryType, postponeAllowed.intValue());
- } catch (IOException ex) {
- if (vm != null) {
- vmRepository.delete(vm);
- }
- LOGGER.error(ex.getMessage());
- throw new CommonException();
- }
- // Списание средств
- UserBalanceHistory transaction = new UserBalanceHistory(user.getId(), vmCost.negate(),
- String.format("Покупка виртуалки на %s дней", days));
- transaction.setVmId(vm.getId());
- balanceRepository.save(transaction);
- }
- private Integer mapToPower(Integer power) {
- switch (power) {
- case 0:
- return 1;
- case 1:
- return 2;
- case 2:
- return 3;
- }
- return 1;
- }
- private String mapToCountry(Integer country) {
- switch (country) {
- case 0:
- return "NETHERLANDS";
- case 1:
- return "SINGAPORE";
- case 2:
- return "GERMANY";
- case 3:
- return "UNITED_KINGDOM";
- case 4:
- return "BELARUS";
- }
- return "NETHERLANDS";
- }
- /**
- * Подсчитывает стоимость виртуалок, исходя из роли пользователя, периода, на который
- * оформляются виртуалки, и кол-ва виртуалок.
- *
- * @return
- */
- public BigDecimal estimateVmCost(Integer timeType, Integer timeCount, Integer powerType, Integer country) {
- ConfigurationPrice configurationPrice = mapToPrices(country);
- BigDecimal amount = new BigDecimal(249);
- switch (timeType) {
- case 0: //День
- amount = BigDecimal.valueOf(timeCount).multiply(dayAmount(powerType, configurationPrice));
- break;
- case 1: //Неделя
- amount = BigDecimal.valueOf(timeCount).multiply(weekAmount(powerType, configurationPrice));
- break;
- case 2: //Месяц
- amount = BigDecimal.valueOf(timeCount).multiply(monthAmount(powerType, configurationPrice));
- break;
- }
- return amount;
- }
- /**
- * Подсчитываем цену для пользователя с учетом скидки
- *
- * @param user
- * @param name
- * @return
- */
- public BigDecimal getDiscountForUser(User user, String name, BigDecimal total) {
- Promo promo = promoService.findByName(name);
- BigDecimal newTotal = total;
- if (promo != null && promo.getActive()) {
- boolean promoAllow = false;
- //Проверяем пользователей приватного промокода
- if (promo.getCampaignType().equals(Promo.CampaignType.PRIVATE)) {
- for (String userId : promo.getUsers()) {
- if (userId.equals(user.getId())) {
- promoAllow = true;
- break;
- }
- }
- }
- if (promo.getCampaignType().equals(Promo.CampaignType.PUBLIC)) {
- promoAllow = true;
- }
- if (promoAllow) {
- switch (promo.getWorthType()) {
- case CONSTANT:
- newTotal = newTotal.subtract(new BigDecimal(promo.getAmount()));
- break;
- case DISCOUNT:
- newTotal = newTotal.subtract(new BigDecimal(NumberUtils.calculatePercent(newTotal.intValue(), promo.getAmount())));
- break;
- }
- } else {
- return newTotal;
- }
- } else {
- return newTotal;
- }
- return newTotal;
- }
- /**
- * Подсчитываем цену для пользователя с учетом скидки от партнера
- *
- * @param user
- * @return
- */
- public BigDecimal getPartnerDiscountForUser(User user, BigDecimal total) {
- BigDecimal newTotal = total;
- if (user.getInvitedPromo() != null && user.getPromoAdminId() != null) {
- User promoAdmin = userService.findById(user.getPromoAdminId());
- if (promoAdmin.getPromoDiscount() != null) {
- Double cashBack = NumberUtils.calculatePercent(total.intValue(),
- promoAdmin.getPromoDiscount());
- return newTotal.subtract(new BigDecimal(cashBack)).setScale(0, RoundingMode.CEILING);
- } else {
- return newTotal;
- }
- } else {
- return newTotal;
- }
- }
- /**
- * Подсчитывает количество дней приостановки виртуальной машины
- */
- public BigDecimal estimatePostpone(Integer timeType, Integer country) {
- BigDecimal postpone = new BigDecimal(0);
- BigDecimal additionalCountry = BigDecimal.valueOf(0);
- if (country.equals(2) || country.equals(3)) {
- additionalCountry = BigDecimal.valueOf(1);
- }
- switch (timeType) {
- case 0:
- postpone = new BigDecimal(0).add(additionalCountry);
- break;
- case 1:
- postpone = BigDecimal.valueOf(2).add(additionalCountry);
- break;
- case 2:
- postpone = BigDecimal.valueOf(5).add(additionalCountry);
- break;
- }
- return postpone;
- }
- private ConfigurationPrice mapToPrices(Integer country) {
- ConfigurationPrice azure = new ConfigurationPrice(199, 990, 2990, 349, 1990, 6490, 499, 2990, 9990);
- // ConfigurationPrice vultr = new ConfigurationPrice(249, 1290, 3990, 390, 2490, 7990, 690, 4990, 13990);
- ConfigurationPrice vultr = new ConfigurationPrice(199, 990, 2990, 349, 1990, 6490, 499, 2990, 9990);
- switch (country) {
- case 0:
- return azure;
- case 1:
- return azure;
- case 2:
- return vultr;
- case 3:
- return vultr;
- }
- return null;
- }
- private BigDecimal dayAmount(Integer powerType, ConfigurationPrice configurationPrice) {
- switch (powerType) {
- case 0:
- return new BigDecimal(configurationPrice.getDayEasy());
- case 1:
- return new BigDecimal(configurationPrice.getDayOptimal());
- case 2:
- return new BigDecimal(configurationPrice.getDaySpeedup());
- }
- return new BigDecimal(configurationPrice.getDayOptimal());
- }
- private BigDecimal weekAmount(Integer powerType, ConfigurationPrice configurationPrice) {
- switch (powerType) {
- case 0:
- return new BigDecimal(configurationPrice.getWeekEasy());
- case 1:
- return new BigDecimal(configurationPrice.getWeekOptimal());
- case 2:
- return new BigDecimal(configurationPrice.getWeekSpeedup());
- }
- return new BigDecimal(configurationPrice.getWeekOptimal());
- }
- private BigDecimal monthAmount(Integer powerType, ConfigurationPrice configurationPrice) {
- switch (powerType) {
- case 0:
- return new BigDecimal(configurationPrice.getMonthEasy());
- case 1:
- return new BigDecimal(configurationPrice.getMonthOptimal());
- case 2:
- return new BigDecimal(configurationPrice.getMonthSpeedup());
- }
- return new BigDecimal(configurationPrice.getMonthOptimal());
- }
- private void deleteAndPostpone(String vmId, ClientVM vm, Integer addDateCount, Integer postponeNegateCount, User user) throws IOException {
- Date now = new Date();
- deleteForPostponeVirtualMachine(vmId);
- vm.setPostponeInitEndDate(vm.getEndDate());
- vm.setPostponeStartDate(now);
- Date endDate = DateUtils.addDays(vm.getEndDate(), addDateCount);
- Date postponeEndDate = DateUtils.addDays(now, addDateCount);
- vm.setPostponeEndDate(postponeEndDate);
- vm.setEndDate(endDate);
- vm.setPostponeAllowed(vm.getPostponeAllowed() - postponeNegateCount);
- vm.setStatus(ClientVMStatus.POSTPONED);
- vm.setIp("");
- vmRepository.save(vm);
- }
- public String postponeVM(String vmId, Integer count, User user) throws IOException {
- ClientVM vm = vmRepository.findOne(vmId);
- if (vm.getPostponeAllowed() >= count) {
- deleteAndPostpone(vmId, vm, count, count, user);
- UserBalanceHistory transaction = new UserBalanceHistory(user.getId(), new BigDecimal(0),
- String.format("Остановка виртуалки на %s дней", String.valueOf(count)));
- transaction.setVmId(vmId);
- balanceRepository.save(transaction);
- return String.format("Виртуальная машинано удалена. Новая создастся через %s дней.", String.valueOf(count));
- } else {
- BigDecimal total = new BigDecimal(count * 70);
- BigDecimal userBalance = getClientBalance(user.getId());
- if (total.compareTo(userBalance) == 1) {
- return "Не достаточно денег не балансе.";
- } else {
- deleteAndPostpone(vmId, vm, count, 0, user);
- UserBalanceHistory transaction = new UserBalanceHistory(user.getId(), total.negate(),
- String.format("Остановка виртуалки на %s дней", String.valueOf(count)));
- transaction.setVmId(vmId);
- balanceRepository.save(transaction);
- return String.format("Виртуальная машинано удалена. Новая создастся через %s дней.", String.valueOf(count));
- }
- }
- }
- public String endPostpone(String vmId, User user) throws IOException {
- ClientVM vm = vmRepository.findOne(vmId);
- if (vm != null) {
- Date now = new Date();
- if (vm.getPostponeInitEndDate() != null) {
- long usedInMillies = Math.abs(now.getTime() - vm.getPostponeStartDate().getTime());
- Long usedInHours = TimeUnit.HOURS.convert(usedInMillies, TimeUnit.MILLISECONDS);
- Date newEndDate = DateUtils.addHours(vm.getPostponeInitEndDate(), usedInHours.intValue());
- vm.setEndDate(newEndDate);
- } else {
- Date postponeEnd = vm.getPostponeEndDate();
- long diffInMillies = Math.abs(now.getTime() - postponeEnd.getTime());
- long diffNowAndPostpone = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
- long diffInMilliesStartAndEnd = Math.abs(vm.getStartDate().getTime() - vm.getEndDate().getTime());
- long diffStartAndVmEnd = TimeUnit.DAYS.convert(diffInMilliesStartAndEnd, TimeUnit.MILLISECONDS);
- long newEnd = diffStartAndVmEnd - diffNowAndPostpone;
- Date newEndDate = DateUtils.addDays(vm.getStartDate(), new Long(newEnd).intValue());
- vm.setEndDate(newEndDate);
- }
- resumeVirtualMachine(vm);
- vm.setStatus(ClientVMStatus.CREATING);
- vm.setPostponeEndDate(null);
- vm.setPostponeStartDate(null);
- vm.setPostponeInitEndDate(null);
- vm.setCreatingDateStart(new Date());
- vmRepository.save(vm);
- try {
- mailService.onVmReady(user);
- } catch (MessagingException | TemplateException e) {
- e.printStackTrace();
- }
- } else {
- return "Виртуальная машина не найдена.";
- }
- return "";
- }
- /**
- * Возвращает баланс клиента по его ИД
- *
- * @param clientId
- * @return
- */
- public BigDecimal getClientBalance(String clientId) {
- List<UserBalanceHistory> balanceHistories = balanceRepository.getClientBalanceHistory(clientId);
- return balanceHistories.stream()
- .map(UserBalanceHistory::getAmount)
- .reduce(BigDecimal.ZERO, BigDecimal::add);
- }
- /**
- * Возвращает балансы всех клиентов в мапе, где ключ - ИД клиента,
- * значение - баланс клиента
- *
- * @return
- */
- public Map<String, BigDecimal> listUserBalances() {
- List<UserBalanceHistory> balanceHistories = balanceRepository.findAll();
- Map<String, List<BigDecimal>> balanceByUser = balanceHistories.stream()
- .collect(Collectors.groupingBy(UserBalanceHistory::getUserId,
- Collectors.mapping(UserBalanceHistory::getAmount, Collectors.toList())));
- Map<String, BigDecimal> balances = new HashMap<>();
- for (Map.Entry<String, List<BigDecimal>> entry : balanceByUser.entrySet()) {
- balances.put(entry.getKey(), entry.getValue().stream().reduce(BigDecimal.ZERO, BigDecimal::add));
- }
- return balances;
- }
- /**
- * Возвращает балансы всех клиентов в мапе, где ключ - ИД клиента,
- * значение - баланс клиента
- *
- * @return
- */
- public Map<String, BigDecimal> listUserSummaryBalances() {
- List<UserBalanceHistory> balanceHistories = balanceRepository.findAll();
- Map<String, List<BigDecimal>> balanceByUser = balanceHistories.stream().filter(balance -> balance.getAmount().doubleValue() > 0)
- .collect(Collectors.groupingBy(UserBalanceHistory::getUserId,
- Collectors.mapping(UserBalanceHistory::getAmount, Collectors.toList())));
- Map<String, BigDecimal> balances = new HashMap<>();
- for (Map.Entry<String, List<BigDecimal>> entry : balanceByUser.entrySet()) {
- balances.put(entry.getKey(), entry.getValue().stream().reduce(BigDecimal.ZERO, BigDecimal::add));
- }
- return balances;
- }
- /**
- * Возвращает список транзакций клиента по его ИД
- *
- * @param clientId
- * @return
- */
- public List<UserBalanceHistory> getClientBalanceHistory(String clientId) {
- return balanceRepository.getClientBalanceHistory(clientId);
- }
- public void save(UserBalanceHistory balanceHistory) {
- balanceRepository.save(balanceHistory);
- }
- /**
- * Возвращает сумму транзакций со знаком плюс
- *
- * @param clientId
- * @return
- */
- public Double getClientIncomesSum(String clientId) {
- Double result = 0.0;
- for (UserBalanceHistory userBalanceHistory : balanceRepository.getClientBalanceHistory(clientId)) {
- if (userBalanceHistory.getAmount().doubleValue() > 0) {
- result += userBalanceHistory.getAmount().doubleValue();
- }
- }
- return result;
- }
- /**
- * Возвращает сумму транзакций со знаком минус
- *
- * @param clientId
- * @return
- */
- public Double getClientOutcomesSum(String clientId) {
- Double result = 0.0;
- for (UserBalanceHistory userBalanceHistory : balanceRepository.getClientBalanceHistory(clientId)) {
- if (userBalanceHistory.getAmount().doubleValue() < 0) {
- result += userBalanceHistory.getAmount().doubleValue();
- }
- }
- return result;
- }
- /**
- * Возвращает список виртуалок клиента по его ИД
- *
- * @param clientId
- * @return
- */
- public List<ClientVM> listVirtualMachinesForClient(String clientId) {
- List<ClientVM> vms = vmRepository.listByUserId(clientId);
- vms = vms.stream().filter(vm -> !vm.getStatus().equals(ClientVMStatus.DELETED))
- .sorted((o1, o2) -> o2.getStartDate().compareTo(o1.getStartDate()))
- .collect(Collectors.toList());
- return vms;
- }
- public List<ClientVM> listActiveVms() {
- return vmRepository.findActive();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement