下面列出了org.eclipse.ui.dialogs.ISelectionStatusValidator#org.eclipse.core.resources.IContainer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static ILaunch startDiagnostics(String connectionName, String conid, boolean includeEclipseWorkspace, boolean includeProjectInfo, IProgressMonitor monitor) throws IOException, CoreException {
List<String> options = new ArrayList<String>();
options.add(CLIUtil.CON_ID_OPTION);
options.add(conid);
if (includeEclipseWorkspace) {
options.add(ECLIPSE_WORKSPACE_OPTION);
options.add(ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString());
}
if (includeProjectInfo) {
options.add(PROJECTS_OPTION);
}
List<String> command = CLIUtil.getCWCTLCommandList(null, DIAGNOSTICS_COLLECT_CMD, options.toArray(new String[options.size()]), null);
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(UtilityLaunchConfigDelegate.LAUNCH_CONFIG_ID);
ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance((IContainer) null, connectionName);
workingCopy.setAttribute(UtilityLaunchConfigDelegate.TITLE_ATTR, Messages.UtilGenDiagnosticsTitle);
workingCopy.setAttribute(UtilityLaunchConfigDelegate.COMMAND_ATTR, command);
ILaunchConfiguration launchConfig = workingCopy.doSave();
return launchConfig.launch(ILaunchManager.RUN_MODE, monitor);
}
/**
* Prompts the user to rename a trace
*
* @param element the conflicting element
* @return the new name to use or null if rename is canceled
*/
private static String promptRename(ITmfProjectModelElement element) {
MessageBox mb = new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.ICON_QUESTION | SWT.CANCEL | SWT.OK);
mb.setText(Messages.DropAdapterAssistant_RenameTraceTitle);
mb.setMessage(NLS.bind(Messages.DropAdapterAssistant_RenameTraceMessage, element.getName()));
if (mb.open() != SWT.OK) {
return null;
}
IContainer folder = element.getResource().getParent();
int i = 2;
while (true) {
String name = element.getName() + '(' + Integer.toString(i++) + ')';
IResource resource = folder.findMember(name);
if (resource == null) {
return name;
}
}
}
private static ResourceTraversal[] getPackageFragmentTraversals(IPackageFragment pack) throws CoreException {
ArrayList<ResourceTraversal> res= new ArrayList<ResourceTraversal>();
IContainer container= (IContainer)pack.getResource();
if (container != null) {
res.add(new ResourceTraversal(new IResource[] { container }, IResource.DEPTH_ONE, 0));
if (pack.exists()) { // folder may not exist any more, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=269167
Object[] nonJavaResources= pack.getNonJavaResources();
for (int i= 0; i < nonJavaResources.length; i++) {
Object resource= nonJavaResources[i];
if (resource instanceof IFolder) {
res.add(new ResourceTraversal(new IResource[] { (IResource)resource }, IResource.DEPTH_INFINITE, 0));
}
}
}
}
return res.toArray(new ResourceTraversal[res.size()]);
}
protected void handleSVNDir(IContainer svnDir, int kind) {
if((kind & IResourceDelta.ALL_WITH_PHANTOMS)!=0) {
if(kind==IResourceDelta.ADDED) {
// should this dir be made team-private? If it contains Entries then yes!
IFile entriesFile = svnDir.getFile(new Path(SVNConstants.SVN_ENTRIES));
if (entriesFile.exists() && !svnDir.isTeamPrivateMember()) {
try {
svnDir.setTeamPrivateMember(true);
if(Policy.DEBUG_METAFILE_CHANGES) {
System.out.println("[svn] found a new SVN meta folder, marking as team-private: " + svnDir.getFullPath()); //$NON-NLS-1$
}
} catch(CoreException e) {
SVNProviderPlugin.log(SVNException.wrapException(svnDir, Policy.bind("SyncFileChangeListener.errorSettingTeamPrivateFlag"), e)); //$NON-NLS-1$
}
}
}
}
}
/**
* Find a handle to the index file of this project.
* @param project the current project
* @param source buildable resource inside project
* @return handle to index file or null if not found.
* Returns null also if the index file is older than the current output file
*/
private IResource findNomencl(IProject project, IResource source) {
IContainer srcDir = TexlipseProperties.getProjectSourceDir(project);
if (srcDir == null) {
srcDir = project;
}
String name = source.getName();
String nomenclName = name.substring(0, name.length() - source.getFileExtension().length()) + TexlipseProperties.INPUT_FORMAT_NOMENCL;
IResource idxFile = srcDir.findMember(nomenclName);
if (idxFile == null) {
return null;
}
IResource outFile = TexlipseProperties.getProjectOutputFile(project);
if (outFile.getLocalTimeStamp() > idxFile.getLocalTimeStamp()) {
return null;
}
return idxFile;
}
private void confirmPackageFragmentRootOverwritting(IConfirmQuery skipQuery, IConfirmQuery overwriteQuery) {
List<IPackageFragmentRoot> toNotOverwrite= new ArrayList<IPackageFragmentRoot>(1);
for (int i= 0; i < fRoots.length; i++) {
IPackageFragmentRoot root= fRoots[i];
if (canOverwrite(root)) {
if (root.getResource() instanceof IContainer) {
if (!skip(JavaElementLabels.getElementLabel(root, JavaElementLabels.ALL_DEFAULT), skipQuery))
toNotOverwrite.add(root);
} else {
if (!overwrite(root.getResource(), overwriteQuery))
toNotOverwrite.add(root);
}
}
}
IPackageFragmentRoot[] roots= toNotOverwrite.toArray(new IPackageFragmentRoot[toNotOverwrite.size()]);
fRoots= ArrayTypeConverter.toPackageFragmentRootArray(ReorgUtils.setMinus(fRoots, roots));
}
private static ResourceTraversal[] getRemotePackageFragmentTraversals(IPackageFragment pack, RemoteResourceMappingContext context, IProgressMonitor monitor) throws CoreException {
ArrayList<ResourceTraversal> res= new ArrayList<>();
IContainer container= (IContainer)pack.getResource();
if (container != null) {
res.add(new ResourceTraversal(new IResource[] {container}, IResource.DEPTH_ONE, 0));
IResource[] remoteMembers= context.fetchRemoteMembers(container, monitor);
if (remoteMembers == null) {
remoteMembers= context.fetchMembers(container, monitor);
}
if (remoteMembers != null) {
for (int i= 0; i < remoteMembers.length; i++) {
IResource member= remoteMembers[i];
if (member instanceof IFolder
&& JavaConventionsUtil.validatePackageName(member.getName(), pack).getSeverity() == IStatus.ERROR) {
res.add(new ResourceTraversal(new IResource[] { member }, IResource.DEPTH_INFINITE, 0));
}
}
}
}
return res.toArray(new ResourceTraversal[res.size()]);
}
/**
* Can be used to announce that a builder participant is done with this file system access and all potentially
* recorded trace information should be persisted.
*
* @param generatorName
* the name of the generator.
* @since 2.3
*/
public void flushSourceTraces(String generatorName) throws CoreException {
Multimap<SourceRelativeURI, IPath> sourceTraces = getSourceTraces();
if (sourceTraces != null) {
Set<SourceRelativeURI> keys = sourceTraces.keySet();
String source = getCurrentSource();
IContainer container = Strings.isEmpty(source) ? getProject() : getProject().getFolder(source);
for (SourceRelativeURI uri : keys) {
if (uri != null) {
Collection<IPath> paths = sourceTraces.get(uri);
IFile sourceFile = container.getFile(new Path(uri.getURI().path()));
if (sourceFile.exists()) {
IPath[] tracePathArray = paths.toArray(new IPath[paths.size()]);
getTraceMarkers().installMarker(sourceFile, generatorName, tracePathArray);
}
}
}
}
resetSourceTraces();
}
private void exportOutputFolders(IProgressMonitor progressMonitor, Set<IJavaProject> javaProjects) throws InterruptedException {
if (javaProjects == null)
return;
Iterator<IJavaProject> iter= javaProjects.iterator();
while (iter.hasNext()) {
IJavaProject javaProject= iter.next();
IContainer[] outputContainers;
try {
outputContainers= getOutputContainers(javaProject);
} catch (CoreException ex) {
addToStatus(ex);
continue;
}
for (int i= 0; i < outputContainers.length; i++)
exportResource(progressMonitor, outputContainers[i], outputContainers[i].getFullPath().segmentCount());
}
}
private void compile(IFile tsConfigFile, CompilerOptions tsconfigOptions, List<IFile> tsFiles, boolean buildOnSave)
throws TypeScriptException, CoreException {
IContainer container = tsConfigFile.getParent();
IDETypeScriptCompilerReporter reporter = new IDETypeScriptCompilerReporter(container, listEmittedFiles,
!buildOnSave ? tsFiles : null);
CompilerOptions options = createOptions(tsconfigOptions, buildOnSave, listEmittedFiles);
// compile ts files to *.js, *.js.map files
super.execute(container.getLocation().toFile(), options, reporter.getFileNames(), reporter);
// refresh *.js, *.js.map which have been generated with tsc.
reporter.refreshEmittedFiles();
// check the given list of ts files are the same than tsc
// --listFiles
for (IFile tsFile : tsFiles) {
if (!reporter.getFilesToRefresh().contains(tsFile)) {
addCompilationContextMarkerError(tsFile, tsConfigFile);
}
}
}
/** */
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);
}
}
/**
* Determines the Resource which should be shown. Respects partial builds.
* @return
* @throws CoreException
*/
public static IResource getOuputResource(IProject project) throws CoreException {
String outFileName = TexlipseProperties.getOutputFileName(project);
if (outFileName == null || outFileName.length() == 0) {
throw new CoreException(TexlipsePlugin.stat("Empty output file name."));
}
// find out the directory where the file should be
IContainer outputDir = null;
// String fmtProp = TexlipseProperties.getProjectProperty(project,
// TexlipseProperties.OUTPUT_FORMAT);
// if (registry.getFormat().equals(fmtProp)) {
outputDir = TexlipseProperties.getProjectOutputDir(project);
/* } else {
String base = outFileName.substring(0, outFileName.lastIndexOf('.') + 1);
outFileName = base + registry.getFormat();
outputDir = TexlipseProperties.getProjectTempDir(project);
}*/
if (outputDir == null) {
outputDir = project;
}
IResource resource = outputDir.findMember(outFileName);
return resource != null ? resource : project.getFile(outFileName);
}
/**
* Determines if the listed item is a file or a folder.
*
* @param file
* @param monitor
* @return
* @throws CoreException
*/
private static boolean isFolder(IFileStore file, IProgressMonitor monitor) throws CoreException
{
// if we are an IContainer, folder == true;
// if we are an IFile, folder == false
// if neither, then check info for isDirectory()
IResource resource = (IResource) file.getAdapter(IResource.class);
if (resource instanceof IContainer)
{
return true;
}
if (!(resource instanceof IFile) && file.fetchInfo(EFS.NONE, monitor).isDirectory())
{
return true;
}
return false;
}
/**
* Converts a {@link RunConfiguration} to an {@link ILaunchConfiguration}. Will throw a {@link WrappedException} in
* case of error.
*
* @see RunConfiguration#readPersistentValues()
*/
public ILaunchConfiguration toLaunchConfiguration(ILaunchConfigurationType type, RunConfiguration runConfig) {
try {
final ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager()
.getLaunchConfigurations(type);
for (ILaunchConfiguration config : configs) {
if (equals(runConfig, config))
return config;
}
final IContainer container = null;
final ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(container, runConfig.getName());
workingCopy.setAttributes(runConfig.readPersistentValues());
return workingCopy.doSave();
} catch (Exception e) {
throw new WrappedException("could not convert N4JS RunConfiguration to Eclipse ILaunchConfiguration", e);
}
}
/**
* Create an App Engine configuration file in the appropriate location for the project.
*
* @param project the hosting project
* @param relativePath the path of the file relative to the configuration location
* @param contents the content for the file
* @param overwrite if {@code true} then overwrite the file if it exists
*/
public static IFile createConfigurationFile(
IProject project,
IPath relativePath,
InputStream contents,
boolean overwrite,
IProgressMonitor monitor)
throws CoreException {
IFolder appengineFolder = project.getFolder(DEFAULT_CONFIGURATION_FILE_LOCATION);
if (appengineFolder != null && appengineFolder.exists()) {
IFile destination = appengineFolder.getFile(relativePath);
if (!destination.exists()) {
IContainer parent = destination.getParent();
ResourceUtils.createFolders(parent, monitor);
destination.create(contents, true, monitor);
} else if (overwrite) {
destination.setContents(contents, IResource.FORCE, monitor);
}
return destination;
}
return WebProjectUtil.createFileInWebInf(project, relativePath, contents, overwrite, monitor);
}
/**
* Show a dialog that lets the user select a working directory from
* the workspace
*/
private void handleWorkspaceDirBrowseButtonSelected() {
IContainer currentContainer = getContainer();
if (currentContainer == null) {
currentContainer = ResourcesPlugin.getWorkspace().getRoot();
}
ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), currentContainer, false,
"Select a workspace relative working directory");
dialog.showClosedProjects(false);
dialog.open();
Object[] results = dialog.getResult();
if ((results != null) && (results.length > 0) && (results[0] instanceof IPath)) {
IPath path = (IPath) results[0];
String containerName = path.makeRelative().toString();
setOtherWorkingDirectoryText("${workspace_loc:" + containerName + "}"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
@Override
public Change createChange(IProgressMonitor pm, INewNameQueries newNameQueries) throws JavaModelException {
NewNameProposer nameProposer= new NewNameProposer();
IPackageFragment[] fragments= getPackages();
pm.beginTask("", fragments.length); //$NON-NLS-1$
CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_copy_package);
composite.markAsSynthetic();
IPackageFragmentRoot root= getDestinationAsPackageFragmentRoot();
for (int i= 0; i < fragments.length; i++) {
if (root == null) {
composite.add(createChange(fragments[i], (IContainer) getResourceDestination(), nameProposer, newNameQueries));
} else {
composite.add(createChange(fragments[i], root, nameProposer, newNameQueries));
}
pm.worked(1);
}
pm.done();
return composite;
}
/**
* Creates the complete package path given by the user (all filled with __init__)
* and returns the last __init__ module created.
*/
public static IFile createPackage(IProgressMonitor monitor, IContainer validatedSourceFolder, String packageName)
throws CoreException {
IFile lastFile = null;
if (validatedSourceFolder == null) {
return null;
}
IContainer parent = validatedSourceFolder;
for (String packagePart : StringUtils.dotSplit(packageName)) {
IFolder folder = parent.getFolder(new Path(packagePart));
if (!folder.exists()) {
folder.create(true, true, monitor);
}
parent = folder;
IFile file = parent.getFile(new Path("__init__"
+ FileTypesPreferences.getDefaultDottedPythonExtension()));
if (!file.exists()) {
file.create(new ByteArrayInputStream(new byte[0]), true, monitor);
}
lastFile = file;
}
return lastFile;
}
public static ViewerFilter filterUIDArtifactChildren() {
return new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof IResource) {
IContainer parent = ((IResource) element).getParent();
if (parent != null) {
return parent.getParent() == null
|| (parent.getParent() != null && (!isAUIDFolder(parent.getParent(), "web_page") &&
!isAUIDFolder(parent.getParent(), "web_widgets") &&
!isAUIDFolder(parent.getParent(), "web_fragments")));
}
}
return true;
}
};
}
@Test
public void testIsFolder() throws Exception {
IProject project = WorkspaceHelper.getProject(ProjectsManager.DEFAULT_PROJECT_NAME);
// Creating test folders and file using 'java.io.*' API (from the outside of the workspace)
File dir = new File(project.getLocation().toString(), "/src/org/eclipse/testIsFolder");
dir.mkdirs();
File file = new File(dir, "Test.java");
file.createNewFile();
// Accessing test folders and file using 'org.eclipse.core.resources.*' API (from inside of the workspace)
IContainer iFolder = project.getFolder("/src/org/eclipse/testIsFolder");
URI uriFolder = iFolder.getLocationURI();
IFile iFile = project.getFile("/src/org/eclipse/testIsFolder/Test.java");
URI uriFile = iFile.getLocationURI();
assertTrue(JDTUtils.isFolder(uriFolder.toString()));
assertEquals(JDTUtils.getFileOrFolder(uriFolder.toString()).getType(), IResource.FOLDER);
assertEquals(JDTUtils.getFileOrFolder(uriFile.toString()).getType(), IResource.FILE);
assertFalse(JDTUtils.isFolder(uriFile.toString()));
assertNotNull(JDTUtils.findFile(uriFile.toString()));
assertNotNull(JDTUtils.findFolder(uriFolder.toString()));
}
/**
* Performs a drop using the FileTransfer transfer type.
*/
private IStatus performFileDrop(final CommonDropAdapter anAdapter, Object data) {
final int currentOperation = anAdapter.getCurrentOperation();
MultiStatus problems = new MultiStatus(PlatformUI.PLUGIN_ID, 0,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_problemImporting, null);
mergeStatus(problems,
validateTarget(anAdapter.getCurrentTarget(), anAdapter
.getCurrentTransfer(), currentOperation));
final IContainer target = getActualTarget((IResource) anAdapter
.getCurrentTarget());
final String[] names = (String[]) data;
// Run the import operation asynchronously.
// Otherwise the drag source (e.g., Windows Explorer) will be blocked
// while the operation executes. Fixes bug 16478.
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
getShell().forceActive();
new CopyFilesAndFoldersOperation(getShell()).copyOrLinkFiles(names, target, currentOperation);
}
});
return problems;
}
/**
* The <code>CopyAction</code> implementation of this <code>SelectionListenerAction</code> method enables this
* action if one or more resources of compatible types are selected.
*/
@Override
protected boolean updateSelection(final IStructuredSelection selection) {
if (!super.updateSelection(selection)) { return false; }
if (getSelectedNonResources().size() > 0) { return false; }
final List<? extends IResource> selectedResources = getSelectedResources();
if (selectedResources.size() == 0) { return false; }
final boolean projSelected = selectionIsOfType(IResource.PROJECT);
final boolean fileFoldersSelected = selectionIsOfType(IResource.FILE | IResource.FOLDER);
if (!projSelected && !fileFoldersSelected) { return false; }
// selection must be homogeneous
if (projSelected && fileFoldersSelected) { return false; }
// must have a common parent
final IContainer firstParent = selectedResources.get(0).getParent();
if (firstParent == null) { return false; }
for (final IResource currentResource : selectedResources) {
if (!currentResource.getParent().equals(firstParent)) { return false; }
// resource location must exist
if (currentResource.getLocationURI() == null) { return false; }
}
return true;
}
public static IProject getEclipseProject(CodewindApplication app) {
IContainer[] containers = ResourcesPlugin.getWorkspace().getRoot().findContainersForLocationURI(new File(app.fullLocalPath.toOSString()).toURI());
for (IContainer container : containers) {
if (container instanceof IProject && ((IProject)container).isAccessible()) {
return (IProject)container;
}
}
return null;
}
public static IContainer findContainerFromWorkspace(String path) {
if (StringUtils.isEmpty(path)) {
return null;
}
IPath containerPath = new Path(path);
return findContainerFromWorkspace(containerPath);
}
/**
* Guess a likely container resource given the user's current selection.
*
* The implemented heuristic follows these lines:
* <ol>
* <li>If there is no selection and the workspace has only one project.
* guess the project.</li>
* <li>If the selection is a container, use that object.</li>
* <li>If the selection is a non-container resource,
* guess that resource's container.</li>
* </ol>
* In all other cases, return {@code null}.
*
* @param selection current user selection, or {@code null} for something
* based on the workspace context (e.g. a singleton project root in the
* workspace).
*
* @return best guess of user's intended container,
* or {@code null} if no reasonable guess can be made.
*/
public static IContainer guessContainer(ISelection selection) {
// If the selection is no help, and the workspace has only one
// project, use that.
Object obj = Selections.getFirstObject(selection);
if (obj == null) {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IProject[] projects = workspace.getRoot().getProjects();
if (null == projects) {
return null;
}
if (projects.length != 1) {
return null;
}
return projects[0];
}
// Multiple selections make it hard to guess the user's intent.
if (Selections.getObjects(selection).size() > 1) {
return null;
}
// A selected container is a good answer
if (obj instanceof IContainer) {
return (IContainer) obj;
}
// If the selected container is any other kind of resource,
// guess that the user meant that resource's container.
if (obj instanceof IResource) {
return ((IResource) obj).getParent();
}
// No reasonable guess for initial container
return null;
}
/**
* Creates the tree viewer.
*
* @param parent
* the parent composite
* @return the tree viewer
*/
protected CheckboxTreeViewer createTreeViewer(Composite parent) {
mViewer = new CheckboxTreeViewer(parent, SWT.BORDER);
mViewer.setContentProvider(mContentProvider);
mViewer.setLabelProvider(mLabelProvider);
mViewer.addCheckStateListener(new ICheckStateListener() {
@Override
public void checkStateChanged(CheckStateChangedEvent event) {
IContainer element = (IContainer) event.getElement();
if (isRecursivelyExcludeSubTree() && !isGrayed(element)) {
setSubElementsGrayedChecked(element, event.getChecked());
} else if (isRecursivelyExcludeSubTree() && isGrayed(element)) {
mViewer.setGrayChecked(element, true);
}
}
});
mViewer.setInput(mInput);
mViewer.setCheckedElements(getInitialElementSelections().toArray());
adaptRecurseBehaviour();
if (mExpandedElements != null) {
mViewer.setExpandedElements(mExpandedElements);
}
return mViewer;
}
private String formatResourceMessage(IResource element) {
IContainer parent= element.getParent();
if (parent != null && parent.getType() != IResource.ROOT)
return BasicElementLabels.getResourceName(element.getName()) + JavaElementLabels.CONCAT_STRING + BasicElementLabels.getPathLabel(parent.getFullPath(), false);
else
return BasicElementLabels.getResourceName(element.getName());
}
protected void refreshOutputFolders(IBuildContext ctx, Map<String, OutputConfiguration> outputConfigurations,
IProgressMonitor monitor) throws CoreException {
SubMonitor subMonitor = SubMonitor.convert(monitor, outputConfigurations.size());
for (OutputConfiguration config : outputConfigurations.values()) {
SubMonitor split = subMonitor.split(1);
final IProject project = ctx.getBuiltProject();
for (IContainer container : getOutputs(project, config)) {
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
sync(container, IResource.DEPTH_INFINITE, split);
}
}
}
/**
* Creates a new instance of the class.
*/
protected GotoResourceDialog(Shell parentShell, IContainer container,
int typesMask) {
super(parentShell, false, container, typesMask);
setTitle(WorkbenchNavigatorMessages.actions_GotoResourceDialog_GoToTitle);
PlatformUI.getWorkbench().getHelpSystem().setHelp(parentShell,
INavigatorHelpContextIds.GOTO_RESOURCE_DIALOG);
}
/**
* Determines if a resource is available on a project's classpath. This method searches both source paths and JAR/ZIP
* files.
*/
public static boolean isResourceOnClasspath(IJavaProject javaProject, IPath resourcePath) throws JavaModelException {
String pckg = JavaUtilities.getPackageNameFromPath(resourcePath.removeLastSegments(1));
String fileName = resourcePath.lastSegment();
for (IPackageFragment pckgFragment : JavaModelSearch.getPackageFragments(javaProject, pckg)) {
if (ClasspathResourceUtilities.isFileOnPackageFragment(fileName, pckgFragment)) {
return true;
}
}
// If the resource doesn't follow normal java naming convention for resources, such as /resources/folder-name/file-name.js
for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
IPackageFragment folderFragment = root.getPackageFragment(pckg);
IResource folder = folderFragment.getResource();
if (folder == null || !folder.exists() || !(folder instanceof IContainer)) {
continue;
}
IResource resource = ((IContainer) folder).findMember(fileName);
if (resource != null && resource.exists()) {
return true;
}
}
// Not there
return false;
}