/////////////////////////////////////////////////////////////////////////////////////////
  //  TEST
  /////////////////////////////////////////////////////////////////////////////////////////
  //	@Test
  public void testGuaranteeXml() {
    AA88ClientAPI api = TestAPIBase.getClientApi(AA88ClientAPI.class);

    AA88UserContext userContext = api.getUserContext();
    String userContextXml = api.getModelObjectsMarshaller().xmlFromBean(userContext);
    System.out.println(userContextXml);

    AA88Guarantee mockGuarantee =
        AA88MockObjectsBuilder.buildMockGuarantee(
            TEST_FILELIST_FOLDER_PATH, AA88GuaranteedUnitID.forId("test1.txt"));
    String xml = api.getModelObjectsMarshaller().xmlFromBean(mockGuarantee);
    System.out.println(xml);
  }
  /**
   * Test the guarantee creation (startGuarantee), refresh (refreshGuarantee) and stop
   * (stopGuarantee)
   */
  @Test
  public void testLifeCycle() {
    log.warn("=============================================================");
    log.warn("Test Life Cycle");
    log.warn("=============================================================");
    AA88ClientAPI api = TestAPIBase.getClientApi(AA88ClientAPI.class);

    // Use a type that encapsulates all the tests
    AA88LifeCycleServicesTestHelper testHelp =
        new AA88LifeCycleServicesTestHelper(api, STORAGE_SERVICES);
    AA88Guarantee guarantee =
        testHelp.testLifeCycle(
            TEST_FILELIST_FOLDER_PATH,
            FileName.of("test2.txt"),
            Arrays.asList(
                AA88MethodToBeTested.START,
                AA88MethodToBeTested.REFRESH,
                AA88MethodToBeTested.STOP));
    // store the tested guarantee oid just to remove it at the end
    _testedGuaranteesOids.add(guarantee.getOid());
  }
  //	@After
  public void tearDown() throws Exception {
    AA88ClientAPI api = TestAPIBase.getClientApi(AA88ClientAPI.class);

    if (CollectionUtils.hasData(_testedGuaranteesOids)) {
      for (AA88GuaranteeOID oid : _testedGuaranteesOids) {
        // [1]: Delete the guarantee publish requests at the DB (if exists)

        Collection<AA88GuaranteePublishRequestOID> deletedGuaranteePubRequestOids =
            api.guaranteesAPI()
                .getForPublishRequestCRUD()
                .deleteAllPublishRequestsForGuaranteeWithOid(oid);
        // [2]: Delete the guarantee record at the DB
        AA88Guarantee deletedGuarantee = api.guaranteesAPI().getForCRUD().delete(oid);
        // [3] - Delete the guarantee zip file & folder
        STORAGE_SERVICES.deleteGuaranteedUnitStorage(
            api.getUserContext(),
            deletedGuarantee.getSourceSystemId(),
            deletedGuarantee.getGuaranteedUnitId());
      }
    }
  }
  //	@Test
  public void testRefresh() {
    log.warn("=============================================================");
    log.warn("Test Refresh");
    log.warn("=============================================================");

    AA88ClientAPI api = TestAPIBase.getClientApi(AA88ClientAPI.class);

    // Use a type that encapsulates all the tests
    final AA88LifeCycleServicesTestHelper testHelp =
        new AA88LifeCycleServicesTestHelper(api, STORAGE_SERVICES);

    // [1] - Create guarantees
    File testFileListsContainerFolder = new File(TEST_FILELIST_FOLDER_PATH.asAbsoluteString());
    File[] testFileLists = testFileListsContainerFolder.listFiles();

    Observable.from(testFileLists)
        .map(
            new Func1<File, AA88Guarantee>() {
              @Override
              public AA88Guarantee call(final File fileList) {
                log.warn("\n\n\n");
                log.warn(
                    "CREATE & DO A FIRST REFRESH for MOCK guarantee using fileList at {}",
                    Paths.forPaths()
                        .join(TEST_FILELIST_FOLDER_PATH, fileList.getName())
                        .asAbsoluteString());

                AA88Guarantee guarantee =
                    testHelp.testLifeCycle(
                        TEST_FILELIST_FOLDER_PATH,
                        FileName.of(fileList.getName()),
                        Arrays.asList(AA88MethodToBeTested.START, AA88MethodToBeTested.REFRESH));
                log.warn(
                    "MOCK guarantee with oid={} CREATED & REFRESHED FOR THE FIRST TIME for fileList at {}",
                    guarantee.getOid(),
                    Paths.forPaths()
                        .join(TEST_FILELIST_FOLDER_PATH, fileList.getName())
                        .asAbsoluteString());
                log.warn("\n\n\n");
                return guarantee;
              }
            })
        .subscribe(
            new Observer<AA88Guarantee>() {
              @Override
              public void onNext(final AA88Guarantee guarantee) {
                _testedGuaranteesOids.add(guarantee.getOid());
              }

              @Override
              public void onCompleted() {
                log.warn("\n\n\n\n\n\n");
                log.warn(
                    ":::::::: {} test guarantees with oids={} created__________________________",
                    _testedGuaranteesOids.size(),
                    _testedGuaranteesOids);
              }

              @Override
              public void onError(final Throwable th) {
                // BEWARE!!! RxJava will catch Exception and most Error.
                //			 Exceptions cannot be propagated out of RxJava
                //			 ... so even if Throwables.propagate(th) is used, the exception is NEVER thrown
                // outside RxJava
                //		 	 the only option is to use Exceptions.throwIfFatal(th)
                //			 (see https://github.com/ReactiveX/RxJava/issues/969)
                // Exceptions.throwIfFatal(th);
                th.printStackTrace(System.out);
              }
            });

    // [2] - With the created guarantees, call refresh guarantee
    if (CollectionUtils.hasData(_testedGuaranteesOids)) {
      log.warn(
          ":::::::: With the created guarantees --> Refesh all Actives Guarantees _____________________________________________________________________");

      // Call refresh all active guarantees and wait a moment to the scheduler to start
      api.guaranteesAPI()
          .getForLifeCycle()
          .refreshAllActiveGuarantees(AA88SourceSystemID.forId("PLATEA-Internet"));
      Threads.safeSleep(TimeLapse.createFor("5s"));

      // Check the process
      final Collection<BeingRefreshedGuarantee> refreshPendingGuarantees =
          FluentIterable.from(_testedGuaranteesOids)
              .transform(
                  new Function<AA88GuaranteeOID, BeingRefreshedGuarantee>() {
                    @Override
                    public BeingRefreshedGuarantee apply(final AA88GuaranteeOID oid) {
                      return new BeingRefreshedGuarantee(oid);
                    }
                  })
              .toList();
      long startTS = System.currentTimeMillis();
      long elapsedMilis = 0;
      boolean anyRefreshPendingGuarantee = false;
      do {
        for (BeingRefreshedGuarantee b : refreshPendingGuarantees) {
          if (b.isRefreshed()) continue;

          // Check that there's NO minor version in requested status
          AA88Guarantee mockGuarantee = api.guaranteesAPI().getForCRUD().load(b.getOid());
          if (mockGuarantee.existsMinorVersionInRequestedStatus()) {
            log.warn(
                "...the guarantee with oid={} unitId={} is still being refreshed (the notary is working)...give a moment to the notary to do it's work...",
                mockGuarantee.getOid(),
                mockGuarantee.getGuaranteedUnitId());
          } else {
            log.warn(
                "The guarantee with oid={} unitId={} has been refreshed!... stop guaranteeing it",
                mockGuarantee.getOid(),
                mockGuarantee.getGuaranteedUnitId());
            b.setRefreshed(true);
          }
        }
        anyRefreshPendingGuarantee = _anyRefreshPendingGuarantee(refreshPendingGuarantees);
        if (anyRefreshPendingGuarantee) {
          elapsedMilis = System.currentTimeMillis() - startTS;
          Threads.safeSleep(TimeLapse.createFor("5s"));
        }
        Assert.assertTrue(
            elapsedMilis
                < AA88LifeCycleServicesTestHelper.MAX_REFRESH_TIME_PER_GUARANTEE
                    * _testedGuaranteesOids.size());
      } while (anyRefreshPendingGuarantee);

      // Stop guaranteeing
      for (AA88GuaranteeOID oid : _testedGuaranteesOids) {
        log.warn("Stop guaranteein guarantee with oid={}", oid);
        api.guaranteesAPI().getForLifeCycle().stopGuaranteeingNow(oid);
      }

      // Check that all guarantees has been stoped
      for (AA88GuaranteeOID oid : _testedGuaranteesOids) {
        AA88Guarantee mockGuarantee = api.guaranteesAPI().getForCRUD().load(oid);
        Assert.assertTrue(!mockGuarantee.isActive());
      }
    } else {
      log.warn("Could NOT create any mock guarantee!!!");
    }
  }