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

The following examples show how to use org.eclipse.core.resources.IFile#getParent() . 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
private void createConfigFiles(IProject project, IProgressMonitor monitor) throws CoreException {
  SubMonitor subMonitor = SubMonitor.convert(monitor, 100);

  FlexDeployPreferences flexDeployPreferences = new FlexDeployPreferences(project);
  String appYamlPath = flexDeployPreferences.getAppYamlPath();
  IFile appYaml = project.getFile(appYamlPath);
  if (appYaml.exists()) {
    return;
  }

  IContainer appYamlParentFolder = appYaml.getParent();
  if (!appYamlParentFolder.exists()) {
    ResourceUtils.createFolders(appYamlParentFolder, subMonitor.newChild(5));
  }

  appYaml.create(new ByteArrayInputStream(new byte[0]), true, subMonitor.newChild(10));
  String configFileLocation = appYaml.getLocation().toString();
  Templates.createFileContent(
      configFileLocation, Templates.APP_YAML_TEMPLATE,
      Collections.<String, String>emptyMap());
  subMonitor.worked(55);

  appYaml.refreshLocal(IResource.DEPTH_ZERO, subMonitor.newChild(30));
}
 
Example 2
public static String getAbsoluteContainerFolderPathOf(final Resource r) {
	URI uri = r.getURI();
	if (uri.isFile()) {
		uri = uri.trimSegments(1);
		return uri.toFileString();
	} else if (uri.isPlatform()) {
		final IPath path = GamlResourceServices.getPathOf(r);
		final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		final IContainer folder = file.getParent();
		return folder.getLocation().toString();
	}
	return URI.decode(uri.toString());

	// final IPath fullPath = file.getLocation();
	// path = fullPath; // toOSString ?
	// if (path == null) { return null; }
	// return path.uptoSegment(path.segmentCount() - 1);
}
 
Example 3
@Test
public void testCreateWebInfFolder_dynamicWebProject() throws CoreException {
  IProject project = testProjectCreator
      .withFacets(JavaFacet.VERSION_1_7, WebFacetUtils.WEB_25).getProject();
  IFile webXml = WebProjectUtil.findInWebInf(project, new Path("web.xml"));
  assertNotNull(webXml);
  assertTrue(webXml.exists());
  IFolder webInfDir = (IFolder) webXml.getParent();

  // should be found alongside the web.xml
  IFolder libFolder = WebProjectUtil.createFolderInWebInf(project, new Path("lib"), null);
  assertNotNull(libFolder);
  assertTrue(libFolder.exists());
  assertEquals(webInfDir.getProjectRelativePath().append("lib").toString(),
      libFolder.getProjectRelativePath().toString());
}
 
Example 4
private boolean showFile(IFile file) {
  // Only show files on the project's classpath
  if (!javaProject.isOnClasspath(file)) {
    return false;
  }

  // Ignore files that are not likely to be bundled resources
  if (!ClientBundleResource.isProbableClientBundleResource(file)) {
    return false;
  }

  // Ignore files directly under the project (.project, .classpath)
  if (file.getParent() instanceof IProject) {
    return false;
  }

  return true;
}
 
Example 5
Source Project: gama   File: WrappedFile.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Object[] getFileChildren() {
	final IFile p = getResource();
	try {
		final IContainer folder = p.getParent();
		final List<WrappedFile> sub = new ArrayList<>();
		for (final IResource r : folder.members()) {
			if (r instanceof IFile && isSupport(p, (IFile) r)) {
				sub.add((WrappedFile) getManager().findWrappedInstanceOf(r));
			}
		}
		return sub.toArray();
	} catch (final CoreException e) {
		e.printStackTrace();
	}
	return VirtualContent.EMPTY;
}
 
Example 6
private boolean belongToRepositoryStore(final IRepositoryStore<?> store, final IFile file) {
    final IFolder parentFolder = store.getResource();
    if (parentFolder == null) {
        return false;
    }
    IContainer current = file.getParent();
    while (current != null && !parentFolder.equals(current)) {
        current = current.getParent();
    }
    return current != null && parentFolder.equals(current);
}
 
Example 7
Source Project: eclipse.jdt.ls   File: JDTUtils.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static boolean isFolder(String uriString) {
	IFile fakeFile = findFile(uriString); // This may return IFile even when uriString really describes a IContainer
	IContainer parent = fakeFile == null ? null : fakeFile.getParent();
	if (parent == null) {
		return false;
	}
	if (!parent.isSynchronized(DEPTH_ONE)) {
		try {
			parent.refreshLocal(DEPTH_ONE, null);
		} catch (CoreException e) {
			// Ignore
		}
	}
	return (parent.findMember(fakeFile.getName()) instanceof IFolder);
}
 
Example 8
/**
 * We will create a new module (file) here given the source folder and the package specified (which
 * are currently validated in the page) 
 * @param monitor 
 * @throws CoreException 
 */
@Override
protected IFile doCreateNew(IProgressMonitor monitor) throws CoreException {
    IContainer validatedSourceFolder = filePage.getValidatedSourceFolder();
    if (validatedSourceFolder == null) {
        return null;
    }
    IContainer validatedPackage = filePage.getValidatedPackage();
    if (validatedPackage == null) {
        String packageText = filePage.getPackageText();
        if (packageText == null) {
            Log.log("Package text not available");
            return null;
        }
        IFile packageInit = PythonPackageWizard.createPackage(monitor, validatedSourceFolder, packageText);
        if (packageInit == null) {
            Log.log("Package not created");
            return null;
        }
        validatedPackage = packageInit.getParent();
    }
    String validatedName = filePage.getValidatedName() + FileTypesPreferences.getDefaultDottedPythonExtension();

    IFile file = validatedPackage.getFile(new Path(validatedName));
    if (file.exists()) {
        Log.log("Module already exists.");
        return null;
    }
    file.create(new ByteArrayInputStream(new byte[0]), true, monitor);
    return file;
}
 
Example 9
public IFile newSource(final IJavaProject it, final String fileName, final String contents) {
  try {
    final IFile result = it.getProject().getFile(("src/" + fileName));
    IContainer parent = result.getParent();
    while ((!parent.exists())) {
      ((IFolder) parent).create(true, false, null);
    }
    StringInputStream _stringInputStream = new StringInputStream(contents);
    result.create(_stringInputStream, true, null);
    return result;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 10
@Override
public List<String> resolveValues(final TemplateVariable variable, final XtextTemplateContext templateContext) {
  final List<String> result = Lists.newArrayList();
  final IDocument document = templateContext.getDocument();
  final Object obj = variable.getVariableType().getParams().iterator().next();
  if (obj instanceof String) {
    final String variableName = (String) obj;
    final IXtextDocument xtextDocument = (IXtextDocument) document;
    final IFile file = xtextDocument.getAdapter(IFile.class);

    switch (variableName) {
    case "package": //$NON-NLS-1$
      if (document instanceof IXtextDocument && file != null && file.getParent() instanceof IFolder) {
        final IJavaProject javaProject = JavaCore.create(file.getProject());
        try {
          final IPackageFragment packageFragment = javaProject.findPackageFragment(file.getParent().getFullPath());
          result.add(packageFragment.getElementName());
        } catch (final JavaModelException e) {
          LOGGER.error("Could not determine package for file of given document"); //$NON-NLS-1$
        }
      }
      break;
    case "file": //$NON-NLS-1$
      final String fileName = file.getName();
      result.add(fileName.indexOf('.') > 0 ? fileName.substring(0, fileName.lastIndexOf('.')) : fileName);
    }
  }
  return Lists.newArrayList(Iterables.filter(result, Predicates.notNull()));
}
 
Example 11
/**
 * Gets the name of containing package.
 *
 * @param xtextDocument
 *          the xtext document
 * @return the name of containing package
 */
public String getNameOfContainingPackage(final IXtextDocument xtextDocument) {
  IFile file = xtextDocument.getAdapter(IFile.class);
  if (file != null && file.getParent() instanceof IFolder) {
    IJavaProject javaProject = JavaCore.create(file.getProject());
    try {
      IPackageFragment myFragment = javaProject.findPackageFragment(file.getParent().getFullPath());
      return myFragment.getElementName();
    } catch (JavaModelException e) {
      LOGGER.error("Could not determine package for file of given document");
    }
  }
  return null;
}
 
Example 12
public List<IFile> getSupportFilesOf(final IFile f) {
	if (f == null) { return Collections.EMPTY_LIST; }
	if (!getContentTypeId(f).equals(SHAPEFILE_CT_ID)) { return Collections.EMPTY_LIST; }
	final IContainer c = f.getParent();
	final List<IFile> result = new ArrayList<>();
	try {
		for (final IResource r : c.members()) {
			if (r instanceof IFile && isSupport(f, (IFile) r)) {
				result.add((IFile) r);
			}
		}
	} catch (final CoreException e) {}
	return result;
}
 
Example 13
Source Project: typescript.java   File: TypeScriptResourceUtil.java    License: MIT License 5 votes vote down vote up
public static void refreshAndCollectEmittedFiles(IFile tsFile, IDETsconfigJson tsconfig, boolean refresh,
		List<IFile> emittedFiles) throws CoreException {
	IContainer baseDir = tsFile.getParent();
	// Set outDir with the folder of the ts file.
	IContainer outDir = tsFile.getParent();
	if (tsconfig != null) {
		// tsconfig.json exists and "outDir" is setted, set "outDir" with
		// the tsconfig.json/compilerOption/outDir
		IContainer configOutDir = tsconfig.getOutDir();
		if (configOutDir != null && configOutDir.exists()) {
			outDir = configOutDir;
		}
	}

	IPath tsFileNamePath = WorkbenchResourceUtil.getRelativePath(tsFile, baseDir).removeFileExtension();
	// Refresh *.js file
	IPath jsFilePath = tsFileNamePath.addFileExtension(FileUtils.JS_EXTENSION);
	refreshAndCollectEmittedFile(jsFilePath, outDir, refresh, emittedFiles);
	// Refresh *.js.map file
	IPath jsMapFilePath = tsFileNamePath.addFileExtension(FileUtils.JS_EXTENSION)
			.addFileExtension(FileUtils.MAP_EXTENSION);
	refreshAndCollectEmittedFile(jsMapFilePath, outDir, refresh, emittedFiles);
	// Refresh ts file
	if (refresh) {
		refreshFile(tsFile, false);
	}
}
 
Example 14
/**
 * Refresh emitted files *.js , *.js.map
 * 
 * @throws CoreException
 */
public void refreshEmittedFiles() throws CoreException {
	// refresh *.js, *.js.map files
	for (IFile emittedFile : emittedFiles) {
		TypeScriptResourceUtil.refreshFile(emittedFile, true);
	}
	for (IFile tsFile : getFilesToRefresh()) {
		try {
			TypeScriptResourceUtil.refreshAndCollectEmittedFiles(tsFile, tsconfig, true, null);
		} catch (CoreException e) {
			Trace.trace(Trace.SEVERE, "Error while tsc compilation when ts file is refreshed", e);
		}
	}
	// refresh outFile if tsconfig.json defines it.
	if (tsconfig != null) {
		// Refresh *.js outFile
		IFile outFile = tsconfig.getOutFile();
		if (outFile != null) {
			TypeScriptResourceUtil.refreshFile(outFile, true);
			// Refresh *.js.map outFile
			IContainer outDir = outFile.getParent();
			IPath mapFileNamePath = WorkbenchResourceUtil.getRelativePath(outFile, outDir)
					.addFileExtension(FileUtils.MAP_EXTENSION);
			TypeScriptResourceUtil.refreshAndCollectEmittedFile(mapFileNamePath, outDir, true, null);
		}
	}
}
 
Example 15
private void handleSelectionChange(Object selection) {
  if (selection instanceof IFile) {
    IFile file = (IFile) selection;
    String fileName = file.getName();
    IContainer rsrcContainer = file.getParent();

    containerText.setText(rsrcContainer.getFullPath().toString());
    fileText.setText(fileName);
  }
}
 
Example 16
/**
 * GWT Maven project will have a short name
 * @return the short name for module
 */
private String getShortName() {
  IFile file = (IFile) storage;
  IFolder moduleFolder = (IFolder) file.getParent();
  String shortName = WebAppProjectProperties.getGwtMavenModuleShortName(moduleFolder.getProject());
  return shortName;
}
 
Example 17
/**
 * Get the gwt maven2 module name
 * @return module name
 */
private String getModuleNameGwtMaven2() {
  IFile file = (IFile) storage;
  IFolder moduleFolder = (IFolder) file.getParent();
  String moduleName = WebAppProjectProperties.getGwtMavenModuleName(moduleFolder.getProject());
  moduleName = moduleName.replaceAll(".*\\.(.*)", "$1");
  return moduleName;
}
 
Example 18
/**
 * 获取所有包括分析文件的文件夹(直接包括或间接包括都可)
 * @param rootFolder	起始文件夹
 * @param allFolderList	承装所有文件夹的集合
 */
public void getAllFolder(IContainer rootFolder, List<IContainer> allFolderList){
	
	if (allFolderList == null) {
		allFolderList = new LinkedList<IContainer>();
	}
	IResource[] members;
	try {
		members = rootFolder.members();
		for (IResource resource : members) {
			if (resource instanceof IContainer) {
				boolean faIFilesExsit = false;
				
				//循环判断所有的要分析的文件,检查当前容器下是否包括要分析的文件
				for (int fileIndex = 0; fileIndex < model.getAnalysisIFileList().size(); fileIndex++) {
					IFile ifile = model.getAnalysisIFileList().get(fileIndex);
					
					IContainer iFileParent = ifile.getParent();
					while (iFileParent != null ) {
						if (iFileParent.equals((IContainer)resource) ) {
							faIFilesExsit = true;
							break;
						}else {
							iFileParent = iFileParent.getParent();
						}
					}
					
					//如果当前容器下存在分析的文件,将该容器加载到缓存中,并停止循环其他分析的文件
					if (faIFilesExsit) {
						allFolderList.add((IContainer)resource);
						break;
					}
				}
				
				getAllFolder((IContainer)resource, allFolderList);
			}
		}
	} catch (CoreException e) {
		LOGGER.error("", e);
		e.printStackTrace();
	}
}
 
Example 19
private IFile getRenamedAbsoluteFile(IFile iFile, String newName) {
	IContainer container = iFile.getParent();
	IFile renamedIFile = container.getFile(new Path(newName));
	return renamedIFile;
}
 
Example 20
public void execute(IFile programFile) throws IOException, InterruptedException {
	IContainer programContainer = programFile.getParent();
	if (!programContainer.isAccessible()) {
		throw new RuntimeException(
				"Test program container " + programContainer.getLocation().toOSString() + " inaccessible");
	}

	File directory = programContainer.getLocation().toFile();
	Process process = new ProcessBuilder(programFile.getLocation().toOSString()).redirectErrorStream(true)
			.directory(directory).start();
	BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

	boolean started = false;
	boolean running = false;
	StringBuilder message = new StringBuilder();
	String line;
	while ((line = reader.readLine()) != null) {
		if (line.startsWith("[====")) {
			if (started) {
				started = false;
				// Eat remaining input
				char[] buffer = new char[4096];
				while (reader.read(buffer) != -1);
				break;
			}
			started = true;
		} else {
			TestOutput testOutput = parseTestOutput(line);
			if (testOutput != null) {
				Description description = testOutput.toDescription();
				switch (testOutput.getStatus()) {
					case TestOutput.RUN :
						running = true;
						message.setLength(0);
						testStarted(description);
						break;
					case TestOutput.OK :
						running = false;
						testFinished(description);
						break;
					default :
						running = false;
						testFailed(description, message.toString());
						testFinished(description);
						break;
				}
			} else if (running) {
				message.append(line);
				message.append("\n");
			}
		}
	}

	process.waitFor();

	if (started) {
		throw new RuntimeException("Test quit unexpectedly (exit status " + process.exitValue() + "):\n" + message);
	}
}