/**
  * Method useWorkspaceResource.
  *
  * @param aVersion R4EFileVersion
  * @return boolean
  */
 public static boolean useWorkspaceResource(R4EFileVersion aVersion) {
   // Get handle to local storage repository
   try {
     if (null != R4EUIModelController.getActiveReview()) {
       final IRFSRegistry localRepository =
           RFSRegistryFactory.getRegistry(R4EUIModelController.getActiveReview().getReview());
       if (null != localRepository) {
         // If resource is available in the workspace, use it.  Otherwise use the local repo
         // version
         if ((null != aVersion) && (null != aVersion.getResource())) {
           final String workspaceFileId =
               localRepository.blobIdFor(((IFile) aVersion.getResource()).getContents());
           final String repoFileId = aVersion.getLocalVersionID();
           if ((null != workspaceFileId) && workspaceFileId.equals((repoFileId))) {
             return true;
           }
         }
       }
     }
   } catch (ReviewsFileStorageException e) {
     R4EUIPlugin.Ftracer.traceWarning("Exception: " + e.toString() + " (" + e.getMessage() + ")");
   } catch (CoreException e) {
     R4EUIPlugin.Ftracer.traceWarning("Exception: " + e.toString() + " (" + e.getMessage() + ")");
   }
   return false;
 }
  /**
   * Method addUserToParticipantList.
   *
   * @param aUser - String
   */
  private void addUsersToParticipantList(String aUser) {
    // Here we first need to resolve any group aliases to multiple users
    final List<String> resolvedUsers = R4EPreferencePage.getParticipantsFromList(aUser.trim());

    for (String user : resolvedUsers) {
      String[] userTokens = user.split(R4EUIConstants.LIST_SEPARATOR);

      // Resolve user in database (if possible)
      R4EParticipant participant = getParticipant(userTokens[0].toLowerCase());
      if (null == participant) {
        return; // Participant already in list
      }

      // Override email with address defined in users group (if any)
      if (2 == userTokens.length && !(userTokens[1].trim().equals(""))) {
        participant.setEmail(userTokens[1]);
      }

      // Override email with address defined in current review (if any)
      if (null != R4EUIModelController.getActiveReview()) {
        R4EParticipant reviewParticipant;
        try {
          reviewParticipant =
              R4EUIModelController.getActiveReview().getParticipant(participant.getId(), false);
          if (null != reviewParticipant) {
            participant.setEmail(reviewParticipant.getEmail());
          }
        } catch (ResourceHandlingException e) {
          UIUtils.displayResourceErrorDialog(e);
        }
      }
      fParticipants.add(participant);
      updateComponents(participant);
    }
  }
  /** Method setViewTreeTable. */
  public void setViewTreeTable() {
    final Object[] expandedElements = getExpandedElements();

    // Create Columns
    createPathColumn();
    createAssignmentColumn();
    createNumChangesColumn();
    createNumAnomaliesColumn();
    getTree().setHeaderVisible(true);

    // Reset Layout to adjust Columns widths
    fTreeColumnLayout.setColumnData(
        fElementColumn.getColumn(), new ColumnWeightData(fElementColumnWeight, true));
    fTreeColumnLayout.setColumnData(
        fPathColumn.getColumn(), new ColumnWeightData(fPathColumnWeight, true));
    fTreeColumnLayout.setColumnData(
        fAssignColumn.getColumn(), new ColumnWeightData(fAssignColumnWeight, true));
    fTreeColumnLayout.setColumnData(
        fNumChangesColumn.getColumn(), new ColumnWeightData(fNumChangesColumnWeight, true));
    fTreeColumnLayout.setColumnData(
        fNumAnomaliesColumn.getColumn(), new ColumnWeightData(fNumAnomaliesColumnWeight, true));

    final R4EUIReviewBasic activeReview = R4EUIModelController.getActiveReview();
    if (null != activeReview) {
      fElementColumn.getColumn().setText(activeReview.getReview().getName());
      fElementColumn
          .getColumn()
          .setToolTipText(
              REVIEW_GROUP_COLUMN_TOOLTIP
                  + activeReview.getParent().getName()
                  + R4EUIConstants.LINE_FEED
                  + REVIEW_COLUMN_LABEL
                  + activeReview.getName());
    }

    // Set Tree Table Filters (shows only Review Items and Files for current review
    final TreeTableFilter filter =
        ((ReviewNavigatorActionGroup) R4EUIModelController.getNavigatorView().getActionSet())
            .getTreeTableFilter();
    fIsDefaultDisplay = false;

    // Save Default Tree input and adjust Tree Table input
    fDefaultInput = this.getInput();
    if (fDefaultInput instanceof R4EUIRootElement || fDefaultInput instanceof R4EUIReviewGroup) {
      this.setInput(R4EUIModelController.getActiveReview());
    }
    this.addFilter(filter);

    // Set Default sorter
    fTreeComparator = getComparator();
    setComparator(fTreeTableComparator);

    // Refresh Display
    this.getTree().getParent().layout();
    setExpandedElements(expandedElements);
  }
 /**
  * Method decorateFont.
  *
  * @param aElement Object
  * @return Font
  * @see org.eclipse.jface.viewers.IFontDecorator#decorateFont(Object)
  */
 public Font decorateFont(Object aElement) { // $codepro.audit.disable
   if (null != R4EUIModelController.getActiveReview()
       && R4EUIModelController.getActiveReview().equals(aElement)) {
     return JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT);
   }
   if (isMyReview((IR4EUIModelElement) aElement)) {
     return JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT);
   }
   return null;
 }
 /** Method setEnabledFields. */
 @Override
 protected void setEnabledFields() {
   if (R4EUIModelController.isJobInProgress()
       || fProperties.getElement().isReadOnly()
       || !fProperties.getElement().isEnabled()
       || null == R4EUIModelController.getActiveReview()
       || ((R4EReviewState) R4EUIModelController.getActiveReview().getReview().getState())
           .getState()
           .equals(R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED)) {
     fPositionText.setForeground(UIUtils.DISABLED_FONT_COLOR);
     fAssignedToText.setForeground(UIUtils.DISABLED_FONT_COLOR);
     fAssignedToButton.setEnabled(false);
     fUnassignedFromButton.setEnabled(false);
   } else {
     fPositionText.setForeground(UIUtils.ENABLED_FONT_COLOR);
     fAssignedToText.setForeground(UIUtils.ENABLED_FONT_COLOR);
     fAssignedToButton.setEnabled(true);
     if (fAssignedToText.getText().length() > 0) {
       fUnassignedFromButton.setEnabled(true);
     } else {
       fUnassignedFromButton.setEnabled(false);
     }
   }
 }
  /**
   * Method updateTargetFile.
   *
   * @param aFile IFile
   * @return IFile
   * @throws CoreException
   * @throws ReviewsFileStorageException
   */
  public static R4EFileVersion updateTargetFile(IFile aFile)
      throws CoreException, ReviewsFileStorageException {

    if (null == aFile) {
      return null; // should never happen
    }

    String remoteID = null;
    String localID = null;

    // Get handle to local storage repository
    final IRFSRegistry localRepository =
        RFSRegistryFactory.getRegistry(R4EUIModelController.getActiveReview().getReview());
    if (null == localRepository) {
      return null;
    }
    // Get Remote repository file info
    final ScmConnector connector = ScmCore.getConnector(aFile.getProject());
    if (null != connector) {
      final ScmArtifact artifact = connector.getArtifact(aFile);
      if ((null != artifact) && (null != artifact.getPath())) {
        // File found in remote repo.

        // Here we check if the file in the remote repository is different than the input file.
        // We cannot use the artifact ID directly and we need to fetch and calculate that SHA of the
        // remote file
        // because we do not know which version control system is used.
        // We need to do this comparison because the versions always return the latest file stored.

        final IFileRevision fileRev = artifact.getFileRevision(null);
        if (null != fileRev) {
          final IStorage fileStore = fileRev.getStorage(null);
          if (null != fileStore) {
            remoteID = localRepository.blobIdFor(fileStore.getContents());
            localID = localRepository.blobIdFor(aFile.getContents());
            if ((null != remoteID) && remoteID.equals(localID)) {
              // The files are the same. Copy from the remote repo
              return copyRemoteFileToLocalRepository(localRepository, artifact);
            }
          }
        }
        // The files are different.  This means the current user modified the file in his workspace
        return copyWorkspaceFileToLocalRepository(localRepository, aFile);
      }
    }
    // Else we copy the file that is in the current workspace
    return copyWorkspaceFileToLocalRepository(localRepository, aFile);
  }
  /**
   * Method updateBaseFile.
   *
   * @param aFile IFile
   * @return IFile
   * @throws CoreException
   * @throws ReviewsFileStorageException
   */
  public static R4EFileVersion updateBaseFile(IFile aFile)
      throws CoreException, ReviewsFileStorageException {
    if (null == aFile) {
      return null; // should never happen
    }

    // Get Remote repository file info
    final ScmConnector connector = ScmCore.getConnector(aFile.getProject());
    if (null != connector) {
      final ScmArtifact artifact = connector.getArtifact(aFile);
      if ((null != artifact) && (null != artifact.getId())) {
        // File was modified, so we need to fetch the base file from the versions repository and
        // copy it to our own local repository
        final IRFSRegistry localRepository =
            RFSRegistryFactory.getRegistry(R4EUIModelController.getActiveReview().getReview());
        return copyRemoteFileToLocalRepository(localRepository, artifact);
      }
    } // else file not in source control

    // File was not modified, or No Version Control System or Remote File detected, so there is no
    // base
    return null;
  }
  /** Method setViewTree. */
  public void setViewTree() {
    final Object[] expandedElements = getExpandedElements();

    double elementColumnWidth = R4EUIConstants.INVALID_VALUE;
    double pathColumnWidth = R4EUIConstants.INVALID_VALUE;
    double assignColumnWidth = R4EUIConstants.INVALID_VALUE;
    double numChangesColumnWidth = R4EUIConstants.INVALID_VALUE;
    double numAnomaliesColumnWidth = R4EUIConstants.INVALID_VALUE;

    if (null != fElementColumn) {
      elementColumnWidth = fElementColumn.getColumn().getWidth();
    }
    createElementsColumn();
    getTree().setHeaderVisible(false);
    if (null != fPathColumn) {
      pathColumnWidth = fPathColumn.getColumn().getWidth();
      fPathColumn.getColumn().dispose();
      fPathColumn = null;
    }
    if (null != fAssignColumn) {
      assignColumnWidth = fAssignColumn.getColumn().getWidth();
      fAssignColumn.getColumn().dispose();
      fAssignColumn = null;
    }
    if (null != fNumChangesColumn) {
      numChangesColumnWidth = fNumChangesColumn.getColumn().getWidth();
      fNumChangesColumn.getColumn().dispose();
      fNumChangesColumn = null;
    }
    if (null != fNumAnomaliesColumn) {
      numAnomaliesColumnWidth = fNumAnomaliesColumn.getColumn().getWidth();
      fNumAnomaliesColumn.getColumn().dispose();
      fNumAnomaliesColumn = null;
    }
    fTreeColumnLayout.setColumnData(fElementColumn.getColumn(), new ColumnWeightData(100, true));

    // Calculate column weights to preserve (if any)
    if (elementColumnWidth != R4EUIConstants.INVALID_VALUE
        && pathColumnWidth != R4EUIConstants.INVALID_VALUE
        && assignColumnWidth != R4EUIConstants.INVALID_VALUE
        && numChangesColumnWidth != R4EUIConstants.INVALID_VALUE
        && numAnomaliesColumnWidth != R4EUIConstants.INVALID_VALUE) {
      final double totalWidth =
          elementColumnWidth
              + pathColumnWidth
              + assignColumnWidth
              + numChangesColumnWidth
              + numAnomaliesColumnWidth;
      fElementColumnWeight = (int) ((elementColumnWidth / totalWidth) * 100);
      fPathColumnWeight = (int) ((pathColumnWidth / totalWidth) * 100);
      fAssignColumnWeight = (int) ((assignColumnWidth / totalWidth) * 100);
      fNumChangesColumnWeight = (int) ((numChangesColumnWidth / totalWidth) * 100);
      fNumAnomaliesColumnWeight = (int) ((numAnomaliesColumnWidth / totalWidth) * 100);
      fElementColumn
          .getColumn()
          .setWidth((int) totalWidth); // make sure width is reset to full treeViewer width
    }
    fIsDefaultDisplay = true;

    // Remove Tree Table filters
    final TreeTableFilter filter =
        ((ReviewNavigatorActionGroup) R4EUIModelController.getNavigatorView().getActionSet())
            .getTreeTableFilter();
    this.removeFilter(filter);

    // Restore Tree sorters (if any)
    setComparator(fTreeComparator);

    // Restore Default Tree input
    this.setInput(fDefaultInput);

    // Set Expanded states correctly
    final List<Object> updatedExpandedElements = new ArrayList<Object>();
    if (expandedElements.length > 0) {
      if (null != expandedElements[0]
          && null != ((IR4EUIModelElement) expandedElements[0]).getParent()) {
        updatedExpandedElements.add(((IR4EUIModelElement) expandedElements[0]).getParent());
        if (null != ((IR4EUIModelElement) expandedElements[0]).getParent().getParent()) {
          updatedExpandedElements.add(
              ((IR4EUIModelElement) expandedElements[0]).getParent().getParent());
        }
      }
      for (Object expandedElement : expandedElements) {
        if (null != expandedElement) {
          updatedExpandedElements.add(expandedElement);
        }
      }
    } else {
      final R4EUIReviewBasic activeReview = R4EUIModelController.getActiveReview();
      if (null != activeReview) {
        updatedExpandedElements.add(activeReview);
        if (null != activeReview.getParent()) {
          updatedExpandedElements.add(activeReview.getParent());
        }
      }
    }
    Object[] elementsToExpand =
        updatedExpandedElements.toArray(new Object[updatedExpandedElements.size()]);
    setExpandedElements(elementsToExpand);
  }
  /**
   * Method buttonPressed.
   *
   * @param buttonId int
   * @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int)
   */
  @Override
  protected void buttonPressed(int buttonId) {
    if (buttonId == IDialogConstants.OK_ID) {
      final List<R4EParticipant> validatedParticipants = new ArrayList<R4EParticipant>();

      for (R4EParticipant newParticipant : fParticipants) {
        // Validate Participant Id
        String validateResult = validateEmptyInput(newParticipant.getId());
        if (null != validateResult) {
          // Validation of input failed
          final ErrorDialog dialog =
              new ErrorDialog(
                  null,
                  R4EUIConstants.DIALOG_TITLE_ERROR,
                  "No input given for Participant Id",
                  new Status(IStatus.ERROR, R4EUIPlugin.PLUGIN_ID, 0, validateResult, null),
                  IStatus.ERROR);
          dialog.open();
          return;
        }

        // Validate Participant Email
        validateResult = validateEmptyInput(newParticipant.getEmail());
        if (null != validateResult) {
          // Validation of input failed
          final ErrorDialog dialog =
              new ErrorDialog(
                  null,
                  R4EUIConstants.DIALOG_TITLE_ERROR,
                  "No Email given for Participant " + newParticipant.getId(),
                  new Status(IStatus.ERROR, R4EUIPlugin.PLUGIN_ID, 0, validateResult, null),
                  IStatus.ERROR);
          dialog.open();
          return;
        }
        if (!CommandUtils.isEmailValid(newParticipant.getEmail())) {
          return;
        }

        // Check if participant already exists (if so ignore but continue)
        R4EParticipant currentParticipant = null;
        if (null
            != R4EUIModelController.getActiveReview()) { // do not do this for participants lists
          try {
            currentParticipant =
                R4EUIModelController.getActiveReview()
                    .getParticipant(newParticipant.getId(), false);
          } catch (ResourceHandlingException e) {
            // ignore
          }
          if (fReviewSource
              && R4EUIModelController.getActiveReview().isParticipant(newParticipant.getId())
              && null != currentParticipant
              && currentParticipant.isEnabled()) {
            final ErrorDialog dialog =
                new ErrorDialog(
                    null,
                    R4EUIConstants.DIALOG_TITLE_ERROR,
                    "Cannot Add Participant " + newParticipant.getId(),
                    new Status(
                        IStatus.ERROR,
                        R4EUIPlugin.PLUGIN_ID,
                        0,
                        "Participant already part of this Review",
                        null),
                    IStatus.ERROR);
            dialog.open();
            continue;
          }

          // Validate Roles (optional)
          if (0 == newParticipant.getRoles().size()) {
            // If there is no roles defined, put one as default depending on the review type
            if (R4EUIModelController.getActiveReview()
                .getReview()
                .getType()
                .equals(R4EReviewType.BASIC)) {
              newParticipant.getRoles().add(R4EUserRole.LEAD);
            } else {
              newParticipant.getRoles().add(R4EUserRole.REVIEWER);
            }
          }
        }
        validatedParticipants.add(newParticipant);
      }
      // Set the participant list to include only the validated participants
      fParticipants = validatedParticipants;
    }
    super.buttonPressed(buttonId);
  }