/**
   * Downloads a {@link Document} from the DMS.
   *
   * @param uuid the ID of the document in DMS.<br>
   * @param versionLabel the version label to be downloaded. Use {@link
   *     DMSConstants#INITIAL_VERSION_LABEL} for first version. Null is not allowed.
   * @return not null {@link Document} or Exception occurs if no content or no document for the
   *     given frameID, or if the version label does not exist.
   * @throws RemoteException Communication Exception.
   * @throws DMSException if an error occurs in DMS back end
   */
  @Interceptors(AuthenticationInterceptor.class)
  public Document getDocumentInVersion(String uuid, String versionLabel)
      throws RemoteException, DMSException {
    Validate.notNull(uuid);
    Validate.notNull(versionLabel);
    /** Get the version history. */
    VersionHistory versionHistory = null;
    Document document = null;

    versionHistory =
        getAuthoringService()
            .getVersionHistory(getReference(null, uuid, DMSStoreRegistry.STORE_REF));

    for (org.alfresco.webservice.types.Version version : versionHistory.getVersions()) {
      Reference reference = version.getId();
      if (version.getLabel().equals(versionLabel)) {
        document = getContent(reference, DMSStoreRegistry.VERSION_STORE_REF);
        if (document != null) {
          return document;
        }
      }
    }

    throw new IllegalStateException("Could not download the version :  " + versionLabel);
  }
  /**
   * {@inheritDoc}
   *
   * @see org.prowim.dms.alfresco.ContentService#getDocumentVersionHistory(java.lang.String)
   */
  @Interceptors(AuthenticationInterceptor.class)
  public org.prowim.datamodel.dms.VersionHistory getDocumentVersionHistory(String uuid)
      throws DMSException, OntologyErrorException {
    Validate.notNull(uuid);
    VersionHistory versionHistory = null;
    ArrayList<org.prowim.datamodel.dms.Version> versionList =
        new ArrayList<org.prowim.datamodel.dms.Version>();
    try {
      versionHistory =
          getAuthoringService()
              .getVersionHistory(getReference(null, uuid, DMSStoreRegistry.STORE_REF));
    } catch (AuthoringFault e) {
      LOG.error("Authoring fault: ", e);
    } catch (RemoteException e) {
      LOG.error("Remote exception: ", e);
    }

    if (versionHistory != null && versionHistory.getVersions() != null) {
      for (org.alfresco.webservice.types.Version version : versionHistory.getVersions()) {
        String author = "";
        long createdAsLong = version.getCreated().getTime().getTime();
        org.prowim.datamodel.dms.Version clientVersion =
            new org.prowim.datamodel.dms.Version(
                DateUtility.getDateTimeString(new DateTime(createdAsLong)),
                version.getCreator(),
                version.getLabel());

        clientVersion.setInstanceID(uuid);
        NamedValue[] nv = version.getCommentaries();
        boolean hasAuthorProp = false;
        for (int i = 0; i < nv.length; i++) {
          if (nv[i].getName().equals(DMSConstants.Content.AUTHOR_PROP)) {
            if (nv[i].getValue().contains(DMSConstants.Content.USER_ID_PATTERN)) {
              author = organizationEntity.getPerson(nv[i].getValue()).toString();
              clientVersion.setCreator(author);
            }
            hasAuthorProp = true;
            break;
          }
        }
        if (!hasAuthorProp) {
          for (int i = 0; i < nv.length; i++) {
            if (nv[i].getName().equals(DMSConstants.Content.AUTHOR_CONST)) {
              if ((nv[i].getValue() != null)
                  && (nv[i].getValue().contains(DMSConstants.Content.USER_ID_PATTERN))) {
                author = organizationEntity.getPerson(nv[i].getValue()).toString();

                clientVersion.setCreator(author);
                LOG.debug(DMSConstants.Content.AUTHOR_PROP + "   --> " + nv[i].getValue());
                break;
              }
            }
          }
        }
        versionList.add(clientVersion);
      }
    }
    return new org.prowim.datamodel.dms.VersionHistory(uuid, versionList);
  }
  /**
   * Tests the createVersion service method
   *
   * @throws Exception
   */
  public void testVersionMethods() throws Exception {
    Reference reference = createContentAtRoot("create_version_test.txt", INITIAL_VERSION_CONTENT);
    Predicate predicate = convertToPredicate(reference);

    // Get the version history (before its been versioned)
    VersionHistory emptyVersionHistory = this.authoringService.getVersionHistory(reference);
    assertNotNull(emptyVersionHistory);
    assertNull(emptyVersionHistory.getVersions());

    // Create the version
    VersionResult result =
        this.authoringService.createVersion(predicate, getVersionComments(), false);
    assertNotNull(result);
    assertEquals(1, result.getNodes().length);
    assertEquals(1, result.getVersions().length);
    Version version = result.getVersions()[0];
    assertEquals("1.0", version.getLabel());
    // TODO check commentaries
    // TODO check creator

    // Get the version history
    this.authoringService.createVersion(predicate, getVersionComments(), false);
    VersionHistory versionHistory = this.authoringService.getVersionHistory(reference);
    assertNotNull(versionHistory);
    assertEquals(2, versionHistory.getVersions().length);
    // TODO some more tests ...

    // Update the content
    this.contentService.write(
        reference, Constants.PROP_CONTENT, SECOND_VERSION_CONTENT.getBytes(), null);

    // Create another version
    VersionResult versionResult2 =
        this.authoringService.createVersion(predicate, getVersionComments(), false);
    assertNotNull(versionResult2);
    assertEquals(1, versionResult2.getNodes().length);
    assertEquals(1, versionResult2.getVersions().length);
    Version version2 = versionResult2.getVersions()[0];
    assertEquals("1.3", version2.getLabel());
    // TODO check commentaries
    // TODO check creator

    // Check the version history
    VersionHistory versionHistory2 = this.authoringService.getVersionHistory(reference);
    assertNotNull(versionHistory2);
    assertEquals(4, versionHistory2.getVersions().length);
    // TODO some more tests ...

    // Create a major version
    NamedValue versionVal = Utils.createNamedValue("versionType", "MAJOR");
    NamedValue descriptionVal = Utils.createNamedValue("description", "new description");
    NamedValue[] comments = new NamedValue[] {versionVal, descriptionVal};
    VersionResult result5 = this.authoringService.createVersion(predicate, comments, false);
    assertNotNull(result5);
    assertEquals(1, result5.getNodes().length);
    assertEquals(1, result5.getVersions().length);
    Version version5 = result5.getVersions()[0];
    assertEquals("2.0", version5.getLabel());

    // Confirm the current content of the node
    Content[] contents =
        this.contentService.read(
            new Predicate(new Reference[] {reference}, BaseWebServiceSystemTest.store, null),
            Constants.PROP_CONTENT.toString());
    Content readResult1 = contents[0];
    String content1 = ContentUtils.getContentAsString(readResult1);
    assertEquals(SECOND_VERSION_CONTENT, content1);

    // Revert the node to the first version
    this.authoringService.revertVersion(reference, "1.0");

    // Confirm that the state of the node has been reverted
    Content[] contents2 =
        this.contentService.read(
            new Predicate(new Reference[] {reference}, BaseWebServiceSystemTest.store, null),
            Constants.PROP_CONTENT.toString());
    Content readResult2 = contents2[0];
    String content2 = ContentUtils.getContentAsString(readResult2);
    assertEquals(INITIAL_VERSION_CONTENT, content2);

    // Now delete the version history
    VersionHistory deletedVersionHistory = this.authoringService.deleteAllVersions(reference);
    assertNotNull(deletedVersionHistory);
    assertNull(deletedVersionHistory.getVersions());

    // Check the version history
    VersionHistory versionHistory3 = this.authoringService.getVersionHistory(reference);
    assertNotNull(versionHistory3);
    assertNull(versionHistory3.getVersions());
  }