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

The following examples show how to use org.eclipse.core.resources.IFile#getProject() . These examples are extracted from open source projects. 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
/**
 * {@inheritDoc}
 */
@Override
public boolean accept(Object element) {
  boolean passes = true;

  if (element instanceof IFile) {

    IFile file = (IFile) element;
    IProject project = file.getProject();

    if (RepositoryProvider.isShared(project)) {

      RepositoryProvider provider = RepositoryProvider.getProvider(project);

      if (provider != null) {

        Subscriber subscriber = provider.getSubscriber();

        if (subscriber != null) {
          passes = hasChanges(file, subscriber);
        }
      }
    }
  }
  return passes;
}
 
Example 2
/**
 * Gets the {@link Session} path form the given platform resource {@link URI}.
 * 
 * @param platformResourceURI
 *            the platform resource {@link URI}
 * @return the {@link Session} path form the given platform resource {@link URI} if any, <code>null</code> otherwise
 */
private String getSessionFromPlatformResource(final URI platformResourceURI) {
    final String res;
    final String filePath = platformResourceURI.toPlatformString(true);
    final IFile genconfFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(filePath));
    final IProject project = genconfFile.getProject();
    final ModelingProject modelingProject = getModelingProject(project);

    if (modelingProject != null) {
        final Session session = modelingProject.getSession();
        if (session != null) {
            final URI sessionURI = session.getSessionResource().getURI();
            res = URI.decode(sessionURI.deresolve(platformResourceURI, false, true, true).toString());
        } else {
            res = null;
        }
    } else {
        res = null;
    }
    return res;
}
 
Example 3
private DataflowMavenModel fromIFile(IFile file) throws CoreException {
  try {
    IStructuredModel structuredModel =
        StructuredModelManager.getModelManager().getModelForEdit(file);
    if (structuredModel instanceof IDOMModel) {
      XPath xpath = XPathFactory.newInstance().newXPath();
      xpath.setNamespaceContext(pomNamespaceContext);
      return new DataflowMavenModel(
          dependencyManager, xpath, file.getProject(), (IDOMModel) structuredModel);
    } else {
      throw new CoreException(new Status(Status.ERROR, DataflowCorePlugin.PLUGIN_ID,
          String.format("File %s wasn't a DOM model", file)));
    }
  } catch (IOException e) {
    throw new CoreException(new Status(Status.ERROR, DataflowCorePlugin.PLUGIN_ID,
        String.format("Couldn't get a DOM Model for file %s", file), e));
  }
}
 
Example 4
protected Set<IFile> getProjectStatechartInput(Diagram diagram) {
	final IFile file = WorkspaceSynchronizer.getFile(diagram.eResource());
	final IProject project = file.getProject();
	final Set<IFile> result = new HashSet<IFile>();
	try {
		project.accept(new IResourceVisitor() {
			public boolean visit(IResource resource) throws CoreException {
				// TODO check for package explorer filters here
				if (resource.isHidden()) {
					return false;
				}
				if (resource instanceof IFile) {
					if (file.getFileExtension().equals(resource.getFileExtension()))
						result.add((IFile) resource);
				}
				return true;
			}
		});
	} catch (CoreException e) {
		e.printStackTrace();
	}
	return result;
}
 
Example 5
/**
 * open the file document which is refered to in the bibtex entry. The path
 * has to start from the root of the project where the bibtex entry is
 * included.
 */
private void openPdf() {
	IFile res = Utils.getIFilefromDocument(document);
	if (res == null || res.getProject() == null) {
		MessageDialog.openInformation(this.getSite().getShell(), "Bibtex" + document.getKey(), "Root or Resource not found");
		return;
	}
	IFile file = res.getProject().getFile(document.getFile());
	if (file.exists()) {
		IFileStore fileStore = EFS.getLocalFileSystem().getStore(file.getLocation());
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

		try {
			IDE.openEditorOnFileStore(page, fileStore);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	} else {
		MessageDialog.openInformation(this.getSite().getShell(), "Bibtex" + document.getKey(), "Document not found");
	}
}
 
Example 6
@Override
protected ISimulationEngine createExecutionContainer(final ILaunch launch, Statechart statechart) {
	try {

		Injector injector = getInjector(statechart, launch);
		IFile file = WorkspaceSynchronizer.getFile(statechart.eResource());
		injector.injectMembers(this);

		for (IOperationExecutor mockup : mockups) {
			if (mockup instanceof JavaOperationMockup) {
				IProject project = file.getProject();
				String classes = launch.getLaunchConfiguration().getAttribute(ISCTLaunchParameters.OPERATION_CLASS,
						"");
				String[] split = classes.split(",");
				((JavaOperationMockup) mockup).initOperationCallbacks(project, split);
			}
		}
		return factory.createExecutionContainer(statechart, launch);
	} catch (CoreException e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 7
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	ISelection sel= HandlerUtil.getCurrentSelection(event);
	IFile iFile = getIFileFrom(sel);
	RenameRefactoringInfo refactoringInfo = getRenameRefactoringInfo(iFile);
	if (refactoringInfo == null) {
		MessageDialog.openError(HandlerUtil.getActiveShell(event), Messages.RenameCompilationUnitHandler_InvalidSelection, Messages.RenameCompilationUnitHandler_CannotPerformRefactoringWithCurrentSelection);
		return null;
	}
	
	IProject iProject = iFile.getProject();
	ILaunch launch = LaunchConfigurationUtils.getLaunch(iProject);
	if (launch != null && launch.getDebugTarget() != null && !launch.getDebugTarget().isTerminated()) {
		MessageDialog.openError(HandlerUtil.getActiveShell(event), Messages.RenameCompilationUnitHandler_ProjectDebugged, Messages.RenameCompilationUnitHandler_CannotChangeFilesOfDebuggedProject);
		return null;
	}
	
	RenameRefactoringProcessor refactoringProcessor = new RenameRefactoringProcessor(refactoringInfo);
	RenameRefactoring renameRefactoring = new RenameRefactoring(refactoringProcessor);
	RenameRefactoringWizard wizard = new RenameRefactoringWizard(renameRefactoring, refactoringInfo);
	
	RefactoringWizardOpenOperation op 
      = new RefactoringWizardOpenOperation( wizard );
    try {
      String titleForFailedChecks = ""; //$NON-NLS-1$
      op.run( HandlerUtil.getActiveShell(event), titleForFailedChecks );
    } catch( final InterruptedException irex ) {
    }
    
	return null;
}
 
Example 8
Source Project: CppStyle   File: CpplintCheckSettings.java    License: MIT License 5 votes vote down vote up
public static String getCpplintRoot(IFile file) {
	IProject project = file.getProject();
	String rootSpec;
	try {
		rootSpec = project.getPersistentProperty(new QualifiedName("", CppStyleConstants.CPPLINT_PROJECT_ROOT));

		if (rootSpec == null || rootSpec.isEmpty()) {
			return null;
		}
	} catch (CoreException e) {
		return null;
	}

	String rootVc = getVersionControlRoot(file);

	if (rootVc == null) {
		return null;
	}

	String relative = new File(rootVc).toURI().relativize(new File(rootSpec).toURI()).getPath();

	if (relative.endsWith("" + Path.SEPARATOR)) {
		return relative.substring(0, relative.length() - 1);
	}

	return relative;
}
 
Example 9
public void selectionChanged(IAction action, ISelection selection) {
  // Reset our old initial selections
  project = null;
  clientBundleType = null;
  List<IFile> selectedFiles = new ArrayList<IFile>();

  if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
    IStructuredSelection structuredSelection = (IStructuredSelection) selection;
    Iterator<?> iter = structuredSelection.iterator();
    while (iter.hasNext()) {
      Object element = iter.next();

      IFile file = AdapterUtilities.getAdapter(element, IFile.class);
      if (file != null) {
        // Set initial project if it's not already set
        if (project == null) {
          project = file.getProject();
        }

        // Try to set the initial ClientBundle type if it's not already set
        if (clientBundleType == null) {
          clientBundleType = findFirstTopLevelClientBundleType(file);
          if (clientBundleType != null) {
            // Ensure that initial project is the one containing the initial
            // ClientBundle type
            project = clientBundleType.getJavaProject().getProject();
          }
        }

        // If the file looks like a ClientBundle resource, add it
        if (ClientBundleResource.isProbableClientBundleResource(file)) {
          selectedFiles.add(file);
        }
      }
    }
  }
  files = selectedFiles.toArray(new IFile[0]);
}
 
Example 10
protected Index getIndex()
{
	// Now try and resolve the value as a URI...
	IEditorInput input = getEditorInput();
	// TODO What about IFileStoreEditorInputs? IURIEditorInputs?
	if (input instanceof IFileEditorInput)
	{
		IFile file = ((IFileEditorInput) input).getFile();
		IProject project = file.getProject();
		return getIndexManager().getIndex(project.getLocationURI());
	}
	return null;
}
 
Example 11
public String initHandle(URI uri) {
	if (!uri.isPlatform())
		return null;
	final IFile file = getWorkspaceRoot().getFile(new Path(uri.toPlatformString(true)));
	if (file == null) {
		return null;
	}
	final IProject project = file.getProject();
	return project.getName();
}
 
Example 12
Source Project: xds-ide   File: ParseTask.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public ParseTask(Collection<IFile> files,
		boolean isReportParseErrors,
		boolean isNeedModulaAst, boolean isParseDualModule,
		boolean isForce, boolean isParseImportSection) {
	IFile firstIFile = files.iterator().next();
	this.buildSettings = BuildSettingsCache.createBuildSettings(firstIFile);
	this.project = firstIFile.getProject();
	this.files = ResourceUtils.convertIFilesToFileStores(files);
	this.isReportParseErrors = isReportParseErrors;
	this.isNeedModulaAst = isNeedModulaAst;
	this.isParseDualModule = isParseDualModule;
	this.isForce = isForce;
	this.isParseImportSection = isParseImportSection;
}
 
Example 13
@Override
public void launch(IEditorPart editor, String mode) {
	IFile file = ResourceUtil.getFile(editor.getEditorInput());
	if (file != null) {
		IProject project = file.getProject();
		launch(project);
	}
	else{
		showEmptyError("Unable to determine the project to launch for from the editor.");
	}
}
 
Example 14
public IProject getProject() {
  // If we already have a project selected, return it
  if (selectedProject != null) {
    return selectedProject;
  }

  // Otherwise, if there's only one project, return it
  IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
  if (projects.length == 1) {
    return projects[0];
  }

  // Finally, if nothing is selected, try to figure out the selected project
  // based on the active editor
  IWorkbenchPage activePage = window.getActivePage();
  if (activePage != null) {
    IEditorPart editor = window.getActivePage().getActiveEditor();
    if (editor != null) {
      IFile input = ResourceUtils.getEditorInput(editor);
      // can return null if the open editor isn't backed by an IFile
      if (input != null) {
        return input.getProject();
      }
    }
  }

  // Couldn't find any project
  return null;
}
 
Example 15
Source Project: erflute   File: AbstractExportAction.java    License: Apache License 2.0 5 votes vote down vote up
protected String getSaveDirPath(IEditorPart editorPart, GraphicalViewer viewer) {
    final IFile file = ((IFileEditorInput) editorPart.getEditorInput()).getFile();
    final DirectoryDialog directoryDialog = new DirectoryDialog(editorPart.getEditorSite().getShell(), SWT.SAVE);
    final IProject project = file.getProject();
    directoryDialog.setFilterPath(project.getLocation().toString());
    return directoryDialog.open();
}
 
Example 16
@Override
public boolean canBuild(URI uri, IStorage storage) {
	if (storage instanceof IFile) {
		IFile file = (IFile) storage;
		IProject project = file.getProject();
		IJavaProject javaProject = JavaCore.create(project);
		return isInSourceFolder(javaProject, file);
	}
	// everything non local shouldn't be indexed at all, as we are going to link against Java.
	return false;
}
 
Example 17
Source Project: cppcheclipse   File: Checker.java    License: Apache License 2.0 5 votes vote down vote up
public void addFile(IFile file) throws CoreException {
	if (suppressionProfile.isFileSuppressed(file.getLocation().toFile()))
		return;
	if (file.getProject() != project) {
		throw new IllegalArgumentException(
				"Only files within the project are valid");
	}
	problemReporter.deleteMarkers(file, true);
	files.add(file);
}
 
Example 18
Source Project: Pydev   File: PyUnitTestResult.java    License: Eclipse Public License 1.0 4 votes vote down vote up
public static ItemPointer getItemPointer(File file, String fileContents, String testPath) {
    SimpleNode testNode = null;
    if (fileContents != null) {
        SimpleNode node = FastDefinitionsParser.parse(fileContents, "", file);
        if (testPath != null && testPath.length() > 0) {
            testNode = NodeUtils.getNodeFromPath(node, testPath);
        }
    }

    ItemPointer itemPointer;
    if (testNode != null) {
        itemPointer = new ItemPointer(file, testNode);
    } else {
        //Ok, it's not defined directly here (it's probably in a superclass), so, let's go on and 
        //do an actual (more costly) find definition.
        try {
            PySourceLocatorBase locator = new PySourceLocatorBase();
            IFile workspaceFile = FindWorkspaceFiles.getWorkspaceFile(file, null);
            if (workspaceFile != null && workspaceFile.exists()) {
                IProject project = workspaceFile.getProject();
                if (project != null && project.exists()) {
                    PythonNature nature = PythonNature.getPythonNature(project);
                    String moduleName = nature.resolveModule(file);
                    if (moduleName != null) {
                        IModule mod = nature.getAstManager().getModule(moduleName, nature, true);
                        if (mod != null) {
                            ICompletionCache completionCache = new CompletionCache();
                            IDefinition[] definitions = mod.findDefinition(CompletionStateFactory
                                    .getEmptyCompletionState(testPath, nature, completionCache), -1, -1, nature);

                            if (definitions != null && definitions.length > 0) {
                                List<ItemPointer> pointers = new ArrayList<ItemPointer>();
                                PyRefactoringFindDefinition.getAsPointers(pointers, definitions);
                                if (pointers.size() > 0) {
                                    return pointers.get(0);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.log(e);
        }
        //if we couldn't actually get the definition line, at least open the file we had (although that may not really
        //be the place where it's defined if it's a test in a superclass).
        itemPointer = new ItemPointer(file);
    }
    return itemPointer;
}
 
Example 19
Source Project: ermaster-b   File: ImportFromFileAction.java    License: Apache License 2.0 4 votes vote down vote up
protected String getLoadFilePath(IEditorPart editorPart) {

		IFile file = ((IFileEditorInput) editorPart.getEditorInput()).getFile();

		FileDialog fileDialog = new FileDialog(editorPart.getEditorSite()
				.getShell(), SWT.OPEN);

		IProject project = file.getProject();

		fileDialog.setFilterPath(project.getLocation().toString());

		String[] filterExtensions = this.getFilterExtensions();
		fileDialog.setFilterExtensions(filterExtensions);

		return fileDialog.open();
	}
 
Example 20
/**
 * Returns the project containing the file indicated by a URI.
 *
 * @param uri
 *          URI containing path from which the project name is extracted
 * @param mapper
 *          class returning e.g. set of storages {@link IStorage} matching given URI; injected by concrete BuilderParticipant
 * @return project {@link IProject} associated with given URI
 */
public static IProject getProject(final URI uri, final IStorage2UriMapper mapper) {
  final IFile file = findFileStorage(uri, mapper);
  return file == null ? null : file.getProject();
}