Java Code Examples for org.eclipse.core.resources.IResource#getProject()

The following examples show how to use org.eclipse.core.resources.IResource#getProject() . 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: SelectionRetrieverFactory.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a {@link SelectionRetriever} capable of retrieving selections of a specific type.
 *
 * <p>Generally the returned {@link SelectionRetriever} is straight forward. If smart is set to
 * true an "intelligent" {@link SelectionRetriever} is returned.
 *
 * <p>In case of {@link IProject}.class the smart {@link SelectionRetriever} does not only return
 * directly selected projects but also the projects, selected resources (like source folder and
 * files) belong to.
 *
 * @param <T> type of the returned list
 * @param adapter type the selections should be adapted to
 * @param smart if true, returns an "intelligent" {@link SelectionRetriever}
 * @return
 */
public static <T> ISelectionRetriever<T> getSelectionRetriever(
    Class<? extends T> adapter, boolean smart) {

  if (smart && adapter.equals(IProject.class)) {
    /*
     * If looking for projects we also want to find them in case a
     * project's resource was selected.
     */
    return new AbstractSelectionConvertingRetriever<IResource, T>(IResource.class) {

      @SuppressWarnings("unchecked")
      @Override
      protected T convert(IResource resource) {
        return (T) resource.getProject();
      }
    };
  } else {
    /*
     * Default selection retriever
     */
    return new SelectionRetriever<T>(adapter);
  }
}
 
Example 2
Source File: BuildpathIndicatorLabelDecorator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ImageDescriptor getOverlay(Object element) {
	if (element instanceof IResource) {
		IResource resource= (IResource) element;
		IProject project= resource.getProject();
		if (project != null) {
			IJavaProject javaProject= JavaCore.create(project);
			if (javaProject != null) {
				if (javaProject.isOnClasspath(resource)) {
					IJavaElement javaElement= JavaCore.create(resource, javaProject);
					try {
						if (javaElement instanceof IPackageFragmentRoot
								&& ((IPackageFragmentRoot)javaElement).getKind() != IPackageFragmentRoot.K_SOURCE) {
							return JavaPluginImages.DESC_OVR_LIBRARY;
						}
					} catch (JavaModelException e) {
						return null;
					}
				}
			}
		}
	}
	return null;
}
 
Example 3
Source File: GoLaunchShortcut.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
protected ILaunchable getLaunchableForGoPackage(IResource goPackageResource) throws CommonException {
	IProject project = goPackageResource.getProject();
	if(project == null) {
		return null;
	}
	GoEnvironment goEnv = GoProjectEnvironment.getGoEnvironment(project);
	Location goPackageLocation = ResourceUtils.getResourceLocation(goPackageResource);
	GoPackageName goPackageName = goEnv.findGoPackageForLocation(goPackageLocation);
	if(goPackageName == null) {
		throw CommonException.fromMsgFormat("{0}", "Resource doesn't have a corresponding Go package.");
	}
	
	BuildTargetLaunchCreator btLaunchCreator = new BuildTargetLaunchCreator().initFromProject(project);
	btLaunchCreator.data.targetName = buildManager.getBuildTargetName2(
		goPackageName.asString(), GoBuildManager.BUILD_TYPE_Build);
	
	return new BuildTargetLaunchable(project, btLaunchCreator);
}
 
Example 4
Source File: PythonPathHelper.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
private static OrderedMap<String, String> getResourcePythonPathMap(
        Map<IProject, OrderedMap<String, String>> projectSourcePathMapsCache, IResource resource) {
    IProject project = resource.getProject();
    OrderedMap<String, String> sourceMap = projectSourcePathMapsCache.get(project);
    if (sourceMap == null) {
        IPythonPathNature pythonPathNature = PythonNature.getPythonPathNature(project);
        // Ignore resources that come from a non-Python project.
        if (pythonPathNature == null) {
            sourceMap = new OrderedMap<String, String>();
        } else {
            try {
                sourceMap = pythonPathNature
                        .getProjectSourcePathResolvedToUnresolvedMap();
            } catch (CoreException e) {
                sourceMap = new OrderedMap<String, String>();
                Log.log(e);
            }
        }
        projectSourcePathMapsCache.put(project, sourceMap);
    }
    return sourceMap;
}
 
Example 5
Source File: CrySLProjectTransformer.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void partOpened(IWorkbenchPartReference partRef) {

	if (Constants.cryslEditorID.equals(partRef.getId())) {
		IResource file = partRef.getPage().getActiveEditor().getEditorInput().getAdapter(IResource.class);
		if (Constants.cryslFileEnding.substring(1).equals(file.getFileExtension())) {
			IProject projectOfOpenedFile = file.getProject();
			try {
				if (!CrySLBuilderUtils.hasCrySLBuilder(projectOfOpenedFile)) {
					CrySLBuilderUtils.addCrySLBuilderToProject(projectOfOpenedFile);
				}
			}
			catch (CoreException e) {
				Activator.getDefault().logError(e);
			}
		}
	}
}
 
Example 6
Source File: LibraryFilter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
	if (element instanceof IPackageFragmentRoot) {
		IPackageFragmentRoot root= (IPackageFragmentRoot)element;
		if (root.isArchive()) {
			// don't filter out JARs contained in the project itself
			IResource resource= root.getResource();
			if (resource != null) {
				IProject jarProject= resource.getProject();
				IProject container= root.getJavaProject().getProject();
				return container.equals(jarProject);
			}
			return false;
		}
	} else if (element instanceof ClassPathContainer.RequiredProjectWrapper) {
		return false;
	}
	return true;
}
 
Example 7
Source File: CpplintCheckSettings.java    From CppStyle with MIT License 6 votes vote down vote up
private static boolean enableCpplint(IResource resource) {
	boolean enable = CppStyle.getDefault().getPreferenceStore()
			.getBoolean(CppStyleConstants.ENABLE_CPPLINT_ON_SAVE);

	try {
		IProject project = resource.getProject();
		String enableProjectSpecific = project
				.getPersistentProperty(new QualifiedName("", CppStyleConstants.PROJECTS_PECIFIC_PROPERTY));

		if (enableProjectSpecific != null && Boolean.parseBoolean(enableProjectSpecific)) {
			String value = project
					.getPersistentProperty(new QualifiedName("", CppStyleConstants.ENABLE_CPPLINT_PROPERTY));
			if (value != null) {
				return Boolean.parseBoolean(value);
			}

			return false;
		}
	} catch (CoreException e) {
		e.printStackTrace();
	}

	return enable;
}
 
Example 8
Source File: TexSpellingEngine.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the project that belongs to the given document.
 * Thanks to Nitin Dahyabhai for the tip.
 * 
 * @param document
 * @return the project or <code>null</code> if no project was found
 */
private static IProject getProject(IDocument document) {
    ITextFileBufferManager fileBufferMgr = FileBuffers.getTextFileBufferManager();
    ITextFileBuffer fileBuffer = fileBufferMgr.getTextFileBuffer(document);
    
    if (fileBuffer != null) {
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IResource res = workspace.getRoot().findMember(fileBuffer.getLocation());
        if (res != null) return res.getProject();        	
    }
    return null;
}
 
Example 9
Source File: BatchModification.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public IProject getResolvedProject() {
	if (project != null) {
		return project;
	}
	if (document != null) {
		IResource resource = document.getAdapter(IResource.class);
		if (resource != null) {
			return resource.getProject();
		}
	}
	return null;
}
 
Example 10
Source File: RefactoringModifications.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected IFile getClasspathFile(IResource resource) {
	IProject project= resource.getProject();
	if (project == null) {
		return null;
	}
	IResource result= project.findMember(".classpath"); //$NON-NLS-1$
	if (result instanceof IFile) {
		return (IFile)result;
	}
	return null;
}
 
Example 11
Source File: CompilerLaunchShortcut.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private ILaunchConfiguration createNewLaunchConfiguration(IResource resource)
    throws CoreException, OperationCanceledException {
  String initialName = resource.getProject().getName();

  ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
  String launchConfigName = manager.generateLaunchConfigurationName(initialName);
  IProject project = resource.getProject();

  ILaunchConfigurationWorkingCopy wc = createLaunchConfigWorkingCopy(launchConfigName, project);

  ILaunchConfiguration toReturn = wc.doSave();

  return toReturn;
}
 
Example 12
Source File: ResourceProcessors.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static String[] computeAffectedNatures(IResource resource) throws CoreException {
	IProject project= resource.getProject();
	Set<String> result= new HashSet<>();
	Set<IProject> visitedProjects= new HashSet<>();
	computeNatures(result, visitedProjects, project);
	return result.toArray(new String[result.size()]);
}
 
Example 13
Source File: WebAppLaunchUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Given a resource, figure out what the target URL should be for a launch configuration
 * corresponding to this resource. If the resource has several possible URLs that correspond to
 * it, this method will cause a dialog to pop up, asking the user to choose one. If the resource's
 * project uses GAE but not GWT, return empty string; GAE-only projects have no startup url. If
 * the resource's project uses GWT 2.0+, return empty string since no URL is started in dev mode.
 */
public static String determineStartupURL(IResource resource, boolean isExternalLaunch)
    throws CoreException {
  ILaunchShortcutStrategy strategy = null;
  IProject project = resource.getProject();

  ExtensionQuery<ILaunchShortcutStrategyProvider> extQuery =
      new ExtensionQuery<ILaunchShortcutStrategyProvider>(GWTPlugin.PLUGIN_ID,
          "launchShortcutStrategy", "class");
  List<ExtensionQuery.Data<ILaunchShortcutStrategyProvider>> strategyProviderInfos =
      extQuery.getData();

  for (ExtensionQuery.Data<ILaunchShortcutStrategyProvider> data : strategyProviderInfos) {
    strategy = data.getExtensionPointData().getStrategy(project);
    break;
  }

  if (strategy == null) {
    if (WebAppUtilities.isWebApp(project)) {
      strategy = new WebAppLaunchShortcutStrategy();
    } else {
      assert (GWTNature.isGWTProject(project));
      strategy = new LegacyGWTLaunchShortcutStrategy();
    }
  }

  return strategy.generateUrl(resource, isExternalLaunch);
}
 
Example 14
Source File: LaunchHelper.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static IProject toProject(Object object) {
  IProject project = AdapterUtil.adapt(object, IProject.class);
  if (project != null) {
    return project;
  }
  IResource resource = AdapterUtil.adapt(object, IResource.class);
  if (resource != null) {
    return resource.getProject();
  }
  return null;
}
 
Example 15
Source File: TexlipseProjectPropertyPage.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Find out if the given file exists in the project.
 * 
 * @param filename the file name assumed to be in the project's main directory
 * @return true, if the given file exists
 */
private boolean projectFileExists(String filename) {

    IResource res = (IResource) getElement();
    IProject project = res.getProject();
    
    IResource file = project.findMember(filename);
    return file != null && file.exists();
}
 
Example 16
Source File: JavaWorkingSetUpdater.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void checkElementExistence(IWorkingSet workingSet) {
	List<IAdaptable> elements= new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements()));
	boolean changed= false;
	for (Iterator<IAdaptable> iter= elements.iterator(); iter.hasNext();) {
		IAdaptable element= iter.next();
		boolean remove= false;
		if (element instanceof IJavaElement) {
			IJavaElement jElement= (IJavaElement)element;
			// If we have directly a project then remove it when it
			// doesn't exist anymore. However if we have a sub element
			// under a project only remove the element if the parent
			// project is open. Otherwise we would remove all elements
			// in closed projects.
			if (jElement instanceof IJavaProject) {
				remove= !jElement.exists();
			} else {
				final IJavaProject javaProject= jElement.getJavaProject();
				final boolean isProjectOpen= javaProject != null ? javaProject.getProject().isOpen() : true;
				remove= isProjectOpen && !jElement.exists();
			}
		} else if (element instanceof IResource) {
			IResource resource= (IResource)element;
			// See comments above
			if (resource instanceof IProject) {
				remove= !resource.exists();
			} else {
				IProject project= resource.getProject();
				remove= (project != null ? project.isOpen() : true) && !resource.exists();
			}
		}
		if (remove) {
			iter.remove();
			changed= true;
		}
	}
	if (changed) {
		workingSet.setElements(elements.toArray(new IAdaptable[elements.size()]));
	}
}
 
Example 17
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isClasspathDelete(IPackageFragmentRoot pkgRoot) {
	IResource res= pkgRoot.getResource();
	if (res == null)
		return true;
	IProject definingProject= res.getProject();
	if (res.getParent() != null && pkgRoot.isArchive() && ! res.getParent().equals(definingProject))
		return true;

	IProject occurringProject= pkgRoot.getJavaProject().getProject();
	return !definingProject.equals(occurringProject);
}
 
Example 18
Source File: LatexRunner.java    From texlipse with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Adds a problem marker
 * 
 * @param error The error or warning string
 * @param causingSourceFile name of the sourcefile
 * @param linenr where the error occurs
 * @param severity
 * @param resource
 * @param layout true, if this is a layout warning
 */
private void addProblemMarker(String error, String causingSourceFile,
        int linenr, int severity, IResource resource, boolean layout) {
    
    
	IProject project = resource.getProject();
    IContainer sourceDir = TexlipseProperties.getProjectSourceDir(project);
    
    IResource extResource = null;
    if (causingSourceFile != null) {
    	IPath p = new Path(causingSourceFile);
    	
    	if (p.isAbsolute()) {
    		//Make absolute path relative to source directory
    		//or to the directory of the resource
    		if (sourceDir.getLocation().isPrefixOf(p)) {
    			p = p.makeRelativeTo(sourceDir.getLocation());
    		}
    		else if (resource.getParent().getLocation().isPrefixOf(p)) {
    			p = p.makeRelativeTo(resource.getParent().getLocation());
    		}
    	}

    	extResource = sourceDir.findMember(p);
        if (extResource == null) {
            extResource = resource.getParent().findMember(p);
        }
    }
    if (extResource == null)
        createMarker(resource, null, error + (causingSourceFile != null ? " (Occurance: "
                + causingSourceFile + ")" : ""), severity);
    else {
        if (linenr >= 0) {
            if (layout)
                createLayoutMarker(extResource, new Integer(linenr), error);
            else
                createMarker(extResource, new Integer(linenr), error, severity);
        } else
            createMarker(extResource, null, error, severity);
    }
}
 
Example 19
Source File: SharedCorePlugin.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Given a resource get the string in the filesystem for it.
 */
public static String getIResourceOSString(IResource f) {
    URI locationURI = f.getLocationURI();
    if (locationURI != null) {
        try {
            //RTC source control not return a valid uri
            return FileUtils.getFileAbsolutePath(new File(locationURI));
        } catch (IllegalArgumentException e) {
        }
    }

    IPath rawLocation = f.getRawLocation();
    if (rawLocation == null) {
        return null; //yes, we could have a resource that was deleted but we still have it's representation...
    }
    String fullPath = rawLocation.toOSString();
    //now, we have to make sure it is canonical...
    File file = new File(fullPath);
    if (file.exists()) {
        return FileUtils.getFileAbsolutePath(file);
    } else {
        //it does not exist, so, we have to check its project to validate the part that we can
        IProject project = f.getProject();
        IPath location = project.getLocation();
        File projectFile = location.toFile();
        if (projectFile.exists()) {
            String projectFilePath = FileUtils.getFileAbsolutePath(projectFile);

            if (fullPath.startsWith(projectFilePath)) {
                //the case is all ok
                return fullPath;
            } else {
                //the case appears to be different, so, let's check if this is it...
                if (fullPath.toLowerCase().startsWith(projectFilePath.toLowerCase())) {
                    String relativePart = fullPath.substring(projectFilePath.length());

                    //at least the first part was correct
                    return projectFilePath + relativePart;
                }
            }
        }
    }

    //it may not be correct, but it was the best we could do...
    return fullPath;
}
 
Example 20
Source File: GotoResourceAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * This is the orignal <code>select</code> method. Since
 * <code>GotoResourceDialog</code> needs to extend
 * <code>FilteredResourcesSelectionDialog</code> result of this
 * method must be combined with the <code>matchItem</code> method
 * from super class (<code>ResourceFilter</code>).
 *
 * @param resource
 *            A resource
 * @return <code>true</code> if item matches against given
 *         conditions <code>false</code> otherwise
 */
private boolean select(IResource resource) {
	IProject project= resource.getProject();
	try {
		if (project.getNature(JavaCore.NATURE_ID) != null)
			return fJavaModel.contains(resource);
	} catch (CoreException e) {
		// do nothing. Consider resource;
	}
	return true;
}