Java Code Examples for org.eclipse.core.resources.IContainer#getFile()

The following examples show how to use org.eclipse.core.resources.IContainer#getFile() . 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: PyRenameResourceChange.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the destination folder and returns the created files.
 */
private IResource[] createDestination(IContainer destination) throws CoreException {
    ArrayList<IResource> lst = new ArrayList<IResource>();
    if (!destination.exists()) {
        //Create parent structure first
        IContainer parent = destination.getParent();
        lst.addAll(Arrays.asList(createDestination(parent)));

        IFolder folder = parent.getFolder(new Path(destination.getFullPath().lastSegment()));

        IFile file = destination.getFile(new Path("__init__.py"));

        folder.create(IResource.NONE, true, null);
        file.create(new ByteArrayInputStream(new byte[0]), IResource.NONE, null);

        //Add in the order to delete later (so, first file then folder).
        lst.add(file);
        lst.add(folder);
    }
    return lst.toArray(new IResource[lst.size()]);
}
 
Example 2
Source File: PerformanceTestProjectSetup.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public static IFile createFile(final String name, final IContainer container, final String content) {
	final IFile file = container.getFile(new Path(name));
	try {
		final InputStream stream = new ByteArrayInputStream(content.getBytes(file.getCharset()));
		if (file.exists()) {
			file.setContents(stream, true, true, null);
		}
		else {
			file.create(stream, true, null);
		}
		stream.close();
	}
	catch (final Exception e) {
		throw new RuntimeException(e);
	}
	return file;
}
 
Example 3
Source File: TypeScriptResourceUtil.java    From typescript.java with MIT License 6 votes vote down vote up
/**
 * 
 * @param emittedFilePath
 * @param baseDir
 * @param refresh
 * @param emittedFiles
 * @throws CoreException
 */
public static void refreshAndCollectEmittedFile(IPath emittedFilePath, IContainer baseDir, boolean refresh,
		List<IFile> emittedFiles) throws CoreException {
	IFile emittedFile = null;
	if (refresh) {
		// refresh emitted file *.js, *.js.map
		emittedFile = baseDir.getFile(emittedFilePath);
		refreshFile(emittedFile, true);
	}

	if (emittedFiles != null) {
		if (emittedFile == null && baseDir.exists(emittedFilePath)) {
			emittedFile = baseDir.getFile(emittedFilePath);
		}
		if (emittedFile != null) {
			emittedFiles.add(emittedFile);
		}
	}
}
 
Example 4
Source File: ProjectFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected IFile createFile(final String name, final IContainer container, final String content,
		final IProgressMonitor progressMonitor) {
	final IFile file = container.getFile(new Path(name));
	createRecursive(file.getParent());
	SubMonitor subMonitor = SubMonitor.convert(progressMonitor, 1);
	try {
		final InputStream stream = new ByteArrayInputStream(content.getBytes(file.getCharset()));
		if (file.exists()) {
			logger.debug("Overwriting content of '" + file.getFullPath() + "'");
			file.setContents(stream, true, true, subMonitor.newChild(1));
		} else {
			file.create(stream, true, subMonitor.newChild(1));
		}
		stream.close();
	} catch (final Exception e) {
		logger.error(e.getMessage(), e);
	} finally {
		subMonitor.done();
	}
	return file;
}
 
Example 5
Source File: JDTAwareEclipseResourceFileSystemAccess2.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Since sourceTraces are relative the URI has to be computed with the currentSource as context
 */
@Override
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 && source != 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();
}
 
Example 6
Source File: SyncFileChangeListener.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
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$
				}
			}
		}
	}
}
 
Example 7
Source File: GetFiles.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets an IFile inside a container given a path in the filesystem (resolves the full path of the container and
 * checks if the location given is under it).
 */
public static final IFile getFileInContainer(IPath location, IContainer container, boolean mustExist) {
    IPath containerLocation = container.getLocation();
    if (containerLocation != null) {
        if (containerLocation.isPrefixOf(location)) {
            int segmentsToRemove = containerLocation.segmentCount();
            IPath removingFirstSegments = location.removeFirstSegments(segmentsToRemove);
            if (removingFirstSegments.segmentCount() == 0) {
                //It's equal: as we want a file in the container, and the path to the file is equal to the
                //container, we have to return null (because it's equal to the container it cannot be a file).
                return null;
            }
            IFile file = container.getFile(removingFirstSegments);
            if (!mustExist || file.exists()) {
                return file;
            }
        }
    } else {
        if (container instanceof IProject) {
            Log.logInfo("Info: container: " + container + " has no associated location.");
        }
    }
    return null;
}
 
Example 8
Source File: AbstractWorkbenchTestCase.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a package structure below a source folder.
 */
protected IFile createPackageStructure(IContainer sourceFolder, String packageName, IProgressMonitor monitor)
        throws CoreException {
    IFile lastFile = null;
    if (sourceFolder == null) {
        return null;
    }
    IContainer parent = sourceFolder;
    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;
}
 
Example 9
Source File: CreateAPICloudProjectWizard.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private void createPictureResource(IContainer container,
		IProgressMonitor monitor) throws CoreException {
	final IFile icon57 = container
			.getFile(new Path("/icon/icon150x150.png"));
	icon57.create(
			this.getClass().getResourceAsStream("/icons/icon150x150.png"),
			true, monitor);

	final IFile launch640x960 = container.getFile(new Path(
			"/launch/launch1080x1920.png"));
	launch640x960.create(
			this.getClass().getResourceAsStream(
					"/icons/launch1080x1920.png"), true, monitor);
}
 
Example 10
Source File: ProjectCustomizer.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a file in a project with an InputStream for the content
 * 
 * @param container
 *          an IProject
 * @param fileName
 *          pathname relative to the project
 * @param is
 *          An inputStream for the the content
 * @param overrideContentIfExist
 *          if true, overrides existing file
 * @return a handle to the file (IFile)
 * @throws PearException
 *           If a problem occurs
 */
public static IFile createFile(IContainer container, String fileName, InputStream is,
        boolean overrideContentIfExist) throws PearException {
  try {
    createPearFolderStructure(container);
    // if we have a container
    if (container.exists()) {
      IFile newFile = container.getFile(new Path(fileName));

      // If the file does not exist, create with content, mark, and return
      if (!newFile.exists()) {
        newFile.create(is, false, null);
        return newFile;
      } else {
        if (overrideContentIfExist)
          newFile.setContents(is, true, true, null);
        // return what already exisited
        return newFile;
      }
    } else
      // return null as there is no container to place a file in
      return null;
  } catch (Throwable e) {
    PearException subEx = new PearException(fileName + " could not be created/saved properly.", e);
    throw subEx;
  }
}
 
Example 11
Source File: ResourceHelper.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * Retrieves a a resource from the project, creates a link if createNew is true and the file is not present 
 * TODO improve this, if the name is wrong
 * 
 * @param name full filename of the resource
 * @param project
 * @param createNew, a boolean flag indicating if the new link should be created if it does not exist
 */
public static IFile getLinkedFile(IContainer project, String name, boolean createNew)
{
    if (name == null || project == null)
    {
        return null;
    }
    IPath location = new Path(name);
    IFile file = project.getFile(new Path(location.lastSegment()));
    if (createNew)
    {
        if (!file.isLinked())
        {
            try
            {
                file.createLink(location, IResource.NONE, new NullProgressMonitor());
                return file;

            } catch (CoreException e)
            {
                Activator.getDefault().logError("Error creating resource link to " + name, e);
            }
        }
        if (file.exists())
        {
            return file;
        } else
        {
            return null;
        }
    }
    return file;
}
 
Example 12
Source File: CordovaProjectConfigurator.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean shouldBeAnEclipseProject(IContainer container, IProgressMonitor monitor) {
	// TODO share code with CanConvertToHybridTester
       boolean configExist = false;
       for(IPath path: PlatformConstants.CONFIG_PATHS){
           IFile config = container.getFile(path);
           if(config.exists()){
               configExist = true;
               break;
           }
       }
       IFolder wwwFile = container.getFolder(new Path(PlatformConstants.DIR_WWW));
       return configExist && wwwFile.exists();
}
 
Example 13
Source File: JavaProjectHelper.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Imports resources from <code>bundleSourcePath</code> to
 * <code>importTarget</code>.
 *
 * @param importTarget
 *            the parent container
 * @param bundleSourcePath
 *            the path to a folder containing resources
 *
 * @throws CoreException
 *             import failed
 * @throws IOException
 *             import failed
 */
public static void importResources(IContainer importTarget, Bundle bundle, String bundleSourcePath) throws CoreException,
        IOException {
    Enumeration<?> entryPaths = bundle.getEntryPaths(bundleSourcePath);
    while (entryPaths.hasMoreElements()) {
        String path = (String) entryPaths.nextElement();
        IPath name = new Path(path.substring(bundleSourcePath.length()));
        if (path.endsWith("/.svn/")) {
            continue; // Ignore SVN folders
        } else if (path.endsWith("/")) {
            IFolder folder = importTarget.getFolder(name);
            if (folder.exists()) {
                folder.delete(true, null);
            }
            folder.create(true, true, null);
            importResources(folder, bundle, path);
        } else {
            URL url = bundle.getEntry(path);
            IFile file = importTarget.getFile(name);
            if (!file.exists()) {
                file.create(url.openStream(), true, null);
            } else {
                file.setContents(url.openStream(), true, false, null);
            }
        }
    }
}
 
Example 14
Source File: NpmLaunchShortcut.java    From wildwebdeveloper with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IResource getLaunchableResource(IContainer container) {
	if (container != null && container.getFile(new Path(PACKAGE_JSON)).exists()) {
		return container.getFile(new Path(PACKAGE_JSON));
	}
	return null;
}
 
Example 15
Source File: AbstractFSSynchronizationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void testDeleteDeletedDerivedResource(IContainer output) {
	try {
		File outputDirectory = output.getLocation().toFile();
		int expectedSize = 0;
		if (outputDirectory.exists()) {
			expectedSize = outputDirectory.list().length;
		}
		IFile sourceFile = createFile(project.getFile(("src/Foo" + F_EXT)).getFullPath(), "object Foo");
		build();
		Assert.assertNotEquals(expectedSize, outputDirectory.list().length);
		IFile file = output.getFile(new Path("Foo.txt"));
		file.refreshLocal(0, null);
		Assert.assertTrue(isSynchronized(file));
		new WorkspaceJob("file.delete") {
			@Override
			public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
				Assert.assertTrue(file.getLocation().toFile().delete());
				Assert.assertFalse(isSynchronized(file));
				return Status.OK_STATUS;
			}
		}.run(monitor());
		sourceFile.delete(false, monitor());
		build();
		Assert.assertEquals(expectedSize, outputDirectory.list().length);
	} catch (CoreException e) {
		throw Exceptions.sneakyThrow(e);
	}
}
 
Example 16
Source File: AbstractFSSynchronizationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void testDeleteUpdatedDerivedResource(IContainer output) {
	try {
		File outputDirectory = output.getLocation().toFile();
		final int expectedSize;
		if (outputDirectory.exists()) {
			expectedSize = outputDirectory.list().length;
		} else {
			expectedSize = 0;
		}
		IFile sourceFile = createFile(project.getFile(("src/Foo" + F_EXT)).getFullPath(), "object Foo");
		build();
		Assert.assertNotEquals(expectedSize, outputDirectory.list().length);
		IFile file = output.getFile(new Path("Foo.txt"));
		file.setLocalTimeStamp(1L);
		new WorkspaceJob("file.setContent") {
			@Override
			public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
				setContent(file.getLocation().toFile(), "Lalala");
				Assert.assertFalse(isSynchronized(file));
				return Status.OK_STATUS;
			}
		}.run(monitor());
		sourceFile.delete(false, monitor());
		build();
		Assert.assertEquals(expectedSize, outputDirectory.list().length);
	} catch (CoreException e) {
		throw Exceptions.sneakyThrow(e);
	}
}
 
Example 17
Source File: AbstractNewDocumentOutputPart.java    From depan with Apache License 2.0 5 votes vote down vote up
@Override
public IFile getOutputFile() throws CoreException {
  IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
  IResource resource = root.findMember(new Path(getContainerName()));
  if (!resource.exists() || !(resource instanceof IContainer)) {
    throwCoreException(
        "Container \"" + getContainerName() + "\" does not exist.");
  }

  IContainer container = (IContainer) resource;
  final IFile file = container.getFile(new Path(getFilename()));
  return file;
}
 
Example 18
Source File: NodeListEditor.java    From depan with Apache License 2.0 5 votes vote down vote up
private IFile getSaveAsFile() {
  IFile infoFile = getInputFile();
  if (null != infoFile) {
    return infoFile;
  }

  IContainer parent = nodeListInfo.getReferenceLocation().getParent();
  String filebase = baseName + '.' + NodeListDocument.EXTENSION;
  String filename = PlatformTools.guessNewFilename(
      parent, filebase, 1, 10);

  IPath filePath = Path.fromOSString(filename);
  return parent.getFile(filePath);
}
 
Example 19
Source File: AppEnginePropertyTester.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Expected value is ignored.
 * 
 * Considers as available for the run a container of a project with the GOOGLE_APP_ENGINE variable
 * declared in it and has a app.yaml or app.yml under it.
 */
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
    IContainer container = CustomizationCommons.getContainerFromObject(receiver);
    if (container == null) {
        return false;
    }

    IPythonPathNature nature = CustomizationCommons.getPythonPathNatureFromObject(receiver);
    if (nature == null) {
        return false;
    }

    //dev_appserver.py [options] <application root>
    //
    //Application root must be the path to the application to run in this server.
    //Must contain a valid app.yaml or app.yml file.
    IFile file = container.getFile(new Path("app.yaml"));
    if (file == null || !file.exists()) {
        file = container.getFile(new Path("app.yml"));
        if (file == null || !file.exists()) {
            return false;
        }
    }

    try {
        Map<String, String> variableSubstitution = nature.getVariableSubstitution();
        //Only consider a google app engine a project that has a google app engine variable!
        if (variableSubstitution != null
                && variableSubstitution.containsKey(AppEngineConstants.GOOGLE_APP_ENGINE_VARIABLE)) {
            return true;
        }
    } catch (Exception e) {
        Log.log(e);
    }

    return false;
}
 
Example 20
Source File: FileSystemAccessWithoutTraceFileSupport.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected IFile getFile(String fileName, String outputName, IProgressMonitor progressMonitor) {
	OutputConfiguration configuration = getOutputConfig(outputName);
	IContainer container = getContainer(configuration);
	if (container != null) {
		// no need to refresh again - it was already done in
		// org.eclipse.n4js.ui.building.N4JSBuilderParticipant#refreshOutputFolders
		// not a life changer, but shaves off approx 5% from the build time and progress monitor flickering is
		// reduced
		return container.getFile(new Path(fileName));
	}
	return null;
}