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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #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: 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 #11
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 #12
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 #13
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 #14
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 #15
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 #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: SourceAttachmentPackageFragmentRootWalker.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public T traverse(IFolder folder, boolean stopOnFirstResult, TraversalState state) {
	T result = null;
	try {
		IPath path = new Path("");
		List<?> parents = state.getParents();
		for (int i = 1, count = parents.size(); i < count; ++i) {
			path = path.append(((IFolder) parents.get(i)).getName());
		}
		for (IResource resource : folder.members()) {
			switch (resource.getType()) {
				case IResource.FOLDER: {
					// If something in this folder might be in the bin includes, traverse it.
					//
					if (isBinInclude(path.append(resource.getName()).toString() + "/") != NO) {
						state.push(resource);
						result = traverse((IFolder) resource, stopOnFirstResult, state);
						state.pop();
					}
					break;
				}
				case IResource.FILE: {
					// If the file is definitely in the bin includes, handle it.
					//
					if (isBinInclude(path.append(resource.getName()).toString()) == YES) {
						result = handle((IFile) resource, state);
					}
					break;
				}
			}
			if (stopOnFirstResult && result != null) {
				break;
			}
		}
	} catch (CoreException e) {
		LOG.error(e.getMessage(), e);
	}
	return result;
}
 
Example #19
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);
}
 
Example #20
Source File: ClasspathChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static ClasspathChange removeEntryChange(IJavaProject project, IClasspathEntry entryToRemove) throws JavaModelException {
	IClasspathEntry[] rawClasspath= project.getRawClasspath();
	ArrayList<IClasspathEntry> newClasspath= new ArrayList<>();
	for (int i= 0; i < rawClasspath.length; i++) {
		IClasspathEntry curr= rawClasspath[i];
		if (curr.getEntryKind() != entryToRemove.getEntryKind() || !curr.getPath().equals(entryToRemove.getPath())) {
			newClasspath.add(curr);
		}
	}
	IClasspathEntry[] entries= newClasspath.toArray(new IClasspathEntry[newClasspath.size()]);
	IPath outputLocation= project.getOutputLocation();

	return newChange(project, entries, outputLocation);
}
 
Example #21
Source File: FileIndexLocation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean startsWith(IPath path) {
	try {
		return path.isPrefixOf(new Path(this.indexFile.getCanonicalPath()));
	} catch (IOException e) {
		return false;
	}
}
 
Example #22
Source File: InvisibleProjectImporterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void importCompleteFolder() throws Exception {
	IProject invisibleProject = copyAndImportFolder("singlefile/lesson1", "src/org/samples/HelloWorld.java");
	assertTrue(invisibleProject.exists());
	IPath sourcePath = invisibleProject.getFolder(new Path(ProjectUtils.WORKSPACE_LINK).append("src")).getFullPath();
	assertTrue(ProjectUtils.isOnSourcePath(sourcePath, JavaCore.create(invisibleProject)));
}
 
Example #23
Source File: CamelNewBeanWizard.java    From tesb-studio-se with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new NewProjectWizard.
 *
 * @param author Project author.
 * @param server
 * @param password
 */
public CamelNewBeanWizard(IPath path) {
    super();
    this.path = path;

    this.property = PropertiesFactory.eINSTANCE.createProperty();
    this.property
            .setAuthor(((RepositoryContext) CorePlugin.getContext().getProperty(Context.REPOSITORY_CONTEXT_KEY)).getUser());
    this.property.setVersion(VersionUtils.DEFAULT_VERSION);
    this.property.setStatusCode(""); //$NON-NLS-1$

    beanItem = CamelPropertiesFactory.eINSTANCE.createBeanItem();

    beanItem.setProperty(property);

    ILibrariesService service = CorePlugin.getDefault().getLibrariesService();
    URL url = service.getBeanTemplate();
    ByteArray byteArray = PropertiesFactory.eINSTANCE.createByteArray();
    InputStream stream = null;
    try {
        stream = url.openStream();
        byte[] innerContent = new byte[stream.available()];
        stream.read(innerContent);
        stream.close();
        byteArray.setInnerContent(innerContent);
    } catch (IOException e) {
        RuntimeExceptionHandler.process(e);
    }

    beanItem.setContent(byteArray);

    addDefaultModulesForBeans();
}
 
Example #24
Source File: IDEClassPathBlock.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private IDECPListElement[] openExternalClassFolderDialog(
		IDECPListElement existing )
{
	if ( existing == null )
	{
		IPath[] selected = BuildPathDialogAccess.chooseExternalClassFolderEntries( getShell( ) );
		if ( selected != null )
		{
			ArrayList res = new ArrayList( );
			for ( int i = 0; i < selected.length; i++ )
			{
				res.add( new IDECPListElement( IClasspathEntry.CPE_LIBRARY,
						selected[i],
						null ) );
			}
			return (IDECPListElement[]) res.toArray( new IDECPListElement[res.size( )] );
		}
	}
	else
	{
		IPath configured = BuildPathDialogAccess.configureExternalClassFolderEntries( getShell( ),
				existing.getPath( ) );
		if ( configured != null )
		{
			return new IDECPListElement[]{
				new IDECPListElement( IClasspathEntry.CPE_LIBRARY,
						configured,
						null )
			};
		}
	}
	return null;
}
 
Example #25
Source File: PackageExplorerView.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getFileContent(String... nodes) throws RemoteException, IOException, CoreException {
  IPath path = new Path(getPath(nodes));
  log.debug("checking existence of file '" + path + "'");
  final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);

  log.debug("Checking full path: '" + file.getFullPath().toOSString() + "'");
  return convertStreamToString(file.getContents());
}
 
Example #26
Source File: NewProjectNameAndLocationWizardPage.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the current project location path as entered by
 * the user, or its anticipated initial value.
 *
 * @return the project location path, its anticipated initial value, or <code>null</code>
 *   if no project location path is known
 */
@Override
public IPath getLocationPath() {
    if (useDefaults) {
        return initialLocationFieldValue;
    }

    return new Path(getProjectLocationFieldValue());
}
 
Example #27
Source File: SARLClasspathContainerTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
private static boolean isReferenceLibrary(String reference, IClasspathEntry entry) {
	IPath path = entry.getPath();
	String str = path.lastSegment();
	if ("classes".equals(str)) {
		str = path.segment(path.segmentCount() - 3);
		return str.equals(reference);
	}
	return str.startsWith(reference + "_");
}
 
Example #28
Source File: ClasspathEntry.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void resolvedChainedLibraries(IPath jarPath, HashSet visited, ArrayList result) {
	if (visited.contains( jarPath))
		return;
	visited.add(jarPath);
	JavaModelManager manager = JavaModelManager.getJavaModelManager();
	if (manager.isNonChainingJar(jarPath))
		return;
	List calledFileNames = getCalledFileNames(jarPath);
	if (calledFileNames == null) {
		manager.addNonChainingJar(jarPath);
	} else {
		Iterator calledFilesIterator = calledFileNames.iterator();
		IPath directoryPath = jarPath.removeLastSegments(1);
		while (calledFilesIterator.hasNext()) {
			String calledFileName = (String) calledFilesIterator.next();
			if (!directoryPath.isValidPath(calledFileName)) {
				if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
					Util.verbose("Invalid Class-Path entry " + calledFileName + " in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$
				}
			} else {
				IPath calledJar = directoryPath.append(new Path(calledFileName));
				// Ignore if segment count is Zero (https://bugs.eclipse.org/bugs/show_bug.cgi?id=308150)
				if (calledJar.segmentCount() == 0) {
					if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
						Util.verbose("Invalid Class-Path entry " + calledFileName + " in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$
					}
					continue;
				}
				resolvedChainedLibraries(calledJar, visited, result);
				result.add(calledJar);
			}
		}
	}
}
 
Example #29
Source File: GdtPreferences.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Attempts to register the SDK from a bundle.
 */
private static void registerBundleSdk(Bundle bundle) throws CoreException {
  try {
    IPath propPath = new Path(SDK_REGISTRANT_PROPERTY_FILE);
    URL propUrl = FileLocator.find(bundle, propPath, (Map<String, String>) null);
    if (propUrl != null) {
      InputStream instream = propUrl.openStream();
      Properties props = new Properties();
      props.load(instream);
      String sdkType = props.getProperty(SDK_BUNDLE_MARKER_PROPERTY);
      String sdkPrefix = props.getProperty(SDK_PATH_PREFIX_PROPERTY);
      if (sdkType != null && sdkPrefix != null) {
        IPath sdkPrefixPath = new Path(sdkPrefix);
        URL sdkPathUrl = FileLocator.find(bundle, sdkPrefixPath, (Map<String, String>) null);
        if (sdkPathUrl == null) {
          // Automatic SDK registration failed. This is expected in dev mode.
          CorePluginLog.logWarning("Failed to register SDK: " + sdkPrefix);
          return;
        }
        // resolve needed to switch from bundleentry to file url
        sdkPathUrl = FileLocator.resolve(sdkPathUrl);
        if (sdkPathUrl != null) {
          if ("file".equals(sdkPathUrl.getProtocol())) {
            GWTSdkRegistrant.registerSdk(sdkPathUrl, sdkType);
          }
        }
      }
    }
  } catch (IOException e) {
    throw new CoreException(new Status(IStatus.WARNING, GdtPlugin.PLUGIN_ID, e.getLocalizedMessage(), e));
  }
}
 
Example #30
Source File: PyStructureConfigHelpers.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new project resource with the entered name.
 * 
 * @param projectName The name of the project
 * @param projectLocationPath the location for the project. If null, the default location (in the workspace)
 * will be used to create the project.
 * @param references The projects that should be referenced from the newly created project
 * 
 * @return the created project resource, or <code>null</code> if the project was not created
 * @throws CoreException 
 * @throws OperationCanceledException 
 */
public static IProject createPydevProject(String projectName, IPath projectLocationPath, IProject[] references,

        IProgressMonitor monitor, String projectType, String projectInterpreter,
        ICallback<List<IContainer>, IProject> getSourceFolderHandlesCallback,
        ICallback<List<String>, IProject> getExternalSourceFolderHandlesCallback,
        ICallback<List<IPath>, IProject> getExistingSourceFolderHandlesCallback,
        ICallback<Map<String, String>, IProject> getVariableSubstitutionCallback)
        throws OperationCanceledException, CoreException {

    // get a project handle
    final IProject projectHandle = getProjectHandle(projectName);

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final IProjectDescription description = workspace.newProjectDescription(projectHandle.getName());
    description.setLocation(projectLocationPath);

    // update the referenced project if provided
    if (references != null && references.length > 0) {
        description.setReferencedProjects(references);
    }

    createPydevProject(description, projectHandle, monitor, projectType, projectInterpreter,
            getSourceFolderHandlesCallback, getExternalSourceFolderHandlesCallback,
            getExistingSourceFolderHandlesCallback, getVariableSubstitutionCallback);
    return projectHandle;
}