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

The following examples show how to use org.eclipse.core.resources.IFile#create() . 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
@Test public void testFullBuildBigProjectWithRefeernceToJar() throws Exception {
	IJavaProject project = workspace.createJavaProject("foo");
	workspace.addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	IFile jarFile = project.getProject().getFile("my.jar");
	jarFile.create(jarInputStream(new TextFile("my/element"+F_EXT,"object ReferenceMe")), true, workspace.monitor());
	workspace.addJarToClasspath(project, jarFile);
	
	int NUM_FILES = 2000;
	IFile[] files = new IFile[NUM_FILES];
	StopWatch timer = new StopWatch();
	for (int i = 0; i < NUM_FILES; i++) {
		IFile file = folder.getFile("Test_" + i + "_" + F_EXT);
		files[i] = file;
		String contents = "object Foo" + i + " references ReferenceMe";
		file.create(new StringInputStream(contents), true, workspace.monitor());
	}
	logAndReset("Creating files", timer);
	workspace.build();
	logAndReset("Auto build", timer);
	IMarker[] iMarkers = folder.findMarkers(EValidator.MARKER, true, IResource.DEPTH_INFINITE);
	for (IMarker iMarker : iMarkers) {
		System.out.println(iMarker.getAttribute(IMarker.MESSAGE));
	}
	assertEquals(0,iMarkers.length);
}
 
Example 2
@Test
public void testNoOutputFolderCreation() throws Exception {
	OutputConfigurationProvider outputConfigurationProvider = new OutputConfigurationProvider() {
		@Override
		public Set<OutputConfiguration> getOutputConfigurations() {
			final Set<OutputConfiguration> result = super.getOutputConfigurations();
			OutputConfiguration configuration = result.iterator().next();
			configuration.setCreateOutputDirectory(false);
			return result;
		}
	};
	BuilderPreferenceAccess.Initializer initializer = new BuilderPreferenceAccess.Initializer();
	initializer.setOutputConfigurationProvider(outputConfigurationProvider);
	initializer.initialize(preferenceStoreAccess);

	IJavaProject project = createJavaProject("foo");
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	IFile file = folder.getFile("Foo" + F_EXT);
	file.create(new StringInputStream("object Foo"), true, monitor());
	build();
	final IFile generatedFile = project.getProject().getFile("./src-gen/Foo.txt");
	assertFalse(generatedFile.exists());
}
 
Example 3
Source Project: RADL   File: RadlCreator.java    License: Apache License 2.0 6 votes vote down vote up
public IFile createRadlFile(String folderName, String serviceName, IProgressMonitor monitor,
    IWorkspaceRoot root) throws CoreException {
  IFolder folder = root.getFolder(new Path(folderName));
  if (!folder.exists()) {
    ensureFolder(monitor, folder);
  }
  final IFile result = folder.getFile(serviceNameToFileName(serviceName));
  try (InputStream stream = getRadlSkeleton(serviceName)) {
    if (result.exists()) {
      result.setContents(stream, true, true, monitor);
    } else {
      result.create(stream, true, monitor);
    }
  } catch (IOException e) { // NOPMD EmptyCatchBlock
  }
  IProjectNature nature = new RadlNature();
  nature.setProject(folder.getProject());
  nature.configure();
  return result;
}
 
Example 4
@Test
public void testGetProject() throws CoreException {
  IProject project = dynamicWebProject.getProject();
  IFile file = project.getFile("testdata.xml");
  file.create(ValidationTestUtils.stringToInputStream(APPLICATION_XML), 0, null);

  IDocument document = ValidationTestUtils.getDocument(file);

  IncrementalHelper helper = new IncrementalHelper(document, project);
  IPath path = file.getFullPath();
  helper.setURI(path.toString());

  IProject testProject = XmlSourceValidator.getProject(helper);
  assertNotNull(testProject);
  assertEquals(project, testProject);
}
 
Example 5
@Test
public void testCSSFile() throws Exception {
	final IFile file = project.getFile("blah.css");
	file.create(new ByteArrayInputStream("ERROR".getBytes()), true, null);
	ITextEditor editor = (ITextEditor) IDE
			.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file);
	editor.getDocumentProvider().getDocument(editor.getEditorInput()).set("FAIL");
	assertTrue("Diagnostic not published", new DisplayHelper() {
		@Override
		protected boolean condition() {
			try {
				return file.findMarkers("org.eclipse.lsp4e.diagnostic", true, IResource.DEPTH_ZERO).length != 0;
			} catch (CoreException e) {
				return false;
			}
		}
	}.waitForCondition(PlatformUI.getWorkbench().getDisplay(), 5000));
}
 
Example 6
/**
 * Gets file handle for the given project (initialized if it doesn't exist).
 *
 * @param project
 *          the project
 * @param filename
 *          the filename
 * @return the existing file
 * @throws CoreException
 *           the core exception
 */
public IFile getHelpFile(final IProject project, final String filename) throws CoreException {
  final List<String> splittedPath = Lists.newArrayList(Splitter.on('/').split(filename));
  for (final String seg : splittedPath) {
    if (splittedPath.indexOf(seg) != splittedPath.size() - 1) {
      IFolder folder = project.getFolder(seg);
      if (!folder.exists()) {
        folder.create(true, true, null);
      }
    }
  }
  IFile file = project.getFile(filename);
  if (!file.exists()) {
    file.create(new ByteArrayInputStream("".getBytes()), true, null);
  }
  return file;
}
 
Example 7
@Test
public void testFalseDetectionAsKubernetes() throws Exception {
	IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject("p");
	p.create(new NullProgressMonitor());
	p.open(new NullProgressMonitor());
	IFile file = p.getFile("blah.yaml");
	file.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor());
	IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
	ITextEditor editor = (ITextEditor)IDE.openEditor(activePage, file, true);
	IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
	document.set("name: a\ndescrition: b");
	boolean markerFound = new DisplayHelper() {
		@Override protected boolean condition() {
			try {
				return file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO).length > 0;
			} catch (CoreException e) {
				return false;
			}
		}
	}.waitForCondition(activePage.getWorkbenchWindow().getShell().getDisplay(), 3000);
	assertFalse(Arrays.stream(file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)).map(Object::toString).collect(Collectors.joining("\n")), markerFound);
}
 
Example 8
@Test
public void testValidationIsDisabled_02() throws Exception {
	IProject project = AbstractXbaseUITestCase.createPluginProject("my.plugin.project");
	IFile file = project.getFile("Hello.xtext");
	InputStream stream = new InputStream() {
		@Override
		public int read() throws IOException {
			return -1;
		}
	};
	file.create(stream, true, null);
	assertFalse(isValidationDisabled(file));
}
 
Example 9
@Test
public void testJSXHighlighting() throws CoreException {
	IFile file = project.getFile("test.jsx");
	file.create(new ByteArrayInputStream("var n = 4;\n".getBytes()), true, null);
	ITextEditor editor = (ITextEditor)IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file);
	StyledText widget = (StyledText) editor.getAdapter(Control.class);
	Color defaultTextColor = widget.getForeground();
	assertTrue("Missing syntax highlighting", new DisplayHelper() {
		@Override protected boolean condition() {
			return Arrays.stream(widget.getStyleRanges()).anyMatch(range -> range.foreground != null && !defaultTextColor.equals(range.foreground));
		}
	}.waitForCondition(widget.getDisplay(), 2000));
}
 
Example 10
protected int createXtendElement(IProgressMonitor monitor, IFile xtendFile, String indentation, String lineSeparator) {
	int size = 0;
	try {
		String content = createContent(monitor, xtendFile, indentation, lineSeparator);
		size = content.length();
		xtendFile.create(new ByteArrayInputStream(content.getBytes()), true, monitor);
		setResource(xtendFile);
	} catch (CoreException e) {
		displayError(getElementCreationErrorMessage(), e.getMessage());
	}
	return size;
}
 
Example 11
private IFile generateJsonFile(Object jsonObject, IPath path, IProject project) throws InvocationTargetException {
	Gson gson = new GsonBuilder().setPrettyPrinting().create();
	String content = gson.toJson(jsonObject);
	IFile file = project.getFile(path);
	try {
		if (file.exists()) {
			file.setContents(IOUtils.toInputStream(content), 1, new NullProgressMonitor());
		} else {
			file.create(IOUtils.toInputStream(content), 1, new NullProgressMonitor());
		}
	} catch (CoreException e) {
		throw new InvocationTargetException(e);
	}
	return file;
}
 
Example 12
@Test
public void testReopen() throws CoreException {
  IFile file1 = projectHelper.getProject().getFile( "image.gif" );
  file1.create( getClass().getResourceAsStream( GIF_IMAGE ), NONE, null );
  IFile file2 = projectHelper.getProject().getFile( "image.png" );
  file2.create( getClass().getResourceAsStream( PNG_IMAGE ), NONE, null );

  ImageViewerEditor editor = openImageViewerEditor( new FileEditorInput( file1 ) );
  ImageData[] imageDatas1 = editor.imageCanvas.getImageDatas();
  editor.getSite().getPage().reuseEditor( editor, new FileEditorInput( file2 ) );
  ImageData[] imageDatas2 = editor.imageCanvas.getImageDatas();

  assertThat( imageDatas1 ).isNotEqualTo( imageDatas2 );
}
 
Example 13
/***/
@SuppressWarnings("resource")
protected IFile doCreateTestFile(IFolder folder, String fullName, CharSequence content) throws CoreException {
	IFile file = folder.getFile(fullName);
	createFolder(folder);
	file.create(new StringInputStream(content.toString()), true, monitor());
	waitForAutoBuild();
	return file;
}
 
Example 14
/**
 * 获取指定节点被选择的子节点
 * @param parentResource 树节点的父节点
 * @param parentFolder 项目空间的父文件夹
 * @return
 */
private void createCurProjectResource(ProjectResource parentResource, IFolder parentContainer) throws Exception{
	if (parentResource == null || parentContainer == null) {
		return;
	}
	for(Object obj : selectContentProvider.getChildren(parentResource)){
		if (obj instanceof ProjectResource) {
			ProjectResource proResource = (ProjectResource) obj;
			if (!selectElementTree.getChecked(proResource)) {
				continue;
			}
			
			// 如果是文件夹,如果没有创建,直接创建
			if (proResource.isFolder()) {
				IFolder childFolder = parentContainer.getFolder(proResource.getLabel());
				if (!childFolder.exists()) {
					childFolder.create(true, true, null);
				}
				createCurProjectResource(proResource, childFolder);
			}else {
				// 如果是文件,则判断是否需要覆盖,若是,则直接覆盖
				if (proResource.isNeedCover()) {
					IFile iFile = parentContainer.getFile(proResource.getLabel());
					InputStream inputStream = proResource.getInputStream();
					if (inputStream != null) {
						if (iFile.exists()) {
							closeOpenedFile(iFile);
							iFile.delete(true, null);
						}
						iFile.create(inputStream, true, null);
					}
				}
			}
		}
	}
}
 
Example 15
@Test
public void testCharsetIsHonored() throws Exception {
	IJavaProject project = createJavaProject("testCharsetIsHonored");
	project.getProject().setDefaultCharset(getNonDefaultEncoding(), null);
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	IFile file = folder.getFile("Foo" + F_EXT);
	file.create(new StringInputStream("object Foo"), true, monitor());
	build();
	IFile generatedFile = project.getProject().getFile("./src-gen/Foo.txt");
	assertEquals(getNonDefaultEncoding(), generatedFile.getCharset());
}
 
Example 16
@Test
public void testValidate_badXml_dynamicWebProject() throws CoreException {
  IProject dynamicWebProject = dynamicWebProjectCreator.getProject();
  IFile file = dynamicWebProject.getFile("src/bad.xml");
  byte[] badXml = BAD_XML.getBytes(StandardCharsets.UTF_8);
  file.create(new ByteArrayInputStream(badXml), true, null);

  IMarker[] markers = ProjectUtils.waitUntilMarkersFound(file, IMarker.PROBLEM,
      true /* includeSubtypes */, IResource.DEPTH_ZERO);
  ArrayAssertions.assertSize(1, markers);

  String resultMessage = (String) markers[0].getAttribute(IMarker.MESSAGE);
  assertEquals("XML document structures must start and end within the same entity.",
      resultMessage);
}
 
Example 17
private IPath createFileInProject(String filename) throws CoreException {
  IFile file = projectCreator.getProject().getFile(filename);
  file.create(new ByteArrayInputStream(new byte[0]), true, null);
  return file.getLocation();
}
 
Example 18
private IFile createBogusProjectFile() throws CoreException {
  IProject project = projectCreator.getProject();
  IFile file = project.getFile("bogus.resource.for.marker.tests");
  file.create(new ByteArrayInputStream(new byte[0]), true, null);
  return file;
}
 
Example 19
@Test
public void testNoCleanUpNoDerived() throws Exception {
	OutputConfigurationProvider outputConfigurationProvider = new OutputConfigurationProvider() {
		@Override
		public Set<OutputConfiguration> getOutputConfigurations() {
			final Set<OutputConfiguration> result = super.getOutputConfigurations();
			OutputConfiguration configuration = result.iterator().next();
			configuration.setCanClearOutputDirectory(false);
			configuration.setCleanUpDerivedResources(false);
			configuration.setSetDerivedProperty(false);
			return result;
		}
	};
	BuilderPreferenceAccess.Initializer initializer = new BuilderPreferenceAccess.Initializer();
	initializer.setOutputConfigurationProvider(outputConfigurationProvider);
	initializer.initialize(preferenceStoreAccess);

	IJavaProject project = createJavaProject("foo");
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	IFile file = folder.getFile("Foo" + F_EXT);
	file.create(new StringInputStream("object Foo"), true, monitor());
	build();
	IFile generatedFileFoo = project.getProject().getFile("./src-gen/Foo.txt");
	assertTrue(generatedFileFoo.exists());
	assertFalse(generatedFileFoo.isDerived());
	assertTrue(generatedFileFoo.findMarkers(DerivedResourceMarkers.MARKER_ID, false, IResource.DEPTH_ZERO).length == 1);
	assertEquals("object Foo", readFile(generatedFileFoo).trim());
	file.setContents(new StringInputStream("object Bar"), true, true, monitor());
	build();
	assertTrue(generatedFileFoo.exists());
	IFile generatedFileBar = project.getProject().getFile("./src-gen/Bar.txt");
	assertTrue(generatedFileBar.exists());
	assertFalse(generatedFileBar.isDerived());
	assertTrue(generatedFileBar.findMarkers(DerivedResourceMarkers.MARKER_ID, false, IResource.DEPTH_ZERO).length == 1);
	assertEquals("object Bar", readFile(generatedFileBar).trim());
	file.delete(true, monitor());
	build();
	assertTrue(generatedFileBar.exists());
	disableAutobuild(()->{
		cleanBuild();
		assertTrue(generatedFileBar.exists());	
	});
}
 
Example 20
Source Project: tlaplus   File: CoverageInformationTest.java    License: MIT License 4 votes vote down vote up
@BeforeClass
public static void setup() throws IOException, CoreException {
	// Create an IFile instance (this is a witness of why the Eclipse Resource API
	// is probably one of the worst APIs ever with the exception of those that I've
	// written).
	final String name = "CoverageInformationTestProject";
	final IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(name);
	final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(name);
	project.create(desc, new NullProgressMonitor());
	project.open(new NullProgressMonitor());
	final IFile file = project.getFile("Simple.tla");
	final InputStream source = CoverageInformationTest.class.getResourceAsStream("Simple.tla");
	file.create(source, IFile.FORCE, null);

	final CoverageInformation ci = new CoverageInformation(Arrays.asList(new IFile[] { file }));

	ci.add(ActionInformationItem.parseInit("<Init line 28, col 1 to line 28, col 4 of module Simple>: 3:3", "M"));
	ci.add(CoverageInformationItem.parse("line 29, col 12 to line 29, col 35 of module Simple: 1", "M"));
	ci.add(CoverageInformationItem.parse("line 30, col 12 to line 30, col 35 of module Simple: 1", "M"));
	ci.add(CoverageInformationItem.parse("line 31, col 12 to line 31, col 21 of module Simple: 1", "M"));
	ci.add(CoverageInformationItem.parse("line 32, col 12 to line 32, col 42 of module Simple: 3", "M"));

	ci.add(ActionInformationItem.parseNext("<a line 34, col 1 to line 34, col 7 of module Simple>: 63:99", "M"));
	ci.add(CoverageInformationItem.parse("line 34, col 15 to line 34, col 28 of module Simple: 558", "M"));
	ci.add(CoverageInformationItem.parse("|line 34, col 15 to line 34, col 22 of module Simple: 459", "M"));
	ci.add(CoverageInformationItem.parse("line 35, col 15 to line 35, col 41 of module Simple: 99", "M"));
	ci.add(CoverageInformationItem.parse("line 36, col 15 to line 36, col 45 of module Simple: 99", "M"));
	ci.add(CoverageInformationItem.parse("line 37, col 15 to line 37, col 30 of module Simple: 99", "M"));
	ci.add(CoverageInformationItem.parse("line 38, col 15 to line 38, col 27 of module Simple: 99", "M"));
	ci.add(CoverageInformationItem.parse("|line 7, col 15 to line 7, col 65 of module Simple: 99", "M"));
	ci.add(CoverageInformationItem.parse("||line 7, col 35 to line 7, col 65 of module Simple: 792", "M"));
	ci.add(CoverageInformationItem.parse("|||line 7, col 35 to line 7, col 41 of module Simple: 792", "M"));
	ci.add(CoverageInformationItem.parse("|||line 7, col 46 to line 7, col 65 of module Simple: 693", "M"));
	ci.add(CoverageInformationItem.parse("||||line 7, col 59 to line 7, col 65 of module Simple: 1188", "M"));
	ci.add(CoverageInformationItem.parse("||||line 7, col 55 to line 7, col 56 of module Simple: 693", "M"));
	ci.add(CoverageInformationItem.parseCost("||line 7, col 25 to line 7, col 32 of module Simple: 99:1881", "M"));
	ci.add(CoverageInformationItem.parse("|line 38, col 23 to line 38, col 26 of module Simple: 99", "M"));

	ci.add(ActionInformationItem.parseNext("<b line 40, col 1 to line 40, col 7 of module Simple>: 87:261", "M"));
	ci.add(CoverageInformationItem.parse("line 40, col 15 to line 40, col 25 of module Simple: 720", "M"));
	ci.add(CoverageInformationItem.parse("|line 40, col 15 to line 40, col 21 of module Simple: 459", "M"));
	ci.add(CoverageInformationItem.parse("line 40, col 30 to line 40, col 40 of module Simple: 621", "M"));
	ci.add(CoverageInformationItem.parse("|line 40, col 30 to line 40, col 36 of module Simple: 360", "M"));
	ci.add(CoverageInformationItem.parse("line 41, col 15 to line 41, col 55 of module Simple: 261", "M"));
	ci.add(CoverageInformationItem.parse("line 42, col 15 to line 42, col 48 of module Simple: 261", "M"));
	ci.add(CoverageInformationItem.parse("line 43, col 15 to line 43, col 30 of module Simple: 261", "M"));
	ci.add(CoverageInformationItem.parse("line 44, col 15 to line 44, col 27 of module Simple: 261", "M"));
	ci.add(CoverageInformationItem.parse("|line 7, col 15 to line 7, col 65 of module Simple: 261", "M"));
	ci.add(CoverageInformationItem.parse("||line 7, col 35 to line 7, col 65 of module Simple: 8352", "M"));
	ci.add(CoverageInformationItem.parse("|||line 7, col 35 to line 7, col 41 of module Simple: 8352", "M"));
	ci.add(CoverageInformationItem.parse("|||line 7, col 46 to line 7, col 65 of module Simple: 8091", "M"));
	ci.add(CoverageInformationItem.parse("||||line 7, col 59 to line 7, col 65 of module Simple: 20880", "M"));
	ci.add(CoverageInformationItem.parse("||||line 7, col 55 to line 7, col 56 of module Simple: 8091", "M"));
	ci.add(CoverageInformationItem.parseCost("||line 7, col 25 to line 7, col 32 of module Simple: 261:28971",
			"M"));
	ci.add(CoverageInformationItem.parse("|line 44, col 23 to line 44, col 26 of module Simple: 261", "M"));

	ci.add(ActionInformationItem.parseNext("<Terminating line 49, col 1 to line 49, col 11 of module Simple>: 0:21",
			"M"));
	ci.add(CoverageInformationItem.parse("line 49, col 40 to line 49, col 56 of module Simple: 330", "M"));
	ci.add(CoverageInformationItem.parse("|line 49, col 40 to line 49, col 47 of module Simple: 267", "M"));
	ci.add(CoverageInformationItem.parse("line 49, col 31 to line 49, col 37 of module Simple: 153", "M"));
	ci.add(CoverageInformationItem.parse("line 50, col 19 to line 50, col 32 of module Simple: 21", "M"));

	mci = ci.projectionFor(file);
	mci.getRoot(); // initialize AII to CII parent-child relationship.
}