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

The following examples show how to use org.eclipse.core.resources.IResource#getType() . 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: TestsRunner.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private static boolean isInteresting(final IProject p) throws CoreException {
	if (p == null || !p.exists() || !p.isAccessible())
		return false;
	// If it is contained in one of the built-in tests projects, return true
	if (p.getDescription().hasNature(WorkbenchHelper.TEST_NATURE))
		return true;
	if (GamaPreferences.Runtime.USER_TESTS.getValue()) {
		// If it is not in user defined projects, return false
		if (p.getDescription().hasNature(WorkbenchHelper.BUILTIN_NATURE))
			return false;
		// We try to find in the project a folder called 'tests'
		final IResource r = p.findMember("tests");
		if (r != null && r.exists() && r.isAccessible() && r.getType() == IResource.FOLDER)
			return true;
	}
	return false;
}
 
Example 2
Source File: EIPModelTreeContentProvider.java    From eip-designer with Apache License 2.0 6 votes vote down vote up
/** */
private static void findEIPModels(List<IResource> models, IPath path, IWorkspaceRoot workspaceRoot){
   IContainer container =  workspaceRoot.getContainerForLocation(path);

   try {
      IResource[] iResources = container.members();
      for (IResource iResource : iResources) {
         if ("eip".equalsIgnoreCase(iResource.getFileExtension())) {
            models.add(iResource);
         }
         if (iResource.getType() == IResource.FOLDER) {
            IPath tempPath = iResource.getLocation();
            findEIPModels(models, tempPath, workspaceRoot);
         }
      }
   } catch (CoreException e) {
      System.err.println("CoreException while browsing " + path);
   }
}
 
Example 3
Source File: SourceFolderSelectionDialogButtonField.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * tries to build a packagefragmentroot out of a string and sets the string into this
 * packagefragmentroot.
 *
 * @param rootString
 */
private IPackageFragmentRoot getRootFromString(String rootString) {
	if (rootString.length() == 0) {
		return null;
	}
	IPath path= new Path(rootString);
	IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
	IResource res= workspaceRoot.findMember(path);
	if (res == null) {
		return null;
	}
	int resType= res.getType();
	if (resType == IResource.PROJECT || resType == IResource.FOLDER) {
		IProject proj= res.getProject();
		if (!proj.isOpen()) {
			return null;
		}
		IJavaProject jproject= JavaCore.create(proj);
		IPackageFragmentRoot root= jproject.getPackageFragmentRoot(res);
		if (root.exists()) {
			return root;
		}
	}
	return null;
}
 
Example 4
Source File: MavenOutputWarDirectoryLocator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IFolder getOutputWarDirectory(IProject project) {
  if (!MavenUtils.hasMavenNature(project)) {
    return null;
  }

  if (WebAppUtilities.isWebApp(project)) {
    IPath lastUsedWarOutLocation = WebAppProjectProperties.getLastUsedWarOutLocation(project);
    if (lastUsedWarOutLocation != null) {
      IResource lastUsedWarOutResource = ResourceUtils.getResource(lastUsedWarOutLocation);
      if (lastUsedWarOutResource != null && lastUsedWarOutResource.getType() == IResource.FOLDER) {
        return (IFolder) lastUsedWarOutResource;
      }
    }
  }
  return null;
}
 
Example 5
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected RefactoringStatus verifyDestination(IResource resource) {
	Assert.isNotNull(resource);
	if (!resource.exists() || resource.isPhantom()) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_phantom);
	}
	if (!resource.isAccessible()) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inaccessible);
	}

	if (!(resource instanceof IContainer)) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource);
	}

	if (resource.getType() == IResource.ROOT) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource);
	}

	if (isChildOfOrEqualToAnyFolder(resource)) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource);
	}

	if (containsLinkedResources() && !ReorgUtils.canBeDestinationForLinkedResources(resource)) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked);
	}

	return new RefactoringStatus();
}
 
Example 6
Source File: SolidityBuilder.java    From uml2solidity with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(IResource resource) throws CoreException {
	if (resource.getType() == IResource.FILE && "sol".equals(resource.getFileExtension())) {
		files.add(resource.getRawLocation().toString());
	}
	return true;
}
 
Example 7
Source File: CommitAction.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private boolean onTagPath(IResource[] modifiedResources) throws SVNException {
 // Multiple resources selected.
 if (url == null) {
IResource resource = modifiedResources[0];
ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);	        
         String firstUrl = svnResource.getStatus().getUrlString();
         if ((firstUrl == null) || (resource.getType() == IResource.FILE)) firstUrl = Util.getParentUrl(svnResource);
         if (firstUrl.indexOf("/tags/") != -1) return true; //$NON-NLS-1$
 }
 // One resource selected.
    else if (url.indexOf("/tags/") != -1) return true; //$NON-NLS-1$
    return false;
}
 
Example 8
Source File: ResourceUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IFile[] getFiles(ICompilationUnit[] cus) {
	List<IResource> files= new ArrayList<IResource>(cus.length);
	for (int i= 0; i < cus.length; i++) {
		IResource resource= cus[i].getResource();
		if (resource != null && resource.getType() == IResource.FILE)
			files.add(resource);
	}
	return files.toArray(new IFile[files.size()]);
}
 
Example 9
Source File: ProblemMarkerManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void checkInvalidate(IResourceDelta delta, IResource resource) {
	int kind= delta.getKind();
	if (kind == IResourceDelta.REMOVED || kind == IResourceDelta.ADDED || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) {
		// invalidate the resource and all parents
		while (resource.getType() != IResource.ROOT && fChangedElements.add(resource)) {
			resource= resource.getParent();
		}
	}
}
 
Example 10
Source File: ProjectResourceControl.java    From depan with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if the inputs are consistent.
 * 
 * @return error string if problems exist, or null if inputs are valid
 */
public static String validateInputs(String containerName, String fileName) {

  if (containerName.length() == 0) {
    return "File container must be specified";
  }

  IPath containerPath = PlatformTools.buildPath(containerName);
  IResource container = WorkspaceTools.buildWorkspaceResource(containerPath);
  if (container == null
      || (container.getType()
          & (IResource.PROJECT | IResource.FOLDER)) == 0) {
    return "File container must exist";
  }
  if (!container.isAccessible()) {
    return "Project must be writable";
  }
  if (fileName.length() == 0) {
    return "File name must be specified";
  }
  IPath filePath = PlatformTools.buildPath(fileName);
  if ((1 != filePath.segmentCount()) || (filePath.hasTrailingSeparator())) {
    return "File name cannot be a path";
  }
  filePath.getFileExtension();

  return null;
}
 
Example 11
Source File: AnalysisBuilderVisitor.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void visitRemovedResource(IResource resource, ICallback0<IDocument> document, IProgressMonitor monitor) {
    PythonNature nature = getPythonNature(resource);
    if (nature == null) {
        return;
    }
    if (resource.getType() == IResource.FOLDER) {
        //We don't need to explicitly treat any folder (just its children -- such as __init__ and submodules)
        return;
    }
    if (!isFullBuild()) {
        //on a full build, it'll already remove all the info
        String moduleName;
        try {
            moduleName = getModuleName(resource, nature);
        } catch (MisconfigurationException e) {
            Log.log(e);
            return;
        }

        long documentTime = this.getDocumentTime();
        if (documentTime == -1) {
            Log.log("Warning: The document time in the visitor for remove is -1. Changing for current time. "
                    + "Resource: " + resource + ". Module name: " + moduleName);
            documentTime = System.currentTimeMillis();
        }
        long resourceModificationStamp = resource.getModificationStamp();

        final IAnalysisBuilderRunnable runnable = AnalysisBuilderRunnableFactory.createRunnable(moduleName, nature,
                isFullBuild(), false, AnalysisBuilderRunnable.ANALYSIS_CAUSE_BUILDER, documentTime,
                resourceModificationStamp);

        if (runnable == null) {
            //It may be null if the document version of the new one is lower than one already active.
            return;
        }

        execRunnable(moduleName, runnable, false);
    }
}
 
Example 12
Source File: RefreshHandler.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
protected void simpleRefresh(final IResource resource, final IProgressMonitor monitor) throws CoreException {
	if (resource.getType() == IResource.PROJECT) {
		checkLocationDeleted((IProject) resource);
	} else if (resource.getType() == IResource.ROOT) {
		final IProject[] projects = ((IWorkspaceRoot) resource).getProjects();
		for (final IProject project : projects) {
			checkLocationDeleted(project);
		}
	}
	resource.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
 
Example 13
Source File: ResourceUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IFile getFile(ICompilationUnit cu) {
	IResource resource= cu.getResource();
	if (resource != null && resource.getType() == IResource.FILE)
		return (IFile)resource;
	else
		return null;
}
 
Example 14
Source File: CommitSynchronizeAction.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
protected SynchronizeModelOperation getSubscriberOperation(ISynchronizePageConfiguration configuration, IDiffElement[] elements) {
	changeSets = new ArrayList();
	// override the elemenents (this has to be done this way because of final methods in eclipse api)
	elements = getFilteredDiffElementsOverride();
	String url = null;
	ChangeSet changeSet = null;
    IStructuredSelection selection = getStructuredSelection();
	Iterator iter = selection.iterator();
	String proposedComment = "";
	while (iter.hasNext()) {
		ISynchronizeModelElement synchronizeModelElement = (ISynchronizeModelElement)iter.next();
		proposedComment = getProposedComment(proposedComment, synchronizeModelElement);
		if (!(synchronizeModelElement instanceof ChangeSetDiffNode)) {
			if (url == null && selection.size() == 1) {
			    IResource resource = synchronizeModelElement.getResource();
			    if (resource != null) {
				    ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
		            try {
		                url = svnResource.getStatus().getUrlString();
		                if ((url == null) || (resource.getType() == IResource.FILE)) url = Util.getParentUrl(svnResource);
		            } catch (SVNException e) {
		            	if (!e.operationInterrupted()) {
		            		SVNUIPlugin.log(IStatus.ERROR, e.getMessage(), e);
		            	}
		            }	    
			    }
			}
		} else {
			if (selection.size() == 1) {
				ChangeSetDiffNode changeSetDiffNode = (ChangeSetDiffNode)synchronizeModelElement;
				changeSet = changeSetDiffNode.getSet();
			}
		}
	}
	CommitSynchronizeOperation operation = new CommitSynchronizeOperation(configuration, elements, url, proposedComment);
    operation.setChangeSet(changeSet);
	return operation;
}
 
Example 15
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns whether the given resource is accessible. Files and folders are
 * always considered accessible and a project is accessible if it is open.
 *
 * @param resource
 *            the resource
 * @return <code>true</code> if the resource is accessible, and
 *         <code>false</code> if it is not
 */
private boolean isAccessible(IResource resource) {
    switch (resource.getType()) {
        case IResource.FILE:
            return true;
        case IResource.FOLDER:
            return true;
        case IResource.PROJECT:
            return ((IProject) resource).isOpen();
        default:
            return false;
    }
}
 
Example 16
Source File: NewEntryPointWizardPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private void initEntryPointPage(IResource resource) {
  if (resource.getType() == IResource.ROOT || !resource.isAccessible()) {
    return;
  }

  if (moduleField.init(resource)) {
    // Initialize the package based on the module's client source path
    if (moduleStatus.isOK()) {
      initPackageFromModule();
    } else {
      // If initializing the module caused an error, reset it
      moduleField.setText("");
    }
  }
}
 
Example 17
Source File: XMLPersistenceProvider.java    From ice with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This operation loads the Item id map with the contents of the project
 * space.
 */
private void loadItemIdMap() {

	// Local Declarations
	int id;
	ArrayList<String> names = new ArrayList<>();
	IResource[] members;

	try {
		// Get the list of files in the project space
		members = project.members();
		for (IResource resource : members) {
			// Only add the resources that are xml files with the format
			// that we expect. This uses a regular expression that checks
			// for <itemName>_<itemId>.xml.
			if (resource.getType() == IResource.FILE && resource.getName()
					.matches("^[a-zA-Z0-9_\\-]*_\\d+\\.xml$")) {
				names.add(resource.getName());
			}
		}

		// Get the ids of all of the items from the file names and map them
		// to the names.
		for (String name : names) {
			logger.info("XMLPersistenceProvider Message: "
					+ "Found persisted Item at " + name);
			// Remove the file extension
			String[] nameParts = name.split("\\.");
			String nameMinusExt = nameParts[0];
			// Get the id from the end
			String[] nameMinusExtParts = nameMinusExt.split("_");
			String idString = nameMinusExtParts[nameMinusExtParts.length
					- 1];
			id = Integer.valueOf(idString);
			// Put the info in the map
			itemIdMap.put(id, name);
		}

	} catch (CoreException e) {
		// TODO Auto-generated catch block
		logger.error(getClass().getName() + " Exception!", e);
	}

	return;
}
 
Example 18
Source File: JavaDeleteProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void checkDirtyCompilationUnit(RefactoringStatus result, ICompilationUnit cunit) {
	IResource resource= cunit.getResource();
	if (resource == null || resource.getType() != IResource.FILE)
		return;
	checkDirtyFile(result, (IFile)resource);
}
 
Example 19
Source File: GlobalizeModelWizard.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * The framework calls this to create the contents of the wizard.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void addPages ()
{
    // Create a page, set the title, and the initial model file name.
    //
    newFileCreationPage = new GlobalizeModelWizardNewFileCreationPage ( "Whatever", selection ); //$NON-NLS-1$
    newFileCreationPage.setTitle ( GlobalizeEditorPlugin.INSTANCE.getString ( "_UI_GlobalizeModelWizard_label" ) ); //$NON-NLS-1$
    newFileCreationPage.setDescription ( GlobalizeEditorPlugin.INSTANCE.getString ( "_UI_GlobalizeModelWizard_description" ) ); //$NON-NLS-1$
    newFileCreationPage.setFileName ( GlobalizeEditorPlugin.INSTANCE.getString ( "_UI_GlobalizeEditorFilenameDefaultBase" ) + "." + FILE_EXTENSIONS.get ( 0 ) ); //$NON-NLS-1$ //$NON-NLS-2$
    addPage ( newFileCreationPage );

    // Try and get the resource selection to determine a current directory for the file dialog.
    //
    if ( selection != null && !selection.isEmpty () )
    {
        // Get the resource...
        //
        Object selectedElement = selection.iterator ().next ();
        if ( selectedElement instanceof IResource )
        {
            // Get the resource parent, if its a file.
            //
            IResource selectedResource = (IResource)selectedElement;
            if ( selectedResource.getType () == IResource.FILE )
            {
                selectedResource = selectedResource.getParent ();
            }

            // This gives us a directory...
            //
            if ( selectedResource instanceof IFolder || selectedResource instanceof IProject )
            {
                // Set this for the container.
                //
                newFileCreationPage.setContainerFullPath ( selectedResource.getFullPath () );

                // Make up a unique new name here.
                //
                String defaultModelBaseFilename = GlobalizeEditorPlugin.INSTANCE.getString ( "_UI_GlobalizeEditorFilenameDefaultBase" ); //$NON-NLS-1$
                String defaultModelFilenameExtension = FILE_EXTENSIONS.get ( 0 );
                String modelFilename = defaultModelBaseFilename + "." + defaultModelFilenameExtension; //$NON-NLS-1$
                for ( int i = 1; ( (IContainer)selectedResource ).findMember ( modelFilename ) != null; ++i )
                {
                    modelFilename = defaultModelBaseFilename + i + "." + defaultModelFilenameExtension; //$NON-NLS-1$
                }
                newFileCreationPage.setFileName ( modelFilename );
            }
        }
    }
    initialObjectCreationPage = new GlobalizeModelWizardInitialObjectCreationPage ( "Whatever2" ); //$NON-NLS-1$
    initialObjectCreationPage.setTitle ( GlobalizeEditorPlugin.INSTANCE.getString ( "_UI_GlobalizeModelWizard_label" ) ); //$NON-NLS-1$
    initialObjectCreationPage.setDescription ( GlobalizeEditorPlugin.INSTANCE.getString ( "_UI_Wizard_initial_object_description" ) ); //$NON-NLS-1$
    addPage ( initialObjectCreationPage );
}
 
Example 20
Source File: TexlipseProjectPropertyPage.java    From texlipse with Eclipse Public License 1.0 4 votes vote down vote up
/**
     * Called when the defaults-button is pressed.
     */
    protected void performDefaults() {
        super.performDefaults();

        IResource project = (IResource) getElement();

        if (project.getType() == IResource.PROJECT) {
            //load settings, if changed on disk
            if (TexlipseProperties.isProjectPropertiesFileChanged((IProject) project)) {
                TexlipseProperties.loadProjectProperties((IProject) project);
            }
        }
        
        // derived flags
        String derivTmp = TexlipseProperties.getProjectProperty(project, TexlipseProperties.MARK_TEMP_DERIVED_PROPERTY);
        derivedTempCheckbox.setSelection("true".equals(derivTmp));
        String derivOut = TexlipseProperties.getProjectProperty(project, TexlipseProperties.MARK_OUTPUT_DERIVED_PROPERTY);
        derivedOutputCheckbox.setSelection("true".equals(derivOut));
        
        // language code
        String lang = TexlipseProperties.getProjectProperty(project, TexlipseProperties.LANGUAGE_PROPERTY);
        languageField.setText((lang != null) ? lang : "");
        
        // makeindex style file
        String sty = TexlipseProperties.getProjectProperty(project, TexlipseProperties.MAKEINDEX_STYLEFILE_PROPERTY);
        indexStyleField.setText((sty != null) ? sty : "");
        
        // read source file name
        String srcDir = TexlipseProperties.getProjectProperty(project,
                TexlipseProperties.SOURCE_DIR_PROPERTY);
        if (srcDir == null) {
            srcDir = "";
        } else if (srcDir.length() > 0 && !srcDir.endsWith("/")) {
            srcDir += '/';
        }
        
        String srcFile = TexlipseProperties.getProjectProperty(project,
                TexlipseProperties.MAINFILE_PROPERTY);
        sourceFileField.setText((srcFile != null) ? (srcDir+srcFile) : "");
        
        // read temp dir
        String temp = TexlipseProperties.getProjectProperty(project,
                TexlipseProperties.TEMP_DIR_PROPERTY);
        tempDirField.setText((temp != null) ? temp : "");
        
        // read bibRef dir
//        String bibRef = TexlipseProperties.getProjectProperty(project,
//                TexlipseProperties.BIBREF_DIR_PROPERTY);
//        bibRefDirField.setText((bibRef != null) ? bibRef : "");

        // find out the default builder
        String str = TexlipseProperties.getProjectProperty(project,
                TexlipseProperties.BUILDER_NUMBER);
        int num = 0;
        if (str == null) {
            str = TexlipsePlugin.getPreference(TexlipseProperties.BUILDER_NUMBER);
        }
        try {
            num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        builderChooser.setSelectedBuilder(num);

        // read output file name
        String outDir = TexlipseProperties.getProjectProperty(project,
                TexlipseProperties.OUTPUT_DIR_PROPERTY);
        if (outDir == null) {
            outDir = "";
        } else if (outDir.length() > 0 && !outDir.endsWith("/")) {
            outDir += '/';
        }
        
        String outFile = TexlipseProperties.getProjectProperty(project,
                TexlipseProperties.OUTPUTFILE_PROPERTY);
        outFileField.setText((outFile != null) ? (outDir+outFile) : "");
        
        // set status of the page
        validateSourceFileField();
        validateOutputFileField();
        validateTempFileField();

    }