Java Code Examples for org.eclipse.core.resources.IProject#hasNature()

The following examples show how to use org.eclipse.core.resources.IProject#hasNature() . 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: JavaUtils.java    From developer-studio with Apache License 2.0 6 votes vote down vote up
public static List<IProject> getProjectsContainingClassName(String fullyQualifiedClassName) throws CoreException {
 IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
 List<IProject> projectsContainingTheClass=new ArrayList<IProject>();
 for (IProject project : projects) {
     try {
  if (project.isOpen()) {
         if (project.hasNature("org.eclipse.jdt.core.javanature")){
         	IJavaProject javaProject = JavaCore.create(project);
         	if (getJavaITypeForClass(javaProject, fullyQualifiedClassName)!=null){
         		projectsContainingTheClass.add(project);
         	}
         }
  }
     } catch (CoreException e) {
         throw e;
     }
 }
 return projectsContainingTheClass;
}
 
Example 2
Source File: ProjectCustomizer.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the UIMA nature to a project
 * 
 * @param project
 *          an IProject
 * @throws PearException
 *           If a problem occurs
 */
public static void addUIMANature(IProject project) throws PearException {
  try {
    if (!project.hasNature(UIMA_NATURE_ID)) {
      IProjectDescription description = project.getDescription();
      String[] natures = description.getNatureIds();
      String[] newNatures = new String[natures.length + 1];
      System.arraycopy(natures, 0, newNatures, 0, natures.length);
      newNatures[natures.length] = UIMA_NATURE_ID;
      description.setNatureIds(newNatures);
      project.setDescription(description, null);
      project.close(null);
      project.open(null);
    }
  } catch (Throwable e) {
    PearException subEx = new PearException("The UIMA Nature could not be added properly.", e);
    throw subEx;
  }
}
 
Example 3
Source File: NavigatorObjViewerFilter.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
	try {
		if (element instanceof IFolder) {
			IFolder folder = (IFolder) element;
			IProject project = folder.getProject();
			
			if (project.hasNature(GoNature.NATURE_ID)) {
				return !folder.getName().equals("_obj");
			}
		}
	} catch (CoreException e) {
		
	}
	
	return true;
}
 
Example 4
Source File: AbstractOptionsDialog.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param projectName
 * @return 
 */
public boolean setSootMainProject(String projectName) {
	if(projectName==null || projectName.length()==0) {
		sootMainProject = null;
		return true;
	}
	IProject project = SootPlugin.getWorkspace().getRoot().getProject(projectName);
	try {
		if(project.exists() && project.isOpen() && project.hasNature("org.eclipse.jdt.core.javanature")) {
			sootMainProject = projectName;
		}
	} catch (CoreException e) {
		e.printStackTrace();
	}
	return sootMainProject!=null;
}
 
Example 5
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 6
Source File: IDEClassPathBlock.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isJavaProject( IProject project )
{
	try
	{
		return project != null && project.hasNature( JavaCore.NATURE_ID );
	}
	catch ( CoreException e )
	{
		return false;
	}
}
 
Example 7
Source File: ProjectUtilities.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Using the natures name, check whether the current project has FindBugs
 * nature.
 *
 * @return boolean <code>true</code>, if the FindBugs nature is assigned to
 *         the project, <code>false</code> otherwise.
 */
public static boolean hasFindBugsNature(IProject project) {
    try {
        return ProjectUtilities.isJavaProject(project) && project.hasNature(FindbugsPlugin.NATURE_ID);
    } catch (CoreException e) {
        FindbugsPlugin.getDefault().logException(e, "Error while testing SpotBugs nature for project " + project);
    }
    return false;
}
 
Example 8
Source File: ProjectDataModel.java    From developer-studio with Apache License 2.0 5 votes vote down vote up
public static IContainer getContainer(File absolutionPath, String projectNature) {
	IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
	int length = 0;
	IProject currentSelection = null;
	for (IProject project : projects) {
		try {
			if (project.isOpen() && project.hasNature(projectNature)) {
				File projectLocation = project.getLocation().toFile();
				int projectLocationLength = projectLocation.toString().length();
				if (projectLocationLength > length && projectLocationLength <= absolutionPath.toString().length()) {
					if (absolutionPath.toString().startsWith(projectLocation.toString())) {
						length = projectLocationLength;
						currentSelection = project;
					}
				}
			}
		} catch (CoreException e) {
			logger.error("ObserverFailed ", e);
		}
	}
	IContainer saveLocation = null;
	if (currentSelection != null) {
		String path =
		              absolutionPath.toString().substring(currentSelection.getLocation().toFile().toString()
		                                                                  .length());

		if (path.equals("")) {
			saveLocation = currentSelection;
		} else {
			saveLocation = currentSelection.getFolder(path);
		}
	}
	return saveLocation;
}
 
Example 9
Source File: TestProject.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
private IStatus isProjectValid() throws CoreException{
	IProject project = getProject();
	if( !project.hasNature(HybridAppNature.NATURE_ID ) ){
		return error("project does not have hybrid application nature");
	}
	if( !project.hasNature( JavaScriptCore.NATURE_ID )){
		return error("project does not have javascript nature");
	}
	for (int i = 0; i < COMMON_PATHS.length; i++) {
		IResource resource = project.findMember(COMMON_PATHS[i]);
		if(resource == null || !resource.exists()){
			error("Project is missing "+ COMMON_PATHS[i] );
		}
	}
	Document doc;
	try {
		doc = loadConfigXML();
	} catch (Exception e) {
		return error("error parsing config.xml");
	}
	String id = doc.getDocumentElement().getAttribute("id");
	if( !appId.equals(id)){
		error("wrong application id");
	}
	NodeList nodes = doc.getDocumentElement().getElementsByTagName("name");
	if(nodes.getLength()< 1){
		return error("Application name is not updated"); 
	}
	String name = nodes.item(0).getTextContent();
	if( !appName.equals(name)){
		return error("Wrong application name");
	}
	
	
	return Status.OK_STATUS;
}
 
Example 10
Source File: XtextProjectHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean hasNature(IProject project) {
	Preconditions.checkNotNull(project);
	try {
		if (project.isAccessible()) {
			return project.hasNature(NATURE_ID);
		}
	} catch (CoreException e) {
		log.error(e.getMessage(), e);
	}
	return false;
}
 
Example 11
Source File: CheckProjectHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks that the Java file for the given class name exists in the project.
 *
 * @param project
 *          the project, must not be {@code null}
 * @param className
 *          the class name, must not be {@code null}
 * @return whether the corresponding java file exists in the project
 */
public boolean isJavaFilePresent(final IProject project, final String className) {
  int packageSplitIndex = className.lastIndexOf('.');
  if (packageSplitIndex == -1) {
    throw new IllegalArgumentException(String.format("%s is a simple class name or not a class name at all.", className));
  }
  int fileNameEndIndex = className.indexOf('$');
  if (fileNameEndIndex == -1) {
    fileNameEndIndex = className.length();
  }
  String packageName = className.substring(0, packageSplitIndex);
  String fileName = className.substring(packageSplitIndex + 1, fileNameEndIndex) + ".java";
  try {
    if (project.hasNature(JavaCore.NATURE_ID)) {
      for (IPackageFragmentRoot root : JavaCore.create(project).getAllPackageFragmentRoots()) {
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
          for (IJavaElement element : root.getChildren()) {
            if (element instanceof IPackageFragment && packageName.equals(element.getElementName())
                && ((IPackageFragment) element).getCompilationUnit(fileName).exists()) {
              return true;
            }
          }
        }
      }
    }
  } catch (CoreException e) {
    LOGGER.error(String.format("Failed to read project %s.", project.getName()), e);
  }
  return false;
}
 
Example 12
Source File: ProjectUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return true if the project has any GWT facets or natures on it
 */
public static boolean isGwtProject(IProject project) throws CoreException {
  String natureId = "com.gwtplugins.gwt.eclipse.core.gwtNature"; // GWTNature.NATURE_ID
  String facetId = "com.gwtplugins.gwt.facet";
  try {
    return project.isAccessible()
        && (project.hasNature(natureId) || FacetedProjectFramework.hasProjectFacet(project,
            facetId));
  } catch (CoreException e) {
    CorePluginLog.logError(e);
  }
  return false;
}
 
Example 13
Source File: NatureUtils.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the nature identified by {@code natureId}. If the {@code project} does not have the
 * nature, this method does nothing.
 *
 * @param monitor a progress monitor, or {@code null} if progress reporting is not desired
 */
public static void removeNature(IProject project, String natureId, IProgressMonitor monitor)
    throws CoreException {
  if (project.hasNature(natureId)) {
    // Remove the nature ID from the natures in the project description
    IProjectDescription description = project.getDescription();
    List<String> natures = Lists.newArrayList(description.getNatureIds());
    natures.remove(natureId);
    description.setNatureIds(natures.toArray(new String[0]));
    project.setDescription(description, monitor);
  }
}
 
Example 14
Source File: JavaProjectHelper.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a IJavaProject.
 *
 * @param projectName
 *            The name of the project
 * @param binFolderName
 *            Name of the output folder
 * @return Returns the Java project handle
 * @throws CoreException
 *             Project creation failed
 */
public static IJavaProject createJavaProject(String projectName, String binFolderName) throws CoreException {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = root.getProject(projectName);
    if (!project.exists()) {
        project.create(null);
    } else {
        project.refreshLocal(IResource.DEPTH_INFINITE, null);
    }

    if (!project.isOpen()) {
        project.open(null);
    }

    IPath outputLocation;
    if (binFolderName != null && binFolderName.length() > 0) {
        IFolder binFolder = project.getFolder(binFolderName);
        if (!binFolder.exists()) {
            CoreUtility.createFolder(binFolder, false, true, null);
        }
        outputLocation = binFolder.getFullPath();
    } else {
        outputLocation = project.getFullPath();
    }

    if (!project.hasNature(JavaCore.NATURE_ID)) {
        addNatureToProject(project, JavaCore.NATURE_ID, null);
    }

    IJavaProject jproject = JavaCore.create(project);

    jproject.setOutputLocation(outputLocation, null);
    jproject.setRawClasspath(new IClasspathEntry[0], null);

    return jproject;
}
 
Example 15
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns true if the given project is accessible and it has
 * a java nature, otherwise false.
 * @param project IProject
 * @return boolean
 */
public static boolean hasJavaNature(IProject project) {
	try {
		return project.hasNature(JavaCore.NATURE_ID);
	} catch (CoreException e) {
		if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(project.getName()))
			return true;
		// project does not exist or is not open
	}
	return false;
}
 
Example 16
Source File: ReportLaunchConfigurationDelegate.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns true if the given project is accessible and it has a java nature,
 * otherwise false.
 * 
 * @param project
 *            IProject
 * @return boolean
 */
private boolean hasJavaNature( IProject project )
{
	try
	{
		return project.hasNature( JavaCore.NATURE_ID );
	}
	catch ( CoreException e )
	{
		// project does not exist or is not open
	}
	return false;
}
 
Example 17
Source File: ProjectBuilder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isInterestingProject ( final IProject project )
{
    try
    {
        final boolean result = project.hasNature ( Constants.PROJECT_NATURE_CONFIGURATION );
        logger.debug ( "Checking project - project: {}, result: {}", project, result );
        return result;
    }
    catch ( final CoreException e )
    {
        StatusManager.getManager ().handle ( e.getStatus () );
        return false;
    }

}
 
Example 18
Source File: ProjectLocationAwareWorkingSetManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns {@code true} if the given project is of the
 * {@link ProjectLocationAwareWorkingSetManager#REMOTE_EDIT_PROJECT_NATURE_ID} nature.
 */
private boolean isRemoteEditNature(IProject project) {
	try {
		if (project.hasNature(REMOTE_EDIT_PROJECT_NATURE_ID)) {
			return true;
		}
	} catch (CoreException e) {
		return false;
	}
	return false;
}
 
Example 19
Source File: ArtifactProjectDeleteParticipant.java    From developer-studio with Apache License 2.0 5 votes vote down vote up
/**
 * This method gets executed before the refactoring gets executed on
 * original file which means this method is executed before the actual
 * project is deleted from the workspace. If you have any task need to run
 * before the project is deleted, you need to generate Changes for those
 * tasks in this method.
 */
@Override
public Change createPreChange(IProgressMonitor arg0) throws CoreException, OperationCanceledException {

	CompositeChange deleteChange = new CompositeChange("Delete Artifact Project");

	IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();

	for (IProject project : projects) {
		if (project.isOpen() && project.hasNature("org.wso2.developerstudio.eclipse.distribution.project.nature")) {
			try {
				IFile pomFile = project.getFile(POM_XML);
				MavenProject mavenProject = ProjectRefactorUtils.getMavenProject(project);
				Dependency projectDependency = ProjectRefactorUtils.getDependencyForTheProject(originalProject);
				if (mavenProject != null) {
					List<?> dependencies = mavenProject.getDependencies();
					if (projectDependency != null) {
						for (Iterator<?> iterator = dependencies.iterator(); iterator.hasNext();) {
							Dependency dependency = (Dependency) iterator.next();
							if (ProjectRefactorUtils.isDependenciesEqual(projectDependency, dependency)) {
								deleteChange.add(new MavenConfigurationFileDeleteChange(project.getName(), pomFile,
								                                                        originalProject));
							}
						}
					}
				}
			} catch (Exception e) {
				log.error("Error occured while trying to generate the Refactoring", e);
			}
		}
	}

	return deleteChange;
}
 
Example 20
Source File: AddProjectNature.java    From CodeCheckerEclipsePlugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    // TODO Auto-generated method stub    	

    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    if (window != null) {
        IStructuredSelection selection = (IStructuredSelection) window.getSelectionService()
                .getSelection();
        Object firstElement = selection.getFirstElement();
        if (firstElement instanceof IAdaptable) {
            IProject project = (IProject) ((IAdaptable) firstElement).getAdapter(IProject
                    .class);
            if (project == null) {
            	Logger.log(IStatus.INFO, "Not a project.");
                return null;
            }
            IPath path = project.getFullPath();
            Logger.log(IStatus.INFO, "" + path);

            try {
                if (project.hasNature(CodeCheckerNature.NATURE_ID)) {                    	
                    return null;
                }

                IProjectDescription description = project.getDescription();
                String[] prevNatures = description.getNatureIds();
                String[] newNatures = new String[prevNatures.length + 1];
                System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
                newNatures[prevNatures.length] = CodeCheckerNature.NATURE_ID;
                description.setNatureIds(newNatures);

                IProgressMonitor monitor = null;
                project.setDescription(description, monitor);
                ConsoleFactory.consoleWrite(project.getName() + ": Sucessfully added CodeChecker Nature");
                Logger.log(IStatus.INFO, "Project nature added!");

            } catch (CoreException e) {
                // TODO Auto-generated catch block
            	Logger.log(IStatus.ERROR,  e.toString());
            	Logger.log(IStatus.INFO, e.getStackTrace().toString());
            }

        }
    }

    return null;
}