private Product getTrialExtensionProduct(TrialInstanceUpdateDto trialInstanceUpdateDto) {
    Product product = null;
    if (isNullOrEmpty(trialInstanceUpdateDto.getProductShortName())) {
      if (trialInstanceUpdateDto.getProductId() != null) {
        if (productDao.exists(trialInstanceUpdateDto.getProductId())) {
          product = productDao.getReference(trialInstanceUpdateDto.getProductId());
        }
      }
    } else {
      product = productDao.findByShortName(trialInstanceUpdateDto.getProductShortName());
    }

    return product;
  }
  @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());
  }
  @Test
  public void testRequestTrialApprove() {
    final MockHttpServletRequest requestStub = super.getRequestStub();

    List<ProductVersion> productVersions = new ArrayList<ProductVersion>();

    productVersions.add(
        productVersionDao.findByProductAndName(productDao.findByShortName("EAM"), "EAM-BC-3"));
    productVersions.add(
        productVersionDao.findByProductAndName(productDao.findByShortName("XM"), "XM-BC-3"));
    User user = userDao.findByUsername(testUserName);
    Region region = regionDao.findById(2L);
    Locale locale = Locale.US;
    String comment = "Test comment.";

    final NullEmailProvider emailProvider = new NullEmailProvider();
    trialEmailComponent.setEmailProvider(emailProvider);

    TrialRequest trialRequest =
        trialService.requestTrial(requestStub, productVersions, user, region, locale, comment);
    List<NullEmailProvider.EmailInfo> asyncEmails = emailProvider.getAsyncEmails();
    assertEquals("Verify email count", 2, asyncEmails.size());
    NullEmailProvider.EmailInfo emailInfo = asyncEmails.get(0);
    assertEquals(
        messageProvider.getMessage(
            StringDefs.MESSAGE_TRIAL_REQUEST_SUBJECT,
            trialEmailComponent.productNamesStrungForEmail(productVersions)),
        emailInfo.subject);
    assertTrue(
        emailInfo.text.contains(
            "Products: " + trialEmailComponent.productNamesStrungForEmail(productVersions)));
    assertTrue(emailInfo.text.contains("User: "******"Comment: " + comment));
    assertTrue(emailInfo.text.contains("Region: " + region.getName()));
    assertEquals(StringDefs.BC_LEADS_EMAIL, emailInfo.address);
    String done = trialService.approveTrialRequest(requestStub, trialRequest.getRequestKey());
    assertEquals("Done", done);

    try {
      trialService.deleteTrialRequest(trialRequest.getRequestKey());
      fail("Delete should fail, as it has already been deleted.");
    } catch (DataAccessException dae) {
      // eat.
    }
  }
  @Test
  public void testAddTrialEnvironment() throws Exception {
    loginTestUser();
    List<TrialEnvironment> environments = trialService.getEnvironments(1L);
    int enviroSize = environments.size();

    User user = new User();
    user.setUsername("*****@*****.**");
    user.setFirstName("Test");
    user.setLastName("Test");
    user.setCreatedAt(new Date());
    user.getRoles().add(Role.ROLE_EXTERNAL);
    user.setPassword(securityService.encodePassword("test", user.getCreatedAt()));
    userDao.save(user);

    Product product = new Product();
    product.setShortName("Test");
    product.setName("Test Long");

    productService.addProduct(product);

    ProductVersion productVersion = new ProductVersion();
    productVersion.setName("Test-version");
    productVersion.setCreatedAt(new Date());
    productVersion.setProduct(product);
    productVersion.setIeOnly(true);
    productVersionDao.save(productVersion);
    product.getProductVersions().add(productVersion);
    productDao.save(product);

    emService.flush();

    TrialDto trial = new TrialDto();
    trial.setProductId(product.getId());
    trial.setProductVersionId(productVersion.getId());
    trial.setUserId(user.getId());
    trial.setUrl("http://test/hahahaha");
    trial.setUsername("test");
    trial.setPassword("haha");
    trialService.createTrialEnvironment(trial);
    emService.flush();

    environments = trialService.getEnvironments(product.getId());
    assertEquals(enviroSize + 1, environments.size());
  }
  @Test
  public void testTrialProductChild() throws Exception {
    assertEquals(3, trialProductChildDao.count());
    ProductVersion productVersion =
        productVersionDao.findByProductAndName(productDao.findByShortName("EAM"), "EAM-BC-3");
    TrialEnvironment environment =
        trialEnvironmentDao
            .findByProductVersionAndRegionAndAvailable(
                productVersion, regionDao.findByShortName("NA"), true)
            .get(0);
    for (TrialProductChild tpc :
        trialProductChildDao.findByRegion(regionDao.findByShortName("NA"))) {

      logger.error("tpc.id:" + tpc.getId());
      logger.error("tpc.getChildVersion().getName():" + tpc.getChildVersion().getName());
      logger.error("tpc.getParentVersion().getName():" + tpc.getParentVersion().getName());
    }
    assertEquals(
        "3 records for region:NA",
        3,
        trialProductChildDao.findByRegion(regionDao.findByShortName("NA")).size());
    assertEquals(
        "3 records with WS as parent",
        3,
        trialProductChildDao
            .findByRegionAndParentVersion(
                regionDao.findByShortName("NA"), productVersionDao.findByName("WS-BC-3"))
            .size());
    assertEquals(
        "1 record with EAM as child",
        1,
        trialProductChildDao
            .findByRegionAndChildVersion(regionDao.findByShortName("NA"), productVersion)
            .size());
    assertEquals(
        "2 records should come back for EAM delete",
        2,
        trialObjectsCreatorComponent
            .deleteEnvironmentAndRelations(
                productVersion, regionDao.findByShortName("NA"), environment)
            .size());
  }
  @Test
  public void testRequestTrialSize() {

    final MockHttpServletRequest requestStub = super.getRequestStub();
    List<ProductVersion> productVersions = new ArrayList<ProductVersion>();
    productVersions.add(
        productVersionDao.findByProductAndName(productDao.findByShortName("EAM"), "EAM-BC-3"));
    User user = userDao.findByUsername(testUserName);
    Region region = regionDao.findById(1L);
    Locale locale = Locale.US;
    String comment = "Test comment.";

    final NullEmailProvider emailProvider = new NullEmailProvider();
    trialEmailComponent.setEmailProvider(emailProvider);

    TrialRequest trialRequest =
        trialService.requestTrial(requestStub, productVersions, user, region, locale, comment);

    List<NullEmailProvider.EmailInfo> asyncEmails = emailProvider.getAsyncEmails();
    assertEquals(2, asyncEmails.size());
    NullEmailProvider.EmailInfo emailInfo = asyncEmails.get(0);
    assertEquals(
        messageProvider.getMessage(
            StringDefs.MESSAGE_TRIAL_REQUEST_SUBJECT,
            trialEmailComponent.productNamesStrungForEmail(productVersions)),
        emailInfo.subject);
    assertTrue(
        emailInfo.text.contains(
            "Products: " + trialEmailComponent.productNamesStrungForEmail(productVersions)));
    assertTrue(emailInfo.text.contains("User: "******"Comment: " + comment));
    assertTrue(emailInfo.text.contains("Region: " + region.getName()));
    logger.debug("\n----- EMAIL BODY --- \n" + emailInfo.text + "\n---------------");

    loginAdminUser();

    assertEquals(1, trialService.getTrialRequests().size());
    trialService.deleteTrialRequest(trialRequest.getRequestKey());
    assertEquals(0, trialService.getTrialRequests().size());
  }
  @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());
  }
 // =================
 private void activateDeploys(User user, List<Long[]> productList) {
   for (Long[] ids : productList) {
     Product product = productDao.findById(ids[0]);
     this.activateDeploy(user.getUsername(), product);
   }
 }
  @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++;
    }
  }