Example #1
0
  /*
   * Gets and caches an image for a JarEntryFile.
   * The image for a JarEntryFile is retrieved from the EditorRegistry.
   */
  private Image getImageForJarEntry(IStorage element) {
    if (fJarImageMap == null) return getDefaultImage();

    if (element == null || element.getName() == null) return getDefaultImage();

    // Try to find icon for full name
    String name = element.getName();
    Image image = (Image) fJarImageMap.get(name);
    if (image != null) return image;
    IFileEditorMapping[] mappings = getEditorRegistry().getFileEditorMappings();
    int i = 0;
    while (i < mappings.length) {
      if (mappings[i].getLabel().equals(name)) break;
      i++;
    }
    String key = name;
    if (i == mappings.length) {
      // Try to find icon for extension
      IPath path = element.getFullPath();
      if (path == null) return getDefaultImage();
      key = path.getFileExtension();
      if (key == null) return getDefaultImage();
      image = (Image) fJarImageMap.get(key);
      if (image != null) return image;
    }

    // Get the image from the editor registry
    ImageDescriptor desc = getEditorRegistry().getImageDescriptor(name);
    image = desc.createImage();

    fJarImageMap.put(key, image);

    return image;
  }
Example #2
0
  /*
   * (non-Javadoc)
   *
   * @see core.resources.ICoreResource#seek(core.resources.IResourceLocationRequestor)
   */
  public void lookup(IResourceAcceptor requestor, LookupDepth depth) {
    String packageName = fRoot.toPackageName(this);
    IPackageFragment[] fragments = fRoot.getAllPackageFragments(packageName);
    for (int i = 0; i < fragments.length; i++) {
      Object[] nonJavaResources = null;
      try {
        if (fragments[i].isReadOnly()) {
          // TODO - is this the correct check for a package in a jar file?
          nonJavaResources = fragments[i].getNonJavaResources();
        } else {
          IContainer container = (IContainer) fragments[i].getUnderlyingResource();
          if (container != null && container.exists()) {
            IResource[] members = container.members(false);
            ArrayList<IResource> resultList = new ArrayList<IResource>();
            for (int j = 0; j < members.length; j++) {
              if (members[j] instanceof IFile) resultList.add(members[j]);
            }
            nonJavaResources = resultList.toArray();
          }
        }
      } catch (CoreException e) {
        TapestryCore.log(e);
      }
      if (nonJavaResources == null) continue;

      for (int j = 0; j < nonJavaResources.length; j++) {
        IStorage storage = (IStorage) nonJavaResources[j];
        ICoreResource loc = new ClasspathResource(fRoot, getPath() + storage.getName());
        if (!requestor.accept(loc)) break;
      }
    }
  }
 private ISourceTagProvider createSourceTagProvider(IStorage storage) {
   ITranslationUnit tUnit = null;
   if (storage instanceof IFile) {
     tUnit = (ITranslationUnit) CoreModel.getDefault().create((IFile) storage);
   } else if (storage instanceof IFileState) {
     ICModel cModel = CoreModel.getDefault().getCModel();
     ICProject[] cProjects;
     try {
       cProjects = cModel.getCProjects();
       if (cProjects.length > 0) {
         tUnit =
             CoreModel.getDefault().createTranslationUnitFrom(cProjects[0], storage.getFullPath());
       }
     } catch (CModelException e) {
     }
   } else {
     IEditorInput input = CDTUITools.getEditorInputForLocation(storage.getFullPath(), null);
     if (input != null) {
       tUnit = (ITranslationUnit) input.getAdapter(ITranslationUnit.class);
     }
   }
   if (tUnit != null) {
     return new CSourceTagProvider(tUnit);
   }
   return null;
 }
Example #4
0
  /**
   * Copies the content of a given file revision to a temporary file inside the state location of
   * this plugin.
   *
   * @param baseName the base name, i.e. a file UUID, never null.
   * @param type an additional extension for the given base name, i.e. "<em>base.cpc</em>", never
   *     null.
   * @param fileRev the file revision to retrieve the content from, may be NULL.
   * @return <em>true</em> on success, <em>false</em> on failure.
   */
  public static boolean storeFileRevision(
      String baseName, String type, IFileRevision fileRev, IProgressMonitor monitor) {
    if (log.isTraceEnabled())
      log.trace(
          "storeFileRevision() - baseName: "
              + baseName
              + ", type: "
              + type
              + ", fileRev: "
              + fileRev);
    assert (baseName != null && type != null);

    if (fileRev == null) return false;

    try {
      IStorage storage = fileRev.getStorage(monitor);
      if (storage == null) return false;

      String content = CoreFileUtils.readStreamContent(storage.getContents());
      if (content == null) return false;

      return storeTemporaryFile(baseName, type, content);
    } catch (CoreException e) {
      log.error(
          "storeFileRevision() - error while storing file revision data - baseName: "
              + baseName
              + ", fileRev: "
              + fileRev
              + " - "
              + e,
          e);
      return false;
    }
  }
Example #5
0
  @Override
  protected void setInput(final IEditorInput input) {
    if (input instanceof FileEditorInput) {
      final IFile file = ((FileEditorInput) input).getFile();
      setPartName(file.getProject().getName() + "/" + input.getName());

      editorInput =
          new RedProjectEditorInput(
              Optional.of(file),
              !file.isReadOnly(),
              new RedEclipseProjectConfigReader().readConfigurationWithLines(file));
      installResourceListener();
    } else {
      final IStorage storage = (IStorage) input.getAdapter(IStorage.class);
      if (storage != null) {
        setPartName(storage.getName() + " [" + storage.getFullPath() + "]");

        try (InputStream stream = storage.getContents()) {
          editorInput =
              new RedProjectEditorInput(
                  Optional.<IFile>absent(),
                  !storage.isReadOnly(),
                  new RobotProjectConfigReader().readConfigurationWithLines(stream));
        } catch (final CoreException | IOException e) {
          throw new IllegalProjectConfigurationEditorInputException(
              "Unable to open editor: unrecognized input of class: " + input.getClass().getName(),
              e);
        }
      } else {
        throw new IllegalProjectConfigurationEditorInputException(
            "Unable to open editor: unrecognized input of class: " + input.getClass().getName());
      }
    }
    super.setInput(input);
  }
Example #6
0
  /*
   * (non-Javadoc)
   *
   * @see core.resources.ICoreResource#getContents()
   */
  public InputStream getContents() {
    try {
      IStorage storage = getStorage();
      if (storage != null) return storage.getContents();
    } catch (CoreException e) {
      TapestryCore.log(e);
    }

    return null;
  }
  private void getChangedLines(Subscriber s, PatchFile p, IProgressMonitor monitor) {
    try {
      // For an outgoing changed resource, find out which lines
      // differ from the local file and its previous local version
      // (i.e. we don't want to force a diff with the repository).
      IDiff d = s.getDiff(p.getResource());
      if (d instanceof IThreeWayDiff
          && ((IThreeWayDiff) d).getDirection() == IThreeWayDiff.OUTGOING) {
        IThreeWayDiff diff = (IThreeWayDiff) d;
        monitor.beginTask(null, 100);
        IResourceDiff localDiff = (IResourceDiff) diff.getLocalChange();
        IResource resource = localDiff.getResource();
        if (resource instanceof IFile) {
          IFile file = (IFile) resource;
          monitor.subTask(Messages.getString("ChangeLog.MergingDiffs")); // $NON-NLS-1$
          String osEncoding = file.getCharset();
          IFileRevision ancestorState = localDiff.getBeforeState();
          IStorage ancestorStorage;
          if (ancestorState != null) {
            ancestorStorage = ancestorState.getStorage(monitor);
            p.setStorage(ancestorStorage);
          } else ancestorStorage = null;

          try {
            // We compare using a standard differencer to get ranges
            // of changes.  We modify them to be document-based (i.e.
            // first line is line 1) and store them for later parsing.
            LineComparator left = new LineComparator(ancestorStorage.getContents(), osEncoding);
            LineComparator right = new LineComparator(file.getContents(), osEncoding);
            for (RangeDifference tmp : RangeDifferencer.findDifferences(left, right)) {
              if (tmp.kind() == RangeDifference.CHANGE) {
                // Right side of diff are all changes found in local file.
                int rightLength = tmp.rightLength() > 0 ? tmp.rightLength() : tmp.rightLength() + 1;
                // We also want to store left side of the diff which are changes to the ancestor as
                // it may contain
                // functions/methods that have been removed.
                int leftLength = tmp.leftLength() > 0 ? tmp.leftLength() : tmp.leftLength() + 1;
                // Only store left side changes if the storage exists and we add one to the start
                // line number
                if (p.getStorage() != null)
                  p.addLineRange(tmp.leftStart(), tmp.leftStart() + leftLength, false);
                p.addLineRange(tmp.rightStart(), tmp.rightStart() + rightLength, true);
              }
            }
          } catch (UnsupportedEncodingException e) {
            // do nothing for now
          }
        }
        monitor.done();
      }
    } catch (CoreException e) {
      // Do nothing if error occurs
    }
  }
 public static String[] parseJarEntryFile(IStorage storage) {
   if (storage == null) return null;
   String s = storage.toString();
   if (!s.startsWith("JarEntryFile[")) return null; // $NON-NLS-1$
   s = s.substring("JarEntryFile[".length()); // $NON-NLS-1$
   int i = s.indexOf("::"); // $NON-NLS-1$
   if (i < 0) return null;
   String jarFile = s.substring(0, i);
   String entry = storage.getFullPath().toString();
   return new String[] {jarFile, entry};
 }
 @Override
 public boolean isReadOnly(Object element) {
   IStorage storage = EditorUtils.getStorageFromInput(element);
   if (storage != null) {
     return storage.isReadOnly();
   }
   File file = EditorUtils.getLocalFileFromInput(element);
   if (file != null) {
     return !file.isFile();
   }
   return super.isReadOnly(element);
 }
  protected boolean setDocumentContent(
      IDocument document, IEditorInput editorInput, String encoding) throws CoreException {
    if (editorInput instanceof IStorageEditorInput) {
      IStorage storage = ((IStorageEditorInput) editorInput).getStorage();
      EditingDomain editingDomain = getEditingDomain();
      URI resourceId = URI.createURI(storage.getFullPath().toString());
      Resource resource = editingDomain.getResourceSet().getResource(resourceId, true);
      IModel model = loadModel(resource, editingDomain);
      setDocumentContent(document, model, resourceId);

      return true;
    }
    return 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);
  }
Example #12
0
  /**
   * Computes and results the byte count for a file revision using its storage. Uses an input stream
   * reader to count bytes read.
   *
   * @param fr file revision
   * @param monitor progress monitor for storage access
   * @return line count or zero, exceptions caught and reported to log
   */
  protected int getByteCount(IFileRevision fr, IProgressMonitor monitor) {
    int byteCount = 0;
    try {
      IStorage storage = fr.getStorage(monitor);
      InputStream is = storage.getContents();
      InputStreamReader isr = new InputStreamReader(is);
      while (isr.read() != -1) {
        byteCount++;
      }
      isr.close();
      is.close();
    } catch (Exception e) {
      CertWareLog.logError(
          String.format("%s %s", "Gathering byte count for revision", fr.getName()), e);
    }

    return byteCount;
  }
Example #13
0
 /**
  * Computes and results the line count for a file revision using its storage. Uses a line number
  * reader to compute the line count.
  *
  * @param fr file revision
  * @param monitor progress monitor for storage access
  * @return line count or zero, exceptions caught and reported to log
  */
 protected int getLineCount(IFileRevision fr, IProgressMonitor monitor) {
   int lineCount = 0;
   try {
     IStorage storage = fr.getStorage(monitor);
     InputStream is = storage.getContents();
     LineNumberReader lineNumberReader = new LineNumberReader(new InputStreamReader(is));
     while (lineNumberReader.ready()) {
       lineNumberReader.readLine();
       lineCount++;
     }
     lineNumberReader.close();
     is.close();
   } catch (Exception e) {
     CertWareLog.logError(
         String.format("%s %s", "Gathering line count for revision", fr.getName()), e);
   }
   return lineCount;
 }
  /**
   * Method copyRemoteFileToLocalRepository.
   *
   * @param aLocalRepository IRFSRegistry
   * @param aArtifact ScmArtifact
   * @return IFile
   * @throws CoreException
   * @throws ReviewsFileStorageException
   */
  public static R4EFileVersion copyRemoteFileToLocalRepository(
      IRFSRegistry aLocalRepository, ScmArtifact aArtifact)
      throws ReviewsFileStorageException, CoreException {

    if ((null == aArtifact)
        || (null == aArtifact.getPath())
        || aArtifact.getPath().equals(INVALID_PATH)) {
      return null; // File not found in remote repository
    }
    final IFileRevision fileRev = aArtifact.getFileRevision(null);
    if (null == fileRev) {
      return null;
    }

    // Pull file from the version control system
    InputStream iStream = null;
    final IStorage fileStore = fileRev.getStorage(null);
    if (null == fileStore) {
      return null;
    }
    try {
      iStream = fileStore.getContents();
    } catch (CoreException e) {
      R4EUIPlugin.Ftracer.traceInfo("Exception: " + e.toString() + " (" + e.getMessage() + ")");
      return null;
    }

    // Create and Set value in temporary File version
    final R4EFileVersion tmpFileVersion = RModelFactory.eINSTANCE.createR4EFileVersion();
    if ((null != tmpFileVersion) && (null != aLocalRepository)) {
      updateFileVersion(tmpFileVersion, aArtifact);

      // Push a local copy to local review repository, and obtain the local id
      tmpFileVersion.setLocalVersionID(aLocalRepository.registerReviewBlob(iStream));
      if (null != iStream) {
        try {
          iStream.close();
        } catch (IOException e) {
          R4EUIPlugin.Ftracer.traceWarning("Exception while closing stream, " + e.toString());
        }
      }
    }
    return tmpFileVersion;
  }
 /**
  * @see
  *     org.eclipse.emf.diffmerge.connector.core.ext.AbstractRevisionScopeDefinitionFactory#getURIForRevision(org.eclipse.team.core.history.IFileRevision)
  */
 @Override
 protected URI getURIForRevision(IFileRevision revision_p) throws CoreException {
   URI result = null;
   IResourceVariant variant = getVariant(revision_p);
   if (variant instanceof BaseFileVariant) {
     // Ancestor
     ILocalResource res = ((BaseFileVariant) variant).getResource();
     IRepositoryLocation location =
         SVNRemoteStorage.instance().getRepositoryLocation(res.getResource());
     result =
         URI.createURI(
             location.getRepositoryRootUrl()
                 + ((BaseFileVariant) variant).getResource().getResource().getFullPath(),
             true);
   } else {
     // Remote
     IStorage storage = getStorage(revision_p);
     if (storage != null) result = toFileURI(storage.getFullPath().toString());
   }
   return result;
 }
 private void initializeResourceObjectFromStorage(IStorageEditorInput input) {
   URI uri = null;
   try {
     IStorage storage = input.getStorage();
     InputStream inputStream = storage.getContents();
     uri = URI.createURI(storage.getName(), true);
     ResourceSet resourceSet = getResourceSet();
     com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.IRezeptTextResource resource =
         (com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.IRezeptTextResource)
             resourceSet.createResource(uri);
     resource.load(inputStream, null);
     setResource(resource);
   } catch (CoreException e) {
     com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.ui.RezeptUIPlugin.logError(
         "Exception while loading resource (" + uri + ") in " + getClass().getSimpleName() + ".",
         e);
   } catch (IOException e) {
     com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.ui.RezeptUIPlugin.logError(
         "Exception while loading resource (" + uri + ") in " + getClass().getSimpleName() + ".",
         e);
   }
 }
 @Override
 protected final void doSaveDocument(
     IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
     throws CoreException {
   if (element instanceof IEditorInput) {
     IEditorInput editorInput = (IEditorInput) element;
     if (editorInput instanceof IStorageEditorInput) {
       IStorage storage = ((IStorageEditorInput) editorInput).getStorage();
       EditingDomain editingDomain = getEditingDomain();
       Resource resource =
           editingDomain
               .getResourceSet()
               .getResource(URI.createURI(storage.getFullPath().toString()), true);
       try {
         resource.save(Collections.EMPTY_MAP);
       } catch (IOException e) {
         // TODO
         throw new RuntimeException(e);
       }
     }
   }
 }
  /**
   * Method updateFileVersion
   *
   * @param aTargetFileVer R4EFileVersion
   * @param aScmArt ScmArtifact
   * @throws CoreException
   */
  public static void updateFileVersion(R4EFileVersion aTargetFileVer, ScmArtifact aScmArt)
      throws CoreException {

    if ((null != aTargetFileVer) && (null != aScmArt)) {
      aTargetFileVer.setName(aScmArt.getFileRevision(null).getName());
      aTargetFileVer.setVersionID(aScmArt.getId());
      final IFileRevision fileRev = aScmArt.getFileRevision(null);
      if (null != fileRev) {
        final IStorage fileStore = fileRev.getStorage(null);
        if (null != fileStore) {
          final IPath filePath = fileStore.getFullPath();
          if (null != filePath) {
            aTargetFileVer.setRepositoryPath(filePath.toPortableString());
          }
        }
      }

      final String fileRelPath = aScmArt.getProjectRelativePath();
      if (null == fileRelPath) {
        R4EUIPlugin.Ftracer.traceDebug(
            "Invalid relative file path in scmArtifact with path: " + aScmArt.getPath());
      }
      final IProject project = ResourceUtils.getProject(aScmArt.getProjectName());
      final IResource resource = ResourceUtils.findResource(project, fileRelPath);

      aTargetFileVer.setPlatformURI(ResourceUtils.toPlatformURIStr(resource));
      aTargetFileVer.setResource(resource);

      final String projPlatformURI = ResourceUtils.toPlatformURIStr(project);
      if (null == projPlatformURI) {
        R4EUIPlugin.Ftracer.traceDebug(
            "Unable to resolve the project: "
                + aScmArt.getProjectName()
                + " platform's URI, in scmArtifact with path: "
                + aScmArt.getPath());
      }
    }
  }
  /*
   * Gets and caches an image for a JarEntryFile.
   * The image for a JarEntryFile is retrieved from the EditorRegistry.
   */
  private Image getImageForJarEntry(IStorage element) {
    if (element instanceof IJarEntryResource && !((IJarEntryResource) element).isFile()) {
      return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
    }

    if (fJarImageMap == null) return getDefaultImage();

    if (element == null || element.getName() == null) return getDefaultImage();

    // Try to find icon for full name
    String name = element.getName();
    Image image = fJarImageMap.get(name);
    if (image != null) return image;
    IFileEditorMapping[] mappings = getEditorRegistry().getFileEditorMappings();
    int i = 0;
    while (i < mappings.length) {
      if (mappings[i].getLabel().equals(name)) break;
      i++;
    }
    String key = name;
    if (i == mappings.length) {
      // Try to find icon for extension
      IPath path = element.getFullPath();
      if (path == null) return getDefaultImage();
      key = path.getFileExtension();
      if (key == null) return getDefaultImage();
      image = fJarImageMap.get(key);
      if (image != null) return image;
    }

    // Get the image from the editor registry
    ImageDescriptor desc = getEditorRegistry().getImageDescriptor(name);
    image = desc.createImage();

    fJarImageMap.put(key, image);

    return image;
  }
 protected boolean setDocumentContent(IDocument document, IStorage storage) throws CoreException {
   try {
     InputStream contentStream = storage.getContents();
     try {
       String encoding =
           (storage instanceof IEncodedStorage
               ? ((IEncodedStorage) storage).getCharset()
               : GeneralUtils.getDefaultFileEncoding());
       setDocumentContent(document, contentStream, encoding);
     } finally {
       ContentUtils.close(contentStream);
     }
   } catch (IOException e) {
     throw new CoreException(GeneralUtils.makeExceptionStatus(e));
   }
   return true;
 }
  /**
   * Initialises the given document with the given stream using the given encoding.
   *
   * @param document the document to be initialised
   * @param storage the storage which delivers the document content
   * @param encoding the character encoding for reading the given stream
   * @param monitor a progress monitor for cancellation, or <code>null</code>
   * @exception CoreException if the given storage can not be accessed or read
   */
  private static void setDocumentContent(
      SymbolisedDocument document, IStorage storage, String encoding, IProgressMonitor monitor)
      throws CoreException {
    Reader in = null;
    InputStream contentStream = new UnicodeInputStream(storage.getContents());
    try {

      final int DEFAULT_FILE_SIZE = 15 * 1024;

      if (encoding == null)
        in = new BufferedReader(new InputStreamReader(contentStream), DEFAULT_FILE_SIZE);
      else
        in = new BufferedReader(new InputStreamReader(contentStream, encoding), DEFAULT_FILE_SIZE);
      StringBuffer buffer = new StringBuffer(DEFAULT_FILE_SIZE);
      char[] readBuffer = new char[2048];
      int n = in.read(readBuffer);
      while (n > 0) {
        if (monitor != null && monitor.isCanceled()) return;

        buffer.append(readBuffer, 0, n);
        n = in.read(readBuffer);
      }

      document.set(buffer.toString());

    } catch (IOException x) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              EditorsUI.PLUGIN_ID,
              IStatus.OK,
              "Failed to access or read underlying storage",
              x)); //$NON-NLS-1$
    } finally {
      try {
        if (in != null) in.close();
        else contentStream.close();
      } catch (IOException x) {
        // ignore
      }
    }
  }
Example #22
0
  /**
   * Loads the given <em>storage</em> as an EMF {@link Resource} in the given resource set..
   *
   * @param resourceURI URI of the resource contained in <em>storage</em>.
   * @param storage The {@link IStorage} from which to fetch the parent EMF Resource contents.
   * @param resourceSet Resource set in which to load the remote logical model.
   * @throws CoreException Thrown if we cannot load this storage as an EMF {@link Resource}.
   */
  private static void loadRemoteResource(URI resourceURI, IStorage storage, ResourceSet resourceSet)
      throws CoreException {
    Resource resource = resourceSet.createResource(resourceURI);

    InputStream remoteStream = null;
    try {
      remoteStream = storage.getContents();
      resource.load(remoteStream, Collections.emptyMap());
    } catch (IOException e) {
      // FIXME log
    } finally {
      if (remoteStream != null) {
        try {
          remoteStream.close();
        } catch (IOException e) {
          // FIXME log
        }
      }
    }
  }
  private void processContents() throws CoreException, UnsupportedEncodingException {
    Set<IFile> files = new HashSet<IFile>();
    files.addAll(contentsOrigin.keySet());
    files.addAll(contentsSource.keySet());
    files.addAll(contentsRemote.keySet());

    for (IFile file : files) {
      String originContent = contentsOrigin.get(file);
      String remoteContent = contentsRemote.get(file);
      String sourceContent = contentsSource.get(file);

      int remoteDiffKind = diffKind(originContent, remoteContent);
      int sourceDiffKind = diffKind(originContent, sourceContent);

      ThreeWayDiff threeWayDiff = mock(ThreeWayDiff.class);

      ITwoWayDiff remoteDiff = mock(ITwoWayDiff.class);
      ITwoWayDiff sourceDiff = mock(ITwoWayDiff.class);

      when(remoteDiff.getKind()).thenReturn(remoteDiffKind);
      when(sourceDiff.getKind()).thenReturn(sourceDiffKind);
      when(threeWayDiff.getLocalChange()).thenReturn(sourceDiff);
      when(threeWayDiff.getRemoteChange()).thenReturn(remoteDiff);

      when(subscriber.getDiff(file)).thenReturn(threeWayDiff);

      IStorageProvider originProvider = mock(IStorageProvider.class);
      IStorageProvider remoteProvider = mock(IStorageProvider.class);
      IStorageProvider sourceProvider = mock(IStorageProvider.class);

      IStorage originStorage = mock(IStorage.class);
      IStorage remoteStorage = mock(IStorage.class);
      IStorage sourceStorage = mock(IStorage.class);

      when(originProvider.getStorage(any(IProgressMonitor.class))).thenReturn(originStorage);
      when(remoteProvider.getStorage(any(IProgressMonitor.class))).thenReturn(remoteStorage);
      when(sourceProvider.getStorage(any(IProgressMonitor.class))).thenReturn(sourceStorage);

      when(originStorage.getContents()).then(openInputStream(originContent));
      when(remoteStorage.getContents()).then(openInputStream(remoteContent));
      when(sourceStorage.getContents()).then(openInputStream(sourceContent));

      when(accessor.getStorageProvider(file, DiffSide.ORIGIN)).thenReturn(originProvider);
      when(accessor.getStorageProvider(file, DiffSide.REMOTE)).thenReturn(remoteProvider);
      when(accessor.getStorageProvider(file, DiffSide.SOURCE)).thenReturn(sourceProvider);
    }
    when(subscriber.members(root)).thenReturn(files.toArray(new IFile[0]));
  }
 /** @since 2.5 */
 @Override
 public URI getUri(/* @NonNull */ IStorage storage) {
   if (storage instanceof IJarEntryResource) {
     final IJarEntryResource casted = (IJarEntryResource) storage;
     IPackageFragmentRoot packageFragmentRoot = casted.getPackageFragmentRoot();
     Map<URI, IStorage> data = getAllEntries(packageFragmentRoot);
     for (Map.Entry<URI, IStorage> entry : data.entrySet()) {
       if (entry.getValue().equals(casted)) return entry.getKey();
     }
     if (packageFragmentRoot.exists() && packageFragmentRoot.isArchive()) {
       IPath jarPath = packageFragmentRoot.getPath();
       URI jarURI;
       if (packageFragmentRoot.isExternal()) {
         jarURI = URI.createFileURI(jarPath.toOSString());
       } else {
         jarURI = URI.createPlatformResourceURI(jarPath.toString(), true);
       }
       URI result = URI.createURI("archive:" + jarURI + "!" + storage.getFullPath());
       return result;
     }
   }
   return null;
 }
 /** @see org.eclipse.ui.IEditorInput#getToolTipText() */
 public String getToolTipText() {
   return contents.getName();
 }
  /**
   * Method copyRemoteFileToLocalRepository.
   *
   * @param aLock ReentrantLock
   * @param aLocalRepository IRFSRegistry
   * @param aArtifact ScmArtifact
   * @param aMainMonitor IProgressMonitor
   * @param aSubMonitor IProgressMonitor
   * @return IFile
   * @throws CoreException
   * @throws ReviewsFileStorageException
   * @throws MainJobCancelledException
   * @throws SubJobCancelledException
   */
  public static R4EFileVersion copyRemoteFileToLocalRepository(
      ReentrantLock aLock,
      IRFSRegistry aLocalRepository,
      ScmArtifact aArtifact,
      IProgressMonitor aMainMonitor)
      throws ReviewsFileStorageException, CoreException {
    ReentrantLock lock = aLock;
    if (null == lock) {
      lock = new ReentrantLock();
    }

    // Check if Main Job or Sub Job was cancelled before fetching
    if (aMainMonitor.isCanceled()) {
      throw new CoreException(
          new Status(
              IStatus.CANCEL,
              R4EUIPlugin.PLUGIN_ID,
              IStatus.CANCEL,
              R4EUIConstants.CANCEL_EXCEPTION_MSG,
              null));
    }

    if ((null == aArtifact)
        || (null == aArtifact.getPath())
        || aArtifact.getPath().equals(INVALID_PATH)) {
      return null; // File not found in remote repository
    }

    // Tracing benchmarks
    Date fetchStart = null;
    if (Tracer.isInfo()) {
      fetchStart = new Date();
    }

    final IFileRevision fileRev = aArtifact.getFileRevision(null);
    if (null == fileRev) {
      return null;
    }

    // Pull file from the version control system
    InputStream iStream = null;
    final IStorage fileStore = fileRev.getStorage(null);
    if (null == fileStore) {
      return null;
    }
    try {
      iStream = fileStore.getContents();
    } catch (CoreException e) {
      R4EUIPlugin.Ftracer.traceInfo("Exception: " + e.toString() + " (" + e.getMessage() + ")");
      return null;
    }

    // Create and Set value in temporary File version
    final R4EFileVersion tmpFileVersion = RModelFactory.eINSTANCE.createR4EFileVersion();
    if ((null != tmpFileVersion) && (null != aLocalRepository)) {
      updateFileVersion(tmpFileVersion, aArtifact);

      // Check if Main Job or Sub Job was cancelled before pushing a local copy
      if (aMainMonitor.isCanceled()) {
        throw new CoreException(
            new Status(
                IStatus.CANCEL,
                R4EUIPlugin.PLUGIN_ID,
                IStatus.CANCEL,
                R4EUIConstants.CANCEL_EXCEPTION_MSG,
                null));
      }

      // Tracing benchmarks
      Date blobRegStart = null;
      if (fetchStart != null) {
        blobRegStart = new Date();
      }

      // Push a local copy to local review repository, and obtain the local id
      lock.lock();
      try {
        tmpFileVersion.setLocalVersionID(aLocalRepository.registerReviewBlob(iStream));
      } finally {
        lock.unlock();

        if (fetchStart != null) {
          long downloadTime = blobRegStart.getTime() - fetchStart.getTime();
          long uploadTime = (new Date()).getTime() - blobRegStart.getTime();
          R4EUIPlugin.Ftracer.traceInfo(
              "Registered blob for "
                  + fileRev.getName()
                  + " "
                  + //$NON-NLS-1$//$NON-NLS-2$
                  aArtifact.getId()
                  + ", fetch (ms): "
                  + downloadTime
                  + ", push (ms) "
                  + uploadTime); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (null != iStream) {
          try {
            iStream.close();
          } catch (IOException e) {
            R4EUIPlugin.Ftracer.traceWarning("Exception while closing stream, " + e.toString());
          }
        }
      }
    }
    return tmpFileVersion;
  }
 /** @see org.eclipse.ui.IEditorInput#getName() */
 public String getName() {
   return contents.getName();
 }
 private ISchedulingRule getSchedulingRule(IStorage storage) {
   if (storage instanceof ISchedulingRule) return (ISchedulingRule) storage;
   else if (storage != null) return (ISchedulingRule) storage.getAdapter(ISchedulingRule.class);
   return null;
 }
  @Override
  public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection)
      throws CoreException {
    TextSelection textSelection = (TextSelection) selection;
    int lineNumber = textSelection.getStartLine();
    IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints();

    if (part instanceof IEditorPart) {
      IEditorPart editor = (IEditorPart) part;
      IResource resource = (IResource) editor.getEditorInput().getAdapter(IResource.class);

      if (resource != null) {
        for (int i = 0; i < breakpoints.length; i++) {
          IBreakpoint breakpoint = breakpoints[i];
          if (resource.equals(breakpoint.getMarker().getResource())) {
            if (((ILineBreakpoint) breakpoint).getLineNumber() == (lineNumber + 1)) {
              breakpoint.delete();
              return;
            }
          }
        }
        String path = ClojureCore.getAsRootClasspathRelativePath((IFile) resource).substring(1);
        JDIDebugModel.createStratumBreakpoint(
            resource,
            "Clojure",
            resource.getName(),
            path,
            null,
            lineNumber + 1,
            -1,
            -1,
            0,
            true,
            null);
      } else {
        // Do it "the hard way" by using the WorkspaceRoot as the host for our breakpoint
        // ... quick analysis seems to indicate it's done this way by the JDT "itself" !
        IStorageEditorInput input = (IStorageEditorInput) editor.getEditorInput();
        IStorage storage = input.getStorage();

        for (int i = 0; i < breakpoints.length; i++) {
          IBreakpoint breakpoint = breakpoints[i];
          if (breakpoint instanceof IJavaStratumLineBreakpoint) {
            IJavaStratumLineBreakpoint stratumBreakpoint = (IJavaStratumLineBreakpoint) breakpoint;
            if (storage
                .getFullPath()
                .toPortableString()
                .equals(stratumBreakpoint.getSourcePath())) {
              if (((ILineBreakpoint) breakpoint).getLineNumber() == (lineNumber + 1)) {
                breakpoint.delete();
                return;
              }
            }
          }
        }
        Map attributes = new HashMap();
        StorageMarkerAnnotationModel.addAttribute(attributes, storage);
        System.out.println("not editor part resource");
        JDIDebugModel.createStratumBreakpoint(
            ResourcesPlugin.getWorkspace().getRoot(),
            "Clojure",
            storage.getName(),
            storage.getFullPath().toPortableString(),
            null,
            lineNumber + 1,
            -1,
            -1,
            0,
            true,
            attributes);
      }
    }
  }