private void extendSingleTrialInstanceExpiration(TrialInstance trialInstance, int days) {
   if (trialInstance == null) {
     return;
   }
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(trialInstance.getExpirationDate());
   calendar.add(Calendar.DATE, days);
   trialInstance.setExpirationDate(calendar.getTime());
 }
  private void extendTrialByGuid(TrialInstanceUpdateDto trialInstanceUpdateDto) {

    TrialInstance trialInstance = trialInstanceDao.findByGuid(trialInstanceUpdateDto.getGuid());
    if (trialInstance == null || !trialInstanceDao.exists(trialInstance.getId())) {
      throw new CSWebApplicationException(StringDefs.GENERAL_ERROR_CODE, "GUID does not exist!");
    }
    extendSingleTrialInstanceExpiration(trialInstance, daysToExtendFromDto(trialInstanceUpdateDto));

    trialInstance.setUpdatedAt(trialInstanceUpdateDto.getUpdatedAt());
    trialInstanceDao.save(trialInstance);
    trialInstanceDao.flush();
  }
 public DeploymentStackDto getDeploymentStackDto(Long id) {
   TrialInstance trialInstance = trailInstanceDao.findById(id);
   DeploymentStackDto stackDto;
   // Set appropriate status and state if trial is expired for front
   // end to display.
   if (trialInstance.getExpirationDate().compareTo(new Date()) < 1) {
     stackDto = new DeploymentStackDto(trialInstance);
     stackDto.setDeploymentState(DeploymentState.DELETED.toString());
     stackDto.setDeploymentStatus(DeploymentStatus.UNKNOWN.toString());
     return stackDto;
   } else {
     return new DeploymentStackDto(trialInstance);
   }
 }
  // will update full list and then save with DAO in bulk
  private void extendTrialInstanceExpiration(
      List<TrialInstance> trialInstances, TrialInstanceUpdateDto trialInstanceUpdateDto) {

    if (trialInstances == null) {
      return;
    }

    Integer days = daysToExtendFromDto(trialInstanceUpdateDto);

    for (TrialInstance trialInstance : trialInstances) {
      extendSingleTrialInstanceExpiration(trialInstance, days);
      trialInstance.setUpdatedAt(trialInstanceUpdateDto.getUpdatedAt());
    }

    trialInstanceDao.save(trialInstances);
  }
  @Test
  public void testGetActualUrl() {
    ProductVersion productVersion =
        productVersionDao.findByProductAndName(productDao.findByShortName("EAM"), "EAM-BC-3");
    User user = userDao.findByUsername(testUserName);
    Region region = regionDao.getReference(2L);
    final TrialDto trialDto =
        trialService.launchTrial(getRequestStub(), productVersion, user, region, Locale.US);
    String guid = trialDto.getGuid();
    String url = trialDto.getUrl();
    assertNotNull(guid);
    assertNotNull(url);
    final TrialInstance actual = trialInstanceDao.findById(trialDto.getId());
    assertEquals(guid, actual.getGuid());
    assertEquals(url, actual.getUrl());

    RedirectUrlDto redirectUrlDto = trialService.getActualUrl(guid);
    assertNotNull(redirectUrlDto);
    assertEquals(actual.getUrl(), redirectUrlDto.getRedirectUrl());
    List<UserTracking> data =
        userTrackingDao.findByTrackingTypeAndUser(TrackingType.PROXY_URL_HIT, user);
    assertNotNull(data);
    assertEquals(1, data.size());
    assertEquals(actual.getId(), data.get(0).getTargetObject());

    redirectUrlDto = trialService.getActualUrl(guid);
    assertEquals(actual.getUrl(), redirectUrlDto.getRedirectUrl());
    data = userTrackingDao.findByTrackingTypeAndUser(TrackingType.PROXY_URL_HIT, user);
    assertNotNull(data);
    assertEquals(2, data.size());
    assertEquals(actual.getId(), data.get(0).getTargetObject());
    assertEquals(actual.getId(), data.get(1).getTargetObject());
  }
 @Transactional
 public void doAction(Long id, DeployActionDto deployActionDto) {
   TrialInstance trialInstance;
   switch (deployActionDto.getType()) {
     case TERMINATE:
       trialInstance = trailInstanceDao.findById(id);
       trialInstance.setExpirationDate(new Date());
       break;
     case EXTEND:
       trialInstance = trailInstanceDao.findById(id);
       TrialInstanceUpdateDto trialUpdate = new TrialInstanceUpdateDto(trialInstance);
       trialUpdate.setDaysToExtend(14);
       trialExtensionComponent.extendTrialExpiration("BYINSTANCEID", trialUpdate);
       break;
     default:
       break;
   }
 }
  @Test
  public void testGetAdminDashboard() throws Exception {

    int oneMonthUserCount = 5;
    int oneDayUserCount = 5;
    int oneWeekUserCount = 5;

    Date now = new Date();

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(now);
    // set two weeks back

    cal.add(GregorianCalendar.DATE, -1);
    Date yesterday = cal.getTime();
    long yesterdayOffset = userDao.countByActiveAndCreatedAt(true, yesterday);
    cal.add(GregorianCalendar.DATE, -5);
    Date winOneWeek = cal.getTime();
    cal.add(GregorianCalendar.DATE, -1);
    Date oneWeek = cal.getTime();
    long oneWeekOffset = userDao.countByActiveAndCreatedAt(true, oneWeek);
    cal.add(GregorianCalendar.DATE, -22);
    Date winOneMonth = cal.getTime();

    cal.add(GregorianCalendar.DATE, -2);
    Date oneMonth = cal.getTime();
    cal.add(GregorianCalendar.YEAR, -20);
    Date effectivelyForever = cal.getTime();

    long oneMonthOffset = userDao.countByActiveAndCreatedAt(true, oneMonth);
    long foreverOffset = userDao.countByActiveAndCreatedAt(true, effectivelyForever);

    long baseMonthUsers = oneMonthUserCount + oneWeekUserCount + oneDayUserCount;
    long baseWeekUsers = oneWeekUserCount + oneDayUserCount;

    ArrayList<User> allUsers = new ArrayList<>();
    logger.info("oneMonthUserCount:" + winOneMonth.getTime());
    logger.info("oneWeekUserCount:" + winOneWeek.getTime());
    logger.info("oneDayUserCount:" + now.getTime());
    allUsers.addAll(
        createUsers(
            winOneMonth, "fakedomain1.com", "first", "last", "password", oneMonthUserCount));
    allUsers.addAll(
        createUsers(winOneWeek, "fakedomain2.com", "first", "last", "password", oneWeekUserCount));
    allUsers.addAll(
        createUsers(now, "fakedomain3.com", "first", "last", "password", oneDayUserCount));

    loginAdminUser();
    userDao.save(allUsers);
    for (User user : allUsers) {
      logger.info("oneMonthUserCount:" + winOneMonth + ",millis:" + winOneMonth.getTime());
      logger.info("oneWeekUserCount:" + winOneWeek + ",millis:" + winOneWeek.getTime());
      logger.info("oneDayUserCount:" + now + ",millis:" + now.getTime());
      logger.info(
          "user["
              + user.getUsername()
              + "] createdAt:"
              + user.getCreatedAt()
              + " , millis:"
              + user.getCreatedAt().getTime());
    }
    Region region = regionDao.findById(1L);

    /*
     * TRIALS SECTION
     */
    List<Product> productsForTrial = productDao.findByTrialsAvailable(true);
    ArrayList<Long> validTrialProductIds = new ArrayList<>();
    for (Product product : productsForTrial) {

      ProductVersion productVersion = pickOne(product.getProductVersions(), region, false);

      if (productVersion == null) {
        continue;
      }
      validTrialProductIds.add(product.getId());

      HashSet<Long> dates = new HashSet<>();

      for (User user : allUsers) {
        loginAdminUser();
        dates.add(user.getCreatedAt().getTime());
        activateTrial(user.getUsername(), product);
        DeployRequestDto deployRequestDto =
            this.getTrialRequestFor(user, productVersion, region, user.getCreatedAt());
        login(user.getUsername(), "password");

        DeploymentStackDto retDto =
            deploymentService.deployMultipleProducts(getRequestStub(), deployRequestDto);
        TrialInstance instance = trialInstanceDao.findById(retDto.getId());
        assertEquals(instance.getCreatedAt(), user.getCreatedAt());
      }
      assertEquals(3, dates.size());
    }
    // END TRIALS SECTION

    /*
     *
     * DO DEPLOYMENTS
     * SECTION
     */

    loginAdminUser();

    // need something there :)
    addAWSCredentials(allUsers);
    // NEED TO VARY.  For now, we will do this with all products for everyone
    List<Long[]> productAndVersionIdList =
        this.getDtoProdAndVersionList(productDao.findAll(), region);
    int badUsers = 0;
    for (User user : allUsers) {
      AmazonCredentials amazonCredentials =
          amazonCredentialsDao.findByUserAndName(user, "Dummy Key");
      if (amazonCredentials == null) {
        badUsers++;
        continue;
      }
      loginAdminUser();
      activateDeploys(user, productAndVersionIdList);
      login(user.getUsername(), "password");
      DeployRequestDto reqDto =
          this.getDeployRequestFor(
              user, productAndVersionIdList, region, amazonCredentials, user.getCreatedAt());
      DeploymentStackDto result =
          deploymentService.deployMultipleProducts(getRequestStub(), reqDto);
      DeploymentStack stack = deploymentStackDao.findById(result.getId());
      assertEquals(
          "User and stack created at times should be ==",
          user.getCreatedAt(),
          stack.getCreatedAt());
    }
    assertEquals(0, badUsers);

    // END DO DEPLOYMENTS SECTION

    /*
     * TESTING THE RETURN
     */
    loginAdminUser();
    DashboardDto dashboardDto = dashboardService.getAdminDashboard();
    assertEquals(
        "Compare what trial count should be",
        (long) (validTrialProductIds.size() * allUsers.size()),
        (long) dashboardDto.getActiveInfor24());
    assertEquals(
        "Compare all users", foreverOffset + allUsers.size(), (long) dashboardDto.getUsersTotal());
    assertEquals(
        "Compare all time deployment count",
        (long) allUsers.size(),
        (long) dashboardDto.getAllTimeAws());
    assertEquals(
        "Compare all time trial count",
        (long) (validTrialProductIds.size() * allUsers.size()),
        (long) dashboardDto.getAllTimeInfor24());
    for (Long[] ids : productAndVersionIdList) {

      // SPECIFIC day/week/month checks for products
      assertEquals(
          "Compare deploy counts for day/productId:" + ids[0],
          (long) oneDayUserCount,
          (long) dashboardDto.getDay().getAwsDeploymentsByProduct().get(ids[0]));
      assertEquals(
          "Compare deploy counts for week/productId:" + ids[0],
          baseWeekUsers,
          (long) dashboardDto.getWeek().getAwsDeploymentsByProduct().get(ids[0]));
      assertEquals(
          "Compare deploy counts for month/productId:" + ids[0],
          baseMonthUsers,
          (long) dashboardDto.getMonth().getAwsDeploymentsByProduct().get(ids[0]));
      assertEquals(
          "Compare all time deploy counts for productId:" + ids[0],
          (long) allUsers.size(),
          (long) dashboardDto.getActiveAwsByProduct().get(ids[0]));
    }

    List<ProductCountDto> prodCountDtos = trialInstanceDao.countByCreatedAtAfter(yesterday);
    for (ProductCountDto count : prodCountDtos) {
      logger.info("prod-id:" + count.getProductId() + ",count:" + count.getCount());
    }

    int processed = 0;
    for (Long productId : validTrialProductIds) {
      assertEquals(
          "Compare counts for productId:" + productId,
          (long) allUsers.size(),
          (long) dashboardDto.getActiveInfor24ByProduct().get(productId));
      // SPECIFIC day/week/month checks for products
      assertEquals(
          "Compare trial counts for day/productId:"
              + productId
              + ",shortName:"
              + productDao.findById(productId).getShortName()
              + ",processed already:"
              + processed,
          (long) oneDayUserCount,
          (long) dashboardDto.getDay().getInfor24DeploymentsByProduct().get(productId));
      assertEquals(
          "Compare trial counts for week/productId:" + productId,
          baseWeekUsers,
          (long) dashboardDto.getWeek().getInfor24DeploymentsByProduct().get(productId));
      assertEquals(
          "Compare trial counts for month/productId:" + productId,
          baseMonthUsers,
          (long) dashboardDto.getMonth().getInfor24DeploymentsByProduct().get(productId));
      processed++;
    }

    assertEquals(
        "Compare users added since day",
        yesterdayOffset + oneDayUserCount,
        (long) dashboardDto.getDay().getNewUsersCount());
    assertEquals(
        "Compare users added since week",
        oneWeekOffset + baseWeekUsers,
        (long) dashboardDto.getWeek().getNewUsersCount());
    assertEquals(
        "Compare users added since day",
        oneMonthOffset + baseMonthUsers,
        (long) dashboardDto.getMonth().getNewUsersCount());
  }
  @Test
  public void testGetRollingDeploys() throws Exception {
    int sixMonthDeploy = 2;
    int fiveMonthDeploy = 3;
    int fourMonthDeploy = 5;
    int threeMonthDeploy = 9;
    int twoMonthDeploy = 7;
    int oneMonthDeploy = 4;
    int totalDeploy =
        totalList(
            sixMonthDeploy,
            fiveMonthDeploy,
            fourMonthDeploy,
            threeMonthDeploy,
            twoMonthDeploy,
            oneMonthDeploy);
    int[] deployedCountList =
        new int[] {
          sixMonthDeploy,
          fiveMonthDeploy,
          fourMonthDeploy,
          threeMonthDeploy,
          twoMonthDeploy,
          oneMonthDeploy
        };
    int sixMonthTrial = 5;
    int fiveMonthTrial = 9;
    int fourMonthTrial = 4;
    int threeMonthTrial = 12;
    int twoMonthTrial = 1;
    int oneMonthTrial = 8;
    int totalTrial =
        totalList(
            sixMonthTrial,
            fiveMonthTrial,
            fourMonthTrial,
            threeMonthTrial,
            twoMonthTrial,
            oneMonthTrial);
    int[] trialCountList =
        new int[] {
          sixMonthTrial,
          fiveMonthTrial,
          fourMonthTrial,
          threeMonthTrial,
          twoMonthTrial,
          oneMonthTrial
        };

    assertEquals(
        "Lengths of trialMonths and deployMonths should be same",
        trialCountList.length,
        deployedCountList.length);

    User user =
        this.createUser("*****@*****.**", "UberUser", "LastName", "password", Role.ROLE_SALES);
    userDao.save(user);
    addAWSCredentials(user);
    user = userDao.findByUsername("*****@*****.**");
    assertNotNull(user);

    Date now = new Date();
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(now);
    zeroOutTime(cal);
    cal.set(GregorianCalendar.DATE, 1);

    List<Date> datesToDeploy = getDates(cal.getTime(), oneMonthDeploy);
    List<Date> datesToTry = getDates(cal.getTime(), oneMonthTrial);

    cal.add(GregorianCalendar.MONTH, -1);
    datesToDeploy.addAll(getDates(cal.getTime(), twoMonthDeploy));
    datesToTry.addAll(getDates(cal.getTime(), twoMonthTrial));

    cal.add(GregorianCalendar.MONTH, -1);
    datesToDeploy.addAll(getDates(cal.getTime(), threeMonthDeploy));
    datesToTry.addAll(getDates(cal.getTime(), threeMonthTrial));

    cal.add(GregorianCalendar.MONTH, -1);
    datesToDeploy.addAll(getDates(cal.getTime(), fourMonthDeploy));
    datesToTry.addAll(getDates(cal.getTime(), fourMonthTrial));

    cal.add(GregorianCalendar.MONTH, -1);
    datesToDeploy.addAll(getDates(cal.getTime(), fiveMonthDeploy));
    datesToTry.addAll(getDates(cal.getTime(), fiveMonthTrial));

    cal.add(GregorianCalendar.MONTH, -1);
    datesToDeploy.addAll(getDates(cal.getTime(), sixMonthDeploy));
    datesToTry.addAll(getDates(cal.getTime(), sixMonthTrial));

    assertEquals("Trial total dates", totalTrial, datesToTry.size());
    assertEquals("Deploy total dates", totalDeploy, datesToDeploy.size());

    Region region = regionDao.findById(1L);
    assertNotNull(region);
    /*
     * TRIALS SECTION
     */

    List<Product> productsForTrial = productDao.findByTrialsAvailable(true);
    ArrayList<Long> validTrialProductIds = new ArrayList<>();

    for (Product product : productsForTrial) {

      ProductVersion productVersion = pickOne(product.getProductVersions(), region, false);

      if (productVersion == null) {
        continue;
      }
      loginAdminUser();
      this.activateTrial("*****@*****.**", product);
      validTrialProductIds.add(product.getId());
      login("*****@*****.**", "password");

      for (Date tryDate : datesToTry) {
        DeployRequestDto deployRequestDto =
            this.getTrialRequestFor(user, productVersion, region, tryDate);
        DeploymentStackDto retDto =
            deploymentService.deployMultipleProducts(getRequestStub(), deployRequestDto);
        TrialInstance instance = trialInstanceDao.findById(retDto.getId());
        assertEquals(instance.getCreatedAt(), tryDate);
      }
    }

    List<Long[]> productAndVersionIdList =
        this.getDtoProdAndVersionList(productDao.findAll(), region);
    for (Date deployDate : datesToDeploy) {
      AmazonCredentials amazonCredentials =
          amazonCredentialsDao.findByUserAndName(user, "Dummy Key");
      assertNotNull(amazonCredentials);
      loginAdminUser();
      activateDeploys(user, productAndVersionIdList);
      login(user.getUsername(), "password");
      DeployRequestDto reqDto =
          this.getDeployRequestFor(
              user, productAndVersionIdList, region, amazonCredentials, deployDate);
      DeploymentStackDto result =
          deploymentService.deployMultipleProducts(getRequestStub(), reqDto);
      DeploymentStack stack = deploymentStackDao.findById(result.getId());
      assertEquals(
          "deployDate and stack created at times should be ==", deployDate, stack.getCreatedAt());
    }

    loginAdminUser();
    DashboardRollingDto rollingDto = dashboardService.getRollingList(deployedCountList.length);
    assertEquals(
        "Confirm correct num of months..",
        deployedCountList.length,
        (int) rollingDto.getMonthCount());
    int index = 0;
    for (DashboardRollingPeriodDto period : rollingDto.getRollingDeployments()) {
      DashboardRollingMonthDto month = (DashboardRollingMonthDto) period;
      assertEquals("Confirm index position", index + 1, (int) month.getMonth());
      assertEquals(
          "Confirm total deploys for month (index:" + index + "):" + month.getName(),
          (long) deployedCountList[index],
          (long) month.getAws());
      assertEquals(
          "Confirm total trials for month (index:" + index + "):" + month.getName(),
          (long) (trialCountList[index] * validTrialProductIds.size()),
          (long) month.getInfor24());

      index++;
    }
  }