org.eclipse.core.resources.IFile Java Examples

The following examples show how to use org.eclipse.core.resources.IFile. 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: Bug462047Test.java    From xtext-eclipse with Eclipse Public License 2.0 7 votes vote down vote up
@Test
public void testNoErrors() throws Exception {
	IResourcesSetupUtil.createFile("bug462047/src/a.bug462047lang", "element CORE ref CORE.b");
	IFile file = IResourcesSetupUtil.createFile("bug462047/src/b.bug462047lang", "element b ref CORE.c");
	IResourcesSetupUtil.createFile("bug462047/src/c.bug462047lang", "element c");
	IResourcesSetupUtil.waitForBuild();
	IResourcesSetupUtil.assertNoErrorsInWorkspace();
	LoggingTester.captureLogging(Level.ERROR, BatchLinkableResource.class, ()-> {
		
		try {
			XtextEditor editor = openEditor(file);
			IXtextDocument document = editor.getDocument();
			document.readOnly((XtextResource res)->{
				EcoreUtil.resolveAll(res);
				ResourceSet resourceSet = res.getResourceSet();
				assertNull(resourceSet.getResource(URI.createURI("java:/Objects/CORE.CORE"), false));
				return null;
			});
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}).assertNoLogEntries();
}
 
Example #2
Source File: JavaRefactoringIntegrationTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testRenameXtendDispatchMethod_2() throws Exception {
	String superModel = "class Super { def dispatch foo(Integer x) {} def dispatch foo(Object x) {} }";
	IFile superClass = createFile("Super.xtend", superModel);
	String subModel = "class Sub extends Super { def dispatch foo(String x) {} }";
	IFile subClass = createFile("Sub.xtend", subModel);
	String javaCallerModel = "public class JavaCaller { void bar(Sub x) { x.foo(new Object()); x._foo(\"\"); } }";
	IFile javaCaller = createFile("JavaCaller.java", javaCallerModel);
	String xtendCallerModel = "class XtendCaller { def bar(Super x) { x.foo(1) } }";
	IFile xtendCaller = createFile("XtendCaller.xtend", xtendCallerModel);
	final XtextEditor editor = openEditorSafely(subClass);
	// on Galileo, _foo is a discouraged method name
	renameXtendElement(editor, subModel.indexOf("foo"), "baz", RefactoringStatus.WARNING);
	assertDocumentContains(editor, subModel.replace("foo", "baz"));
	fileAsserts.assertFileContains(xtendCaller, xtendCallerModel.replace("foo", "baz"));
	fileAsserts.assertFileContains(javaCaller, javaCallerModel.replace("foo", "baz"));
	fileAsserts.assertFileContains(superClass, superModel.replace("foo", "baz"));
}
 
Example #3
Source File: ExternalPackagesPluginTest.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Check if index is populated only with workspace project content when the external location with single project is
 * registered and workspace contains project with the same name. External library is registered before project is
 * created in the workspace.
 */
@Test
public void testWorkspaceProjectHidingExternalProject_after() throws Exception {
	IProject createJSProject = ProjectTestsUtils.createJSProject(PROBAND_LIBFOO);
	IFolder src = configureProjectWithXtext(createJSProject);
	IFile packageJson = createJSProject.getProject().getFile(IN4JSProject.PACKAGE_JSON);
	assertMarkers("package.json of first project should have no errors", packageJson, 0);

	createTestFile(src, "Foo", "console.log('hi')");
	createTestFile(src, "AAAA", "console.log('hi')");
	createTestFile(src, "BBB", "console.log('hi')");
	waitForAutoBuild();

	copyProjectsToLocation(projectsRoot, externalLibrariesRoot, PROBAND_LIBFOO);
	ProjectTestsUtils.importDependencies(new EclipseProjectName(createJSProject.getName()).toN4JSProjectName(),
			externalLibrariesRoot.toUri(), libraryManager);

	Collection<String> expectedWorkspace = collectIndexableFiles(ResourcesPlugin.getWorkspace());
	// remove those that are shadowed
	expectedWorkspace.remove("/LibFoo/node_modules/LibFoo/src/Foo.n4js");
	expectedWorkspace.remove("/LibFoo/node_modules/LibFoo/package.json");

	assertResourceDescriptions(expectedWorkspace, BuilderUtil.getAllResourceDescriptions());
}
 
Example #4
Source File: ProblemHoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	modelAsText = "stuff mystuff\nstuff yourstuff refs _mystuff stuff hisstuff refs _yourstuff// Comment";
	IFile file = IResourcesSetupUtil.createFile("test/test.testlanguage", modelAsText);
	editor = openEditor(file);
	document = editor.getDocument();
	hover = TestsActivator.getInstance().getInjector(getEditorId()).getInstance(ProblemAnnotationHover.class);
	hover.setSourceViewer(editor.getInternalSourceViewer());
	List<Issue> issues = document.readOnly(new IUnitOfWork<List<Issue>, XtextResource>() {
		@Override
		public List<Issue> exec(XtextResource state) throws Exception {
			return state.getResourceServiceProvider().getResourceValidator().validate(state, CheckMode.ALL, null);
		}	
	});
	MarkerCreator markerCreator =  TestsActivator.getInstance().getInjector(getEditorId()).getInstance(MarkerCreator.class);
	for (Issue issue : issues) {
		markerCreator.createMarker(issue, file, MarkerTypes.forCheckType(issue.getType()));
	}
}
 
Example #5
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected IFile[] getChangedFiles() throws CoreException {
	Set<IFile> combined= new HashSet<>();
	combined.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits())));
	if (fRenameSubpackages) {
		IPackageFragment[] allPackages= JavaElementUtil.getPackageAndSubpackages(fPackage);
		for (int i= 0; i < allPackages.length; i++) {
			combined.addAll(Arrays.asList(ResourceUtil.getFiles(allPackages[i].getCompilationUnits())));
		}
	} else {
		combined.addAll(Arrays.asList(ResourceUtil.getFiles(fPackage.getCompilationUnits())));
	}
	if (fQualifiedNameSearchResult != null) {
		combined.addAll(Arrays.asList(fQualifiedNameSearchResult.getAllFiles()));
	}
	return combined.toArray(new IFile[combined.size()]);
}
 
Example #6
Source File: CopyResourceChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * returns false if source and destination are the same (in workspace or on disk)
 * in such case, no action should be performed
 * @param pm the progress monitor
 * @param newName the new name
 * @return returns <code>true</code> if the resource already exists
 * @throws CoreException thrown when teh resource cannpt be accessed
 */
private boolean deleteIfAlreadyExists(IProgressMonitor pm, String newName) throws CoreException {
	pm.beginTask("", 1); //$NON-NLS-1$
	IResource current= getDestination().findMember(newName);
	if (current == null)
		return true;
	if (! current.exists())
		return true;

	IResource resource= getResource();
	Assert.isNotNull(resource);

	if (ReorgUtils.areEqualInWorkspaceOrOnDisk(resource, current))
		return false;

	if (current instanceof IFile)
		((IFile)current).delete(false, true, new SubProgressMonitor(pm, 1));
	else if (current instanceof IFolder)
		((IFolder)current).delete(false, true, new SubProgressMonitor(pm, 1));
	else
		Assert.isTrue(false);

	return true;
}
 
Example #7
Source File: MemoryEditor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs ()
{
    SaveAsDialog saveAsDialog = new SaveAsDialog ( getSite ().getShell () );
    saveAsDialog.open ();
    IPath path = saveAsDialog.getResult ();
    if ( path != null )
    {
        IFile file = ResourcesPlugin.getWorkspace ().getRoot ().getFile ( path );
        if ( file != null )
        {
            doSaveAs ( URI.createPlatformResourceURI ( file.getFullPath ().toString (), true ), new FileEditorInput ( file ) );
        }
    }
}
 
Example #8
Source File: SyncGraphvizExportHandler.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void openFile(IFile file) {
	IEditorRegistry registry = PlatformUI.getWorkbench()
			.getEditorRegistry();
	if (registry.isSystemExternalEditorAvailable(file.getName())) {

		/**
		 * in case of opening the exported file from an other thread e.g. in
		 * case of listening to an IResourceChangeEvent
		 */
		Display.getDefault().asyncExec(new Runnable() {

			@Override
			public void run() {
				IWorkbenchPage page = PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getActivePage();
				try {
					page.openEditor(new FileEditorInput(file),
							IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
				} catch (PartInitException e) {
					DotActivatorEx.logError(e);
				}
			}
		});
	}
}
 
Example #9
Source File: LegacyGWTLaunchShortcutStrategy.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private void inferModuleAndHostPage(IResource selection) {
  if (selection.getType() == IResource.FILE) {
    if ("html".equalsIgnoreCase(selection.getFileExtension())) {
      for (IFile module : allHostPagesByModule.keySet()) {
        if (allHostPagesByModule.get(module).contains(selection)) {
          // Try to infer the module from the host page
          inferFromHostPage(selection);
        }
      }
    } else if (ModuleUtils.isModuleXml(selection)) {
      if (allHostPagesByModule.containsKey(selection)) {
        // Try to infer the host page from the selected module
        inferFromModule(selection);
      }
    }
  } else if (selection.getType() == IResource.PROJECT) {
    // Try to infer the module and host page from the project
    inferFromProject(selection.getProject());
  }
}
 
Example #10
Source File: TestLanguageServers.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testTSXFile() throws Exception {
	final IFile file = project.getFile("blah.tsx");
	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 #11
Source File: ItemManagerTester.java    From ice with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This operation checks the ability of the ItemManager to load a single
 * Item.
 */
@Test
public void checkSingleItemLoad() {
	// Reset the fake provider
	fakePersistenceProvider.reset();
	// Create a fake file and direct the manager to load it
	IFile fakeFile = new FakeIFile();
	Form form = itemManager.loadItem(fakeFile);
	// The form should not be null since the FakePersistenceProvider creates
	// an Item.
	assertNotNull(form);
	// Make sure the name matches the one in the FakePersistenceProvider and
	// that the load operation was called.
	assertEquals("The Doctor", form.getName());
	assertTrue(fakePersistenceProvider.allLoaded());
	// Reset the fake provider one more time, just to be polite.
	fakePersistenceProvider.reset();

	return;
}
 
Example #12
Source File: StandardFacetInstallationTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Test
public void testStandardFacetInstallation() throws IOException, CoreException {
  projects = ProjectUtils.importProjects(getClass(),
      "projects/test-dynamic-web-project.zip", true /* checkBuildErrors */, null);
  assertEquals(1, projects.size());
  IProject project = projects.values().iterator().next();
  IFacetedProject facetedProject = ProjectFacetsManager.create(project);
  // verify that the appengine-web.xml is installed in the dynamic web root folder
  AppEngineStandardFacet.installAppEngineFacet(facetedProject, true, null);
  IFile correctAppEngineWebXml = project.getFile("war/WEB-INF/appengine-web.xml");
  IFile wrongAppEngineWebXml = project.getFile("src/main/webapp/WEB-INF/appengine-web.xml");
  assertTrue(correctAppEngineWebXml.exists());
  assertFalse(wrongAppEngineWebXml.exists());

  ProjectUtils.waitForProjects(project); // App Engine runtime is added via a Job, so wait.
  IRuntime primaryRuntime = facetedProject.getPrimaryRuntime();
  assertTrue(AppEngineStandardFacet.isAppEngineStandardRuntime(primaryRuntime));
}
 
Example #13
Source File: TmfTraceManager.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Signal handler for the traceOpened signal.
 *
 * @param signal
 *            The incoming signal
 */
@TmfSignalHandler
public synchronized void traceOpened(final TmfTraceOpenedSignal signal) {
    final ITmfTrace trace = signal.getTrace();
    final IFile editorFile = signal.getEditorFile();

    final TmfTimeRange windowRange = trace.getInitialTimeRange();
    final ITmfTimestamp startTs = windowRange.getStartTime();
    final TmfTimeRange selectionRange = new TmfTimeRange(startTs, startTs);

    final TmfTraceContext startCtx = trace.createTraceContext(selectionRange, windowRange, editorFile, null);

    fTraces.put(trace, startCtx);

    IResource resource = trace.getResource();
    if (resource != null) {
        fInstanceCounts.add(resource);
        updateTraceContext(trace, builder -> builder.setInstanceNumber(fInstanceCounts.count(resource)));
    }

    /* We also want to set the newly-opened trace as the active trace */
    fCurrentTrace = trace;
}
 
Example #14
Source File: GetterSetterCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public TextFileChange getChange(IFile file) throws CoreException {
	final SelfEncapsulateFieldRefactoring refactoring= new SelfEncapsulateFieldRefactoring(fField);
	refactoring.setVisibility(Flags.AccPublic);
	refactoring.setConsiderVisibility(false);//private field references are just searched in local file
	refactoring.checkInitialConditions(new NullProgressMonitor());
	refactoring.checkFinalConditions(new NullProgressMonitor());
	Change createdChange= refactoring.createChange(new NullProgressMonitor());
	if (createdChange instanceof CompositeChange) {
		Change[] children= ((CompositeChange) createdChange).getChildren();
		for (int i= 0; i < children.length; i++) {
			Change curr= children[i];
			if (curr instanceof TextFileChange && ((TextFileChange) curr).getFile().equals(file)) {
				return (TextFileChange) curr;
			}
		}
	}
	return null;
}
 
Example #15
Source File: JavaClasspathTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testJavaSourceLevelMismatch() throws Exception {
	IProject project = testHelper.getProject();

	// create a fake java.util.List without type param
	IFolder folder = project.getFolder(new Path("src/java/util"));
	IResourcesSetupUtil.createFolder(folder.getFullPath());
	IFile list = folder.getFile("List.xtend");
	list.create(new StringInputStream("package java.util; class List {}"), true, null);

	IFile file = project.getFile("src/Foo.xtend");
	if (!file.exists())
		file.create(new StringInputStream(TEST_CLAZZ),
				true, null);
	IResourcesSetupUtil.cleanBuild();
	IResourcesSetupUtil.waitForBuild();
	markerAssert.assertErrorMarker(file, IssueCodes.JDK_NOT_ON_CLASSPATH);

	list.delete(true, null);
	IResourcesSetupUtil.cleanBuild();
	IResourcesSetupUtil.waitForBuild();
	markerAssert.assertNoErrorMarker(file);
}
 
Example #16
Source File: CreateFileChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected IFile getOldFile(IProgressMonitor pm) throws OperationCanceledException {
	pm.beginTask("", 1); //$NON-NLS-1$
	try {
		return ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);
	} finally {
		pm.done();
	}
}
 
Example #17
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Validates that the given source resources can be copied to the
 * destination as decided by the VCM provider.
 *
 * @param destination
 *            copy destination
 * @param sourceResources
 *            source resources
 * @return <code>true</code> all files passed validation or there were no
 *         files to validate. <code>false</code> one or more files did not
 *         pass validation.
 */
private boolean validateEdit(IContainer destination, IResource[] sourceResources) {
    ArrayList<IFile> copyFiles = new ArrayList<IFile>();

    collectExistingReadonlyFiles(destination.getFullPath(), sourceResources, copyFiles);
    if (copyFiles.size() > 0) {
        IFile[] files = copyFiles.toArray(new IFile[copyFiles.size()]);
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IStatus status = workspace.validateEdit(files, messageShell);

        canceled = status.isOK() == false;
        return status.isOK();
    }
    return true;
}
 
Example #18
Source File: TexProjectOutline.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the complete outline starting with the main file
 * and displaying all the files that are included from the main
 * file.
 * 
 * Note that this clears the problem markers from the main file
 * and each included file. 
 * 
 * @return List containing <code>outlineNode</code>s
 */
public List<OutlineNode> getFullOutline() {
    included.clear();
    virtualTopNode = new OutlineNode("Entire document", OutlineNode.TYPE_DOCUMENT, 0, null);
    
    IFile currentTexFile = TexlipseProperties.getProjectSourceFile(currentProject);
    MarkerHandler marker = MarkerHandler.getInstance();
    marker.clearProblemMarkers(currentTexFile);
    String fullName = getProjectRelativeName(currentTexFile);
    if (topLevelNodes == null) {
        try {
            topLevelNodes = fileParser.parseFile(currentTexFile);
            outlines.put(fullName, topLevelNodes);
        } catch (IOException ioe) {
            TexlipsePlugin.log("Unable to create full document outline; main file is not parsable", ioe);
            return new ArrayList<OutlineNode>();
        }
    }
    included.add(fullName);
    addChildren(virtualTopNode, topLevelNodes, currentTexFile);

    List<OutlineNode> outlineTop = virtualTopNode.getChildren();
    for (Iterator<OutlineNode> iter = outlineTop.iterator(); iter.hasNext();) {
        OutlineNode node = iter.next();
        node.setParent(null);
    }
    return outlineTop;
}
 
Example #19
Source File: DefaultCasDocumentProvider.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
@Override
protected void doSaveDocument(IProgressMonitor monitor, Object element, ICasDocument document,
        boolean overwrite) throws CoreException {

  if (element instanceof FileEditorInput) {
    FileEditorInput fileInput = (FileEditorInput) element;

    IFile file = fileInput.getFile();

    if (document instanceof DocumentUimaImpl) {

      DocumentUimaImpl documentImpl = (DocumentUimaImpl) document;

      ByteArrayOutputStream outStream = new ByteArrayOutputStream(40000);
      documentImpl.serialize(outStream);

      InputStream stream = new ByteArrayInputStream(outStream.toByteArray());
      
      isFileChangeTrackingEnabled = false;
      
      try {
        file.setContents(stream, true, false, null);
      }
      finally {
        isFileChangeTrackingEnabled = true;
      }
    }
  }

  // tell everyone that the element changed and is not dirty any longer
  fireElementDirtyStateChanged(element, false);
}
 
Example #20
Source File: OutputFileManager.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Retrieves the IFile object of the actually used source file, no matter
 * if it actually exists.
 * This method is used to respect partial builds.
 *
 * @return actually selected source file, or null if no source file has
 *  been set
 */
private IFile getActualSourceFile() {
    if (currentSourceFile == null) {
        return sourceFile;
    }
    else {
        return currentSourceFile;
    }
}
 
Example #21
Source File: CSVModel.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Default constructor
 */
public CSVModel(final IFile file) {
	this.file = file;
	displayFirstLine = true;
	rows = new ArrayList<>();
	listeners = new ArrayList<>();
}
 
Example #22
Source File: ExportConnectorArchiveOperation.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected IStatus addImplementationJar(final ConnectorImplementation implementation, final IFolder classpathFolder, final SourceRepositoryStore sourceStore, final IRepositoryStore implStore, final List<IResource> resourcesToExport) throws CoreException, InvocationTargetException, InterruptedException {
    final String connectorJarName = NamingUtils.toConnectorImplementationFilename(implementation.getImplementationId(), implementation.getImplementationVersion(),false) +".jar";
    final IFile jarFile = classpathFolder.getFile(Path.fromOSString(connectorJarName)) ;
    final String qualifiedClassName = impl.getImplementationClassname() ;
    String packageName ="" ;
    if(qualifiedClassName.indexOf(".")!= -1){
        packageName = qualifiedClassName.substring(0, qualifiedClassName.lastIndexOf(".")) ;
    }
    final PackageFileStore file =  (PackageFileStore) sourceStore.getChild(packageName, true) ;
    if(file != null){
        file.exportAsJar(jarFile.getLocation().toFile().getAbsolutePath(), false) ;
        if(includeSources){
            final IFolder srcFolder = implStore.getResource().getFolder(SRC_DIR) ;
            if(srcFolder.exists()){
                srcFolder.delete(true, Repository.NULL_PROGRESS_MONITOR) ;
            }
            srcFolder.create(true, true, Repository.NULL_PROGRESS_MONITOR) ;
            cleanAfterExport.add(srcFolder) ;

            final IPath path = file.getResource().getFullPath().makeRelativeTo(sourceStore.getResource().getFullPath()) ;
            final IFolder newFolder = srcFolder.getFolder(path) ;
            newFolder.getLocation().toFile().getParentFile().mkdirs() ;
            srcFolder.refreshLocal(IResource.DEPTH_INFINITE, Repository.NULL_PROGRESS_MONITOR) ;
            file.getResource().copy(newFolder.getFullPath(),true, Repository.NULL_PROGRESS_MONITOR) ;


            resourcesToExport.add(srcFolder) ;
        }
    }

    return Status.OK_STATUS ;
}
 
Example #23
Source File: MavenBuildSupportTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUpdateSnapshots() throws Exception {
	boolean updateSnapshots = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().isMavenUpdateSnapshots();
	FeatureStatus status = preferenceManager.getPreferences().getUpdateBuildConfigurationStatus();
	try {
		IProject project = importMavenProject("salut3");
		waitForBackgroundJobs();
		IJavaProject javaProject = JavaCore.create(project);
		IType type = javaProject.findType("org.apache.commons.lang3.StringUtils");
		assertNull(type);
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setMavenUpdateSnapshots(false);
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setUpdateBuildConfigurationStatus(FeatureStatus.automatic);
		IFile pom = project.getFile("pom.xml");
		String content = ResourceUtils.getContent(pom);
		//@formatter:off
		content = content.replace("<dependencies></dependencies>",
				"<dependencies>\n"
					+ "<dependency>\n"
					+ "   <groupId>org.apache.commons</groupId>\n"
					+ "   <artifactId>commons-lang3</artifactId>\n"
					+ "   <version>3.9</version>\n"
					+ "</dependency>"
					+ "</dependencies>");
		//@formatter:on
		ResourceUtils.setContent(pom, content);
		URI uri = pom.getRawLocationURI();
		projectsManager.fileChanged(uri.toString(), CHANGE_TYPE.CHANGED);
		waitForBackgroundJobs();
		type = javaProject.findType("org.apache.commons.lang3.StringUtils");
		assertNotNull(type);
	} finally {
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setMavenUpdateSnapshots(updateSnapshots);
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setUpdateBuildConfigurationStatus(status);
	}
}
 
Example #24
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected RefactoringModifications getModifications() throws CoreException {
	if (fModifications != null) {
		return fModifications;
	}

	fModifications= new MoveModifications();
	IPackageFragment pack= getDestinationAsPackageFragment();
	IContainer container= getDestinationAsContainer();
	Object unitDestination= null;
	if (pack != null) {
		unitDestination= pack;
	} else {
		unitDestination= container;
	}

	boolean updateReferenes= getUpdateReferences();
	if (unitDestination != null) {
		ICompilationUnit[] units= getCus();
		for (int i= 0; i < units.length; i++) {
			fModifications.move(units[i], new MoveArguments(unitDestination, updateReferenes));
		}
	}
	if (container != null) {
		IFile[] files= getFiles();
		for (int i= 0; i < files.length; i++) {
			fModifications.move(files[i], new MoveArguments(container, updateReferenes));
		}
		IFolder[] folders= getFolders();
		for (int i= 0; i < folders.length; i++) {
			fModifications.move(folders[i], new MoveArguments(container, updateReferenes));
		}
	}
	return fModifications;
}
 
Example #25
Source File: ContentFacadeFactory.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
/**
     * 
     * @param o
     * @return
     */
    public PreservingProperties.ContentFacade getFacadeForObject(Object o) {
        if (o instanceof IFile) {
            return new EFSFileProvider((IFile)o);
        }
// @TODO might want to implement other instances of ContentFacade
//        else if (o instanceof String) {
//          how do we get IFile from a path here, vs. java.io.File?
//        }
//        else if (o instanceof java.io.File {
//        }
         
        return null;
    }
 
Example #26
Source File: ChangeConverter.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void _handleReplacements(ITextDocumentChange change) {
	if (!change.getReplacements().isEmpty()) {
		IFile file = resourceUriConverter.toFile(change.getOldURI());
		if (!canWrite(file)) {
			issues.add(RefactoringIssueAcceptor.Severity.FATAL, "Affected file '" + file.getFullPath() + "' is read-only");
		}
		checkDerived(file);
		List<ReplaceEdit> textEdits = change.getReplacements().stream().map(replacement -> {
			return new ReplaceEdit(replacement.getOffset(), replacement.getLength(), replacement.getReplacementText());
		}).collect(Collectors.toList());

		MultiTextEdit textEdit = new MultiTextEdit();
		textEdit.addChildren(textEdits.toArray(new TextEdit[textEdits.size()]));
		ITextEditor openEditor = findOpenEditor(file);
		final TextChange ltkChange;
		if (openEditor == null) {
			TextFileChange textFileChange = new TextFileChange(change.getOldURI().lastSegment(), file);
			textFileChange.setSaveMode(TextFileChange.FORCE_SAVE);
			ltkChange = textFileChange;
		} else {
			ltkChange = new EditorDocumentChange(currentChange.getName(), openEditor, false);
		}
		ltkChange.setEdit(textEdit);
		ltkChange.setTextType(change.getOldURI().fileExtension());
		addChange(ltkChange);
	}
}
 
Example #27
Source File: MOOSEModel.java    From ice with Eclipse Public License 1.0 5 votes vote down vote up
/**
	 * A private utility used for deleting a range of lines in a text file.
	 *
	 * @param filename
	 * @param startline
	 * @param numlines
	 */
	private void deleteLines(IFile file, int startline, int numlines) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(file.getContents()));
//			BufferedReader br = new BufferedReader(new FileReader(filename));

			// String buffer to store contents of the file
			StringBuffer sb = new StringBuffer("");

			// Keep track of the line number
			int linenumber = 1;
			String line;

			while ((line = br.readLine()) != null) {
				// Store each valid line in the string buffer
				if (linenumber < startline || linenumber >= startline + numlines) {
					sb.append(line + "\n");
				}
				linenumber++;
			}
			if (startline + numlines > linenumber) {
				logger.info("End of file reached.");
			}
			br.close();

			FileWriter fw = new FileWriter(file.getLocation().toFile());
			// Write entire string buffer into the file
			fw.write(sb.toString());
			fw.close();
		} catch (Exception e) {
			logger.error(getClass().getName() + " Exception!",e);
		}
	}
 
Example #28
Source File: FilesPage.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Open in an editor the selected file of the table files.
 * 
 * @param selection
 */
private void openFile(ISelection selection) {
	if (selection.isEmpty()) {
		return;
	}
	String file = (String) ((IStructuredSelection) selection).getFirstElement();
	IFile tsconfigFile = getTsconfigFile();
	if (tsconfigFile != null) {
		IFile tsFile = tsconfigFile.getParent().getFile(new Path(file));
		if (tsFile.exists()) {
			EditorUtils.openInEditor(tsFile, true);
		}
	}
}
 
Example #29
Source File: AbstractBuilderParticipantTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/***/
protected void setDocumentContent(String context, IFile file, XtextEditor fileEditor, String newContent) {
	@SuppressWarnings("hiding")
	IDirtyStateManager dirtyStateManager = this.dirtyStateManager.get();

	TestEventListener eventListener = new TestEventListener(context, file);
	dirtyStateManager.addListener(eventListener);

	setDocumentContent(fileEditor, newContent);

	eventListener.waitForFiredEvent();
	dirtyStateManager.removeListener(eventListener);
	waitForUpdateEditorJob();
}
 
Example #30
Source File: BugInfoView.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void showInView(IMarker m) {
    this.marker = m;
    if (MarkerUtil.isFindBugsMarker(marker)) {
        bug = MarkerUtil.findBugInstanceForMarker(marker);
        file = (IFile) (marker.getResource() instanceof IFile ? marker.getResource() : null);
        javaElt = MarkerUtil.findJavaElementForMarker(marker);

        pattern = bug != null ? bug.getBugPattern() : null;
        refreshTitle();
        refreshAnnotations();
        refreshBrowser();
        rootComposite.layout(true, true);
    }
}