/**
   * {@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);
  }
  /**
   * {@inheritDoc}
   *
   * @throws DMSException
   * @throws OntologyErrorException
   * @see org.prowim.dms.alfresco.ContentService#uploadDocument(org.prowim.datamodel.dms.Document,
   *     String)
   */
  @Override
  @Interceptors(AuthenticationInterceptor.class)
  public boolean uploadDocument(Document document, String userName)
      throws DMSException, OntologyErrorException {
    Validate.notNull(document);

    ContentServiceSoapBindingStub contentService = getContentService();
    ContentFormat contentFormat =
        new ContentFormat(document.getContentType(), DMSConstants.ENCODING);
    DMSFault dmsFault;

    try {
      if (findFolderOrContent(document.getName()) == null) {
        Reference contentReference =
            this.createReference(document.getName(), organizationEntity.getUser(userName).getID());

        contentService.write(
            contentReference, Constants.PROP_CONTENT, document.getContent(), contentFormat);
        makeVersionable(contentReference);
        return true;
      } else return false;
    } catch (ContentFault e) {
      String message = "Could not create content: ";
      LOG.error(message, e);
      dmsFault = new DMSFault();
      dmsFault.setMessage(message);
      throw new DMSException(message, dmsFault, e.getCause());
    } catch (RemoteException e) {
      String message = "Could not create connection: ";
      LOG.error(message, e);
      dmsFault = new DMSFault();
      dmsFault.setMessage(message);
      throw new DMSException(message, dmsFault, e.getCause());
    }
  }
 /**
  * Gets the caller authorization.
  *
  * @param methodname not null methodname.
  * @param classname not null classname.
  * @return {@link Authorization}.
  * @throws OntologyErrorException if an error occurs in ontology back end
  */
 private Authorization getCallerAuthorization(String methodname, String classname)
     throws OntologyErrorException {
   return DefaultSecurityManager.getInstance()
       .createAuthorization(
           organizationEntity.getUser(sessionCoontext.getCallerPrincipal().getName()).getID(),
           methodname,
           classname);
 }
  /**
   * This checks every not administrator caller if he can change the process model. <br>
   * this returns true if the process (in this context call) can be changed from the caller.
   *
   * @param parameters the method parameter.
   * @return true if the caller can change the process.
   * @throws OntologyErrorException if an error occurs in ontology back end
   */
  private boolean checkNotAdminUser(Object[] parameters) throws OntologyErrorException {

    String modelID = (String) parameters[0];
    LOG.debug("checkNotAdminUser PARAM[0]   " + modelID);
    return DefaultSecurityManager.getInstance()
        .checkPersonCanModifyEntity(
            modelID,
            organizationEntity.getUser(sessionCoontext.getCallerPrincipal().getName()).getID());
  }
  /**
   * {@inheritDoc}
   *
   * @see org.prowim.dms.alfresco.ContentService#writeContent(byte[], java.lang.String,
   *     java.lang.String, java.lang.String, java.lang.String)
   */
  @Interceptors(AuthenticationInterceptor.class)
  public boolean writeContent(
      byte[] content, String name, String mimeType, String frameID, String username)
      throws OntologyErrorException, DMSException {
    Validate.notNull(content);
    Validate.notEmpty(name);
    Validate.notNull(mimeType);
    Validate.notNull(frameID);

    ContentServiceSoapBindingStub contentService = getContentService();
    ContentFormat contentFormat = new ContentFormat(mimeType, DMSConstants.ENCODING);
    DMSFault dmsFault;
    try {
      if (findFolderOrContent(name) == null) {
        Reference contentReference =
            this.createReference(name, organizationEntity.getUser(username).getID());

        Content contentRef =
            contentService.write(contentReference, Constants.PROP_CONTENT, content, contentFormat);
        makeVersionable(contentReference);
        documentManagement.setDocumentIdentification(contentRef.getNode().getUuid(), name, frameID);
        if (this.commonBean
            .getDirectClassOfInstance(frameID)
            .equals(Relation.Classes.KNOWLEDGE_LINK))
          documentManagement.bindDocument(
              contentRef.getNode().getUuid(),
              name,
              frameID,
              getLastVersionLabel(contentRef.getNode()));
        return true;
      } else return false;
    } catch (ContentFault e) {
      String message = "Could not create content: ";
      LOG.error(message, e);
      dmsFault = new DMSFault();
      dmsFault.setMessage(message);
      throw new DMSException(message, dmsFault, e.getCause());
    } catch (RemoteException e) {
      String message = "Could not create connection: ";
      LOG.error(message, e);
      dmsFault = new DMSFault();
      dmsFault.setMessage(message);
      throw new DMSException(message, dmsFault, e.getCause());
    }
  }
  /**
   * {@inheritDoc}
   *
   * @see org.prowim.dms.alfresco.ContentService#createNewVersion(java.lang.String,
   *     java.lang.String, java.lang.String)
   */
  @Interceptors(AuthenticationInterceptor.class)
  public VersionResult createNewVersion(String name, String username, String uuid)
      throws OntologyErrorException, DMSException {
    // get the user
    String userID = organizationEntity.getUser(username).getID();

    AuthoringServiceSoapBindingStub authoringService = WebServiceFactory.getAuthoringService();
    final Reference reference = new Reference(DMSStoreRegistry.STORE_REF, uuid, null);
    final Predicate predicate = new Predicate(new Reference[] {reference}, null, null);
    NamedValue[] comments =
        new NamedValue[] {
          Utils.createNamedValue("description", "User description"),
          Utils.createNamedValue("versionType", "MINOR"),
          Utils.createNamedValue(DMSConstants.Content.AUTHOR_PROP, userID)
        };
    VersionResult vr;
    try {
      vr = authoringService.createVersion(predicate, comments, true);
      String descriptionNew = "This is a sample description for " + name;
      Predicate pred = new Predicate(vr.getNodes(), null, null);

      NamedValue[] titledProps = new NamedValue[2];
      titledProps[0] = Utils.createNamedValue(Constants.PROP_NAME, name);
      titledProps[1] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, descriptionNew);

      CMLUpdate update = new CMLUpdate(titledProps, pred, null);
      CML cml = new CML();
      cml.setUpdate(new CMLUpdate[] {update});

      WebServiceFactory.getRepositoryService().update(cml);

      return vr;
    } catch (AuthoringFault e) {
      LOG.error(
          "Could not create new version in DMS for user " + username + " and UUID " + uuid, e);
    } catch (RemoteException e) {
      LOG.error(
          "Could not create new version in DMS for user " + username + " and UUID " + uuid, e);
    }

    return null;
  }