org.eclipse.core.runtime.IPath Java Examples

The following examples show how to use org.eclipse.core.runtime.IPath. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GWTMavenRuntime.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Maven-based GWT SDKs do not have a clear installation path. So, we say that the installation path corresponds to:
 * <code><repository path>/<group path></code>.
 */
@Override
public IPath getInstallationPath() {

  try {
    IClasspathEntry classpathEntry = findGwtUserClasspathEntry();
    if (classpathEntry == null) {
      return null;
    }

    IPath p = classpathEntry.getPath();
    if (p.segmentCount() < 4) {
      return null;
    }
    return p.removeLastSegments(3);
  } catch (JavaModelException e) {
    Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
        "Unable to determine installation path for the maven-based GWT runtime.", e));
  }

  return null;
}
 
Example #2
Source File: JavadocConfigurationBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String chooseArchive() {
	if (fWorkspaceRadio.isSelected()) {
		return chooseWorkspaceArchive();
	}

	IPath currPath= new Path(fArchiveField.getText());
	if (ArchiveFileFilter.isArchivePath(currPath, true)) {
		currPath= currPath.removeLastSegments(1);
	}

	FileDialog dialog= new FileDialog(fShell, SWT.OPEN);
	dialog.setFilterExtensions(ArchiveFileFilter.JAR_ZIP_FILTER_EXTENSIONS);
	dialog.setText(PreferencesMessages.JavadocConfigurationBlock_zipImportSource_title);
	dialog.setFilterPath(currPath.toOSString());

	return dialog.open();
}
 
Example #3
Source File: BundleCacher.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
private void forcePathsOfChildren(List<MenuElement> children)
{
	if (children != null)
	{
		for (MenuElement child : children)
		{
			String childPath = child.getPath();
			IPath pathObj = Path.fromOSString(childPath);
			if (!pathObj.isAbsolute())
			{
				// Prepend the bundle directory.
				child.setPath(bundleDirectory.getAbsolutePath() + File.separator + childPath);
			}
			forcePathsOfChildren(child.getChildren());
		}
	}
}
 
Example #4
Source File: HandleFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the package fragment root that contains the given resource path.
 */
private PackageFragmentRoot getPkgFragmentRoot(String pathString) {

	IPath path= new Path(pathString);
	IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
	for (int i= 0, max= projects.length; i < max; i++) {
		try {
			IProject project = projects[i];
			if (!project.isAccessible()
				|| !project.hasNature(JavaCore.NATURE_ID)) continue;
			IJavaProject javaProject= this.javaModel.getJavaProject(project);
			IPackageFragmentRoot[] roots= javaProject.getPackageFragmentRoots();
			for (int j= 0, rootCount= roots.length; j < rootCount; j++) {
				PackageFragmentRoot root= (PackageFragmentRoot)roots[j];
				if (root.internalPath().isPrefixOf(path) && !Util.isExcluded(path, root.fullInclusionPatternChars(), root.fullExclusionPatternChars(), false)) {
					return root;
				}
			}
		} catch (CoreException e) {
			// CoreException from hasNature - should not happen since we check that the project is accessible
			// JavaModelException from getPackageFragmentRoots - a problem occured while accessing project: nothing we can do, ignore
		}
	}
	return null;
}
 
Example #5
Source File: SyntaxServerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDidOpen() throws Exception {
	URI fileURI = openFile("maven/salut4", "src/main/java/java/Foo.java");
	Job.getJobManager().join(SyntaxDocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(fileURI);
	assertNotNull(cu);
	IPath rootPath = getWorkingTestPath("maven/salut4");
	String projectName = ProjectUtils.getWorkspaceInvisibleProjectName(rootPath);
	assertEquals(projectName, cu.getJavaProject().getProject().getName());

	IPath[] sourcePaths = ProjectUtils.listSourcePaths(cu.getJavaProject());
	assertEquals(2, sourcePaths.length);
	IPath basePath = ProjectUtils.getProject(projectName).getFolder(ProjectUtils.WORKSPACE_LINK).getFullPath();
	assertTrue(Objects.equals(basePath.append("src/main/java"), sourcePaths[0]));
	assertTrue(Objects.equals(basePath.append("src/test/java"), sourcePaths[1]));
}
 
Example #6
Source File: JsonReferenceProposalProvider.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns collection of JSON reference proposals.
 * 
 * If the scope is local, it will only return JSON references from within the current document.
 * 
 * If the scope is project, it will return all JSON references from within the current document and from all
 * documents inside the same project.
 * 
 * If the scope is workspace, it will return all JSON references from within the current document and from all
 * documents inside the same workspace.
 * 
 * @param pointer
 * @param document
 * @param scope
 * @return proposals
 */
public Collection<ProposalDescriptor> getProposals(JsonPointer pointer, JsonDocument document, Scope scope) {
    final ContextType type = contextTypes.get(document.getModel(), pointer);
    final IFile currentFile = getActiveFile();
    final IPath basePath = currentFile.getParent().getFullPath();
    final List<ProposalDescriptor> proposals = new ArrayList<>();
    
    if (scope == Scope.LOCAL) {
        proposals.addAll(type.collectProposals(document, null));
    } else if (!type.isLocalOnly()) {
        final SwaggerFileFinder fileFinder = new SwaggerFileFinder(fileContentType);

        for (IFile file : fileFinder.collectFiles(scope, currentFile)) {
            IPath relative = file.equals(currentFile) ? null : file.getFullPath().makeRelativeTo(basePath);
            if (file.equals(currentFile)) {
                proposals.addAll(type.collectProposals(document, relative));
            } else {
                proposals.addAll(type.collectProposals(manager.getDocument(file.getLocationURI()), relative));
            }
        }
    }

    return proposals;
}
 
Example #7
Source File: SiteConfigurationServlet.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected synchronized void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	traceRequest(req);
	String userName = req.getRemoteUser();
	if (userName == null) {
		handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request: authenticated user is null", null));
		return;
	}
	IPath pathInfo = getPathInfo(req);
	if (pathInfo.segmentCount() == 1) {
		SiteInfo site = getExistingSiteConfig(req, resp, userName);
		if (siteConfigurationResourceHandler.handleRequest(req, resp, site)) {
			return;
		}
	} else {
		handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request", null));
		return;
	}
	super.doPut(req, resp);
}
 
Example #8
Source File: FileNamePatternSearchScope.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static void addToList(ArrayList<IResource> res, IResource curr, boolean includeDerived) {
	if (!includeDerived && curr.isDerived(IResource.CHECK_ANCESTORS)) {
		return;
	}
	IPath currPath= curr.getFullPath();
	for (int k= res.size() - 1; k >= 0 ; k--) {
		IResource other= res.get(k);
		IPath otherPath= other.getFullPath();
		if (otherPath.isPrefixOf(currPath)) {
			return;
		}
		if (currPath.isPrefixOf(otherPath)) {
			res.remove(k);
		}
	}
	res.add(curr);
}
 
Example #9
Source File: TypeScriptCompilerLaunchConfigurationDelegate.java    From typescript.java with MIT License 6 votes vote down vote up
/**
 * Expands and returns the working directory attribute of the given launch
 * configuration. Returns <code>null</code> if a working directory is not
 * specified. If specified, the working is verified to point to an existing
 * tsconfig.json file in the local file system.
 * 
 * @param configuration
 *            launch configuration
 * @return an absolute path to a directory in the local file system, or
 *         <code>null</code> if unspecified
 * @throws CoreException
 *             if unable to retrieve the associated launch configuration
 *             attribute, if unable to resolve any variables, or if the
 *             resolved location does not point to an existing tsconfig.json
 *             file in the local file system.
 */
private static IPath getBuildPath(ILaunchConfiguration configuration) throws CoreException {
	String location = configuration.getAttribute(TypeScriptCompilerLaunchConstants.BUILD_PATH, (String) null);
	if (location != null) {
		String expandedLocation = getStringVariableManager().performStringSubstitution(location);
		if (expandedLocation.length() > 0) {
			File path = new File(expandedLocation);
			if (path.isFile()) {
				return new Path(expandedLocation);
			}
			String msg = NLS.bind(
					TypeScriptCoreMessages.TypeScriptCompilerLaunchConfigurationDelegate_invalidBuildPath,
					new Object[] { expandedLocation, configuration.getName() });
			abort(msg, null, 0);
		}
	}
	return null;
}
 
Example #10
Source File: Activator.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Return a path to a file relative to this plugin's base directory
 *
 * @param relativePath
 *            The path relative to the plugin's root directory
 * @return The path corresponding to the relative path in parameter
 */
public static IPath getAbsoluteFilePath(String relativePath) {
    Activator plugin = Activator.getDefault();
    if (plugin == null) {
        /*
         * Shouldn't happen but at least throw something to get the test to
         * fail early
         */
        throw new IllegalStateException();
    }
    URL location = FileLocator.find(plugin.getBundle(), new Path(relativePath), null);
    try {
        return new Path(FileLocator.toFileURL(location).getPath());
    } catch (IOException e) {
        throw new IllegalStateException();
    }
}
 
Example #11
Source File: Activator.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Return a path to a file relative to this plugin's base directory
 *
 * @param relativePath
 *            The path relative to the plugin's root directory
 * @return The path corresponding to the relative path in parameter
 */
public static IPath getAbsoluteFilePath(String relativePath) {
    Activator plugin = Activator.getDefault();
    if (plugin == null) {
        /*
         * Shouldn't happen but at least throw something to get the test to
         * fail early
         */
        throw new IllegalStateException();
    }
    URL location = FileLocator.find(plugin.getBundle(), new Path(relativePath), null);
    try {
        return new Path(FileLocator.toFileURL(location).getPath());
    } catch (IOException e) {
        throw new IllegalStateException();
    }
}
 
Example #12
Source File: ProjectFolderSelectionGroup.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the currently entered container name. Null if the field is empty. Note that the container may not exist yet if the user
 * entered a new container name in the field.
 */
public IPath getContainerFullPath() {
    if (allowNewContainerName) {
        String pathName = containerNameField.getText();
        if (pathName == null || pathName.length() < 1)
            return null;
        else
            //The user may not have made this absolute so do it for them
            return (new Path(pathName)).makeAbsolute();
    } else {
        if (selectedContainer == null)
            return null;
        else
            return selectedContainer.getFullPath();
    }
}
 
Example #13
Source File: ConfigManager.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
public void setConfig(IDominoDesignerProject project, BluemixConfig config, boolean replaceManifest, LinkedHashMap<String, String> extraEnv) {
    // Write the NSF -> deploy dir config file
    _mapProps.setProperty(getProjectKey(project), config.directory);
    BluemixUtil.writeProperties(_mapProps, _mapPath);

    // Write the Bluemix properties file
    Properties bmProps = new Properties();
    bmProps.setProperty(_ORG, config.org);
    bmProps.setProperty(_SPACE, config.space);
    if (StringUtil.isNotEmpty(config.copyMethod)) {
        bmProps.setProperty(_COPY_METHOD, config.copyMethod);
    }
    if (StringUtil.isNotEmpty(config.uri)) {
        bmProps.setProperty(_URI, config.uri);
    }
    
    IPath path = new Path(config.directory).addTrailingSeparator().append(_BLUEMIX_FILE);
    BluemixUtil.writeProperties(bmProps, path);
    
    // Write the default manifest to the deploy dir
    if (replaceManifest) {
        ManifestUtil.writeDefaultManifest(config, project.getDatabaseName(), extraEnv);
    }
}
 
Example #14
Source File: JarFileExportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void exportExternalClassFolderElement(IJavaElement javaElement, IPath classFolderPath, IProgressMonitor progressMonitor) throws JavaModelException, InterruptedException {
	if (javaElement instanceof IClassFile) {
		IClassFile classFile= (IClassFile) javaElement;
		IPath path= classFile.getPath();

		IPath destination= path.removeFirstSegments(classFolderPath.segmentCount()).setDevice(null);

		try {
			((IJarBuilderExtension) fJarBuilder).writeFile(path.toFile(), destination);
		} catch (CoreException e) {
			handleCoreExceptionOnExport(e);
		} finally {
			progressMonitor.worked(1);
			ModalContext.checkCanceled(progressMonitor);
		}
	} else if (javaElement instanceof IPackageFragment) {
		IJavaElement[] children= ((IPackageFragment) javaElement).getChildren();
		for (int i= 0; i < children.length; i++) {
			exportExternalClassFolderElement(children[i], classFolderPath, progressMonitor);
		}
	}
}
 
Example #15
Source File: BuildPathCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static IProject findBelongedProject(IPath sourceFolder) {
	List<IProject> projects = Stream.of(ProjectUtils.getAllProjects()).filter(ProjectUtils::isJavaProject).sorted(new Comparator<IProject>() {
		@Override
		public int compare(IProject p1, IProject p2) {
			return p2.getLocation().toOSString().length() - p1.getLocation().toOSString().length();
		}
	}).collect(Collectors.toList());

	for (IProject project : projects) {
		if (project.getLocation().isPrefixOf(sourceFolder)) {
			return project;
		}
	}

	return null;
}
 
Example #16
Source File: ItemEditor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs ()
{
    SaveAsDialog saveAsDialog = new SaveAsDialog ( getSite ().getShell () );
    saveAsDialog.open ();
    IPath path = saveAsDialog.getResult ();
    if ( path != null )
    {
        IFile file = ResourcesPlugin.getWorkspace ().getRoot ().getFile ( path );
        if ( file != null )
        {
            doSaveAs ( URI.createPlatformResourceURI ( file.getFullPath ().toString (), true ), new FileEditorInput ( file ) );
        }
    }
}
 
Example #17
Source File: LibraryClasspathContainerResolverService.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
private IClasspathEntry resolveLibraryFileAttachSourceSync(LibraryFile libraryFile)
    throws CoreException {

  Artifact artifact = repositoryService.resolveArtifact(libraryFile, new NullProgressMonitor());
  IPath libraryPath = new Path(artifact.getFile().getAbsolutePath());

  // Not all artifacts have sources; need to work if no source artifact is available
  // e.g. appengine-api-sdk doesn't
  IPath sourceAttachmentPath = repositoryService.resolveSourceArtifact(
      libraryFile, artifact.getVersion(), new NullProgressMonitor());

  IClasspathEntry newLibraryEntry =
      JavaCore.newLibraryEntry(
          libraryPath,
          sourceAttachmentPath,
          null /*  sourceAttachmentRootPath */,
          getAccessRules(libraryFile.getFilters()),
          getClasspathAttributes(libraryFile, artifact),
          true /* isExported */);
  return newLibraryEntry;
}
 
Example #18
Source File: SelectTraceExecutableHandler.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    Shell shell = HandlerUtil.getActiveShell(event);

    // Get the selection before opening the dialog because otherwise the
    // getCurrentSelection() call will always return null
    ISelection selection = HandlerUtil.getCurrentSelection(event);

    SelectTraceExecutableDialog dialog = new SelectTraceExecutableDialog(shell);
    dialog.open();
    if (dialog.getReturnCode() != Window.OK) {
        return null;
    }
    IPath tracedExecutable = dialog.getExecutablePath();

    if (selection instanceof IStructuredSelection) {
        for (Object o : ((IStructuredSelection) selection).toList()) {
            TmfTraceElement traceElement = (TmfTraceElement) o;
            IResource resource = traceElement.getResource();
            try {
                resource.setPersistentProperty(GdbTrace.EXEC_KEY, tracedExecutable.toString());
            } catch (CoreException e) {
                TraceUtils.displayErrorMsg(e);
            }
        }
    }
    return null;
}
 
Example #19
Source File: ProjectFileTracking.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Generates a map of output files in the given folder, along with their
 * file extensions. The latter can be used for renaming the output files
 * later. Output files can be the main output file, a partial build output,
 * or a file with the same name, but different file extension as the source
 * file. This different extension has to be any of the ones passed in
 * <code>derivedExts</code>.
 *
 * @param aSourceContainer source container to scan for output files
 * @param sourceBaseName name without extension of the current source file
 * @param derivedExts derived file extensions
 * @param format current output format
 * @param monitor progress monitor
 * @return a map with output files (keys) and extensions (values)
 * @throws CoreException if an error occurs
 */
public static Map<IPath, String> getOutputNames(IContainer aSourceContainer,
        String sourceBaseName, String[] derivedExts, String format,
        IProgressMonitor monitor) throws CoreException {
    final Map<IPath, String> outputNames = new HashMap<IPath, String>();
    final String dotFormat = '.' + format;
    final String currentOutput = sourceBaseName + dotFormat;

    for (IResource res : aSourceContainer.members()) {
        // Disregard subfolders
        if (res instanceof IFile) {
            String name = res.getName();
            if (name.equals(currentOutput)) {
                outputNames.put(res.getProjectRelativePath(), dotFormat);
            }
            else {
                String ext = getMatchingExt(name, derivedExts);
                if (ext != null
                        && OutputFileManager.stripFileExt(name, ext).equals(sourceBaseName)) {
                    outputNames.put(res.getProjectRelativePath(), ext);
                }
            }
        }
        monitor.worked(1);
    }
    return outputNames;
}
 
Example #20
Source File: DownloadManager.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Download the remote content.
 * 
 * @param monitor
 */
protected IStatus download(IProgressMonitor monitor)
{
	SubMonitor subMonitor = SubMonitor.convert(monitor, Messages.DownloadManager_downloadingContent,
			downloads.size());
	MultiStatus multi = new MultiStatus(CoreIOPlugin.PLUGIN_ID, IStatus.OK, null, null);
	completedDownloadsPaths = new ArrayList<IPath>(downloads.size());
	for (Iterator<ContentDownloadRequest> iterator = downloads.iterator(); iterator.hasNext();)
	{
		if (subMonitor.isCanceled())
		{
			// TODO Append to multi status and return that?
			return Status.CANCEL_STATUS;
		}

		ContentDownloadRequest request = iterator.next();
		request.execute(subMonitor.newChild(1));
		IStatus result = request.getResult();
		if (result != null)
		{
			if (result.isOK())
			{
				completedDownloadsPaths.add(request.getDownloadLocation());
				iterator.remove();
			}
			multi.add(result);
		}
		subMonitor.setWorkRemaining(downloads.size());
	}

	return multi;
}
 
Example #21
Source File: GWTRefactoringSupportTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private Set<IIndexedJavaRef> createRefSet(String[] rawRefs, IPath source) {
  Set<IIndexedJavaRef> refs = new HashSet<IIndexedJavaRef>();

  for (String rawRef : rawRefs) {
    JsniJavaRef ref = JsniJavaRef.parse(rawRef);
    ref.setSource(source);
    IndexedJsniJavaRef indexedRef = new IndexedJsniJavaRef(ref);
    refs.add(indexedRef);
  }

  return refs;
}
 
Example #22
Source File: GTestHelper.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
private void copyFilesFromBundleToFolder() {
	IPath targetPath = getTargetPath();
	List<String> testDataFiles = getFilesToCopy();
	getTestDataFiles(testDataFiles);
	for (String file : testDataFiles) {
		copier.copyFileFromBundleToFolder(getTestBundle(), file, targetPath);
	}
}
 
Example #23
Source File: XMLAnalysesManagerPreferencePage.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Fill the table with the imported files.
 */
private void fillAnalysesTable() {
    fAnalysesTable.removeAll();
    Map<String, File> files = XmlUtils.listFiles();
    for (String file : files.keySet()) {
        // Remove the extension from the file path to display.
        IPath path = new Path(file);

        // Create item and add to table
        TableItem item = new TableItem(fAnalysesTable, SWT.NONE);
        item.setText(path.removeFileExtension().toString());
        item.setChecked(XmlUtils.isAnalysisEnabled(path.toString()));
    }
    setButtonsEnabled(false);
}
 
Example #24
Source File: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the location URI of the classpath entry
 *
 * @param entry
 *            the classpath entry
 * @return the location URI
 */
public static URI getLocationURI(final IClasspathEntry entry) {
	IPath path= null;
	if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE)
		path= JavaCore.getResolvedVariablePath(entry.getPath());
	else
		path= entry.getPath();
	final IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
	URI location= null;
	if (root.exists(path)) {
		location= root.getFile(path).getRawLocationURI();
	} else
		location= URIUtil.toURI(path);
	return location;
}
 
Example #25
Source File: RenamePackageChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IPath createNewPath() {
	IPackageFragment oldPackage= getPackage();
	IPath oldPackageName= createPath(oldPackage.getElementName());
	IPath newPackageName= createPath(getNewName());
	return getResourcePath().removeLastSegments(oldPackageName.segmentCount()).append(newPackageName);
}
 
Example #26
Source File: CloudSdkStagingHelperTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testStageFlexible() throws CoreException, AppEngineException {
  createFile("src/main/appengine/app.yaml", APP_YAML);

  IFolder appEngineDirectory = project.getFolder("src/main/appengine");
  IPath deployArtifact = createFile("my-app.war", "fake WAR").getLocation();

  CloudSdkStagingHelper.stageFlexible(
      appEngineDirectory.getLocation(), deployArtifact, stagingDirectory, monitor);

  assertTrue(stagingDirectory.append("app.yaml").toFile().exists());
  assertTrue(stagingDirectory.append("my-app.war").toFile().exists());
}
 
Example #27
Source File: ConverterUtil.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 得到本地文件系统路径
 * @param workspacePath
 * @return ;
 */
public static String toLocalPath(String workspacePath) {
	if (isWorkspacePath(workspacePath)) {
		IPath path = Platform.getLocation();
		return path.append(workspacePath).toOSString();
	} else {
		return workspacePath;
	}
}
 
Example #28
Source File: LibraryClasspathContainerInitializerTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitialize_ifSourcePathIsValidContainerIsNotResolvedAgain()
    throws CoreException, IOException {
  File artifactFile = temporaryFolder.newFile();
  File sourceArtifactFile = temporaryFolder.newFile();

  IClasspathEntry entry = JavaCore.newLibraryEntry(new Path(artifactFile.getAbsolutePath()),
                                                   new Path(sourceArtifactFile.getAbsolutePath()),
                                                   null);
  IClasspathEntry[] entries = new IClasspathEntry[]{ entry };
  LibraryClasspathContainer container = mock(LibraryClasspathContainer.class);
  when(container.getClasspathEntries()).thenReturn(entries);
  when(serializer.loadContainer(any(IJavaProject.class), any(IPath.class))).thenReturn(container);

  LibraryClasspathContainerInitializer containerInitializer =
      new LibraryClasspathContainerInitializer(TEST_CONTAINER_PATH, serializer, resolverService);
  containerInitializer.initialize(new Path(TEST_LIBRARY_PATH), testProject.getJavaProject());
  testProject.getJavaProject().getRawClasspath();
  IClasspathEntry[] resolvedClasspath = testProject.getJavaProject().getResolvedClasspath(false);

  for (IClasspathEntry resolvedEntry : resolvedClasspath) {
    if (resolvedEntry.getPath().toOSString().equals(artifactFile.getAbsolutePath())) {
      assertThat(resolvedEntry.getSourceAttachmentPath().toOSString(),
          is(sourceArtifactFile.getAbsolutePath()));
      verifyResolveServiceResolveContainerNotCalled();
      return;
    }
  }
  fail("classpath entry not found");
}
 
Example #29
Source File: ClasspathEntry.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public char[][] fullInclusionPatternChars() {

		if (this.fullInclusionPatternChars == UNINIT_PATTERNS) {
			int length = this.inclusionPatterns.length;
			this.fullInclusionPatternChars = new char[length][];
			IPath prefixPath = this.path.removeTrailingSeparator();
			for (int i = 0; i < length; i++) {
				this.fullInclusionPatternChars[i] =
					prefixPath.append(this.inclusionPatterns[i]).toString().toCharArray();
			}
		}
		return this.fullInclusionPatternChars;
	}
 
Example #30
Source File: XmlUtilsTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test the {@link XmlUtils#getXmlFilesPath()} method
 */
@Test
public void testXmlPath() {
    IPath xmlPath = XmlUtils.getXmlFilesPath();

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IPath workspacePath = workspace.getRoot().getRawLocation();
    workspacePath = workspacePath.addTrailingSeparator()
            .append(".metadata").addTrailingSeparator().append(".plugins")
            .addTrailingSeparator()
            .append("org.eclipse.tracecompass.tmf.analysis.xml.core")
            .addTrailingSeparator().append("xml_files");

    assertEquals(xmlPath, workspacePath);
}