Java Code Examples for org.eclipse.jdt.core.IPackageFragmentRoot#createPackageFragment()

The following examples show how to use org.eclipse.jdt.core.IPackageFragmentRoot#createPackageFragment() . 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: MoveCompilationUnitChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private IPackageFragment[] createDestination(IPackageFragmentRoot root, IPackageFragment destination, IProgressMonitor pm) throws JavaModelException {
	String packageName= destination.getElementName();
	String[] split= packageName.split("\\."); //$NON-NLS-1$

	ArrayList<IPackageFragment> created= new ArrayList<>();

	StringBuilder name= new StringBuilder();
	name.append(split[0]);
	for (int i= 0; i < split.length; i++) {
		IPackageFragment fragment= root.getPackageFragment(name.toString());
		if (!fragment.exists()) {
			created.add(fragment);
		}

		if (fragment.equals(destination)) {
			root.createPackageFragment(name.toString(), true, pm);
			return created.toArray(new IPackageFragment[created.size()]);
		}

		name.append("."); //$NON-NLS-1$
		name.append(split[i + 1]);
	}

	return null;
}
 
Example 2
Source File: DiagnosticHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testUnnecessary() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("import java.security.*;\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	CompilationUnit asRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, monitor);
	IProblem[] problems = asRoot.getProblems();
	List<Diagnostic> diagnostics = DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problems), true);
	assertEquals(1, diagnostics.size());
	List<DiagnosticTag> tags = diagnostics.get(0).getTags();
	assertEquals(1, tags.size());
	assertEquals(DiagnosticTag.Unnecessary, tags.get(0));
}
 
Example 3
Source File: DiagnosticHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDeprecated() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("import java.security.Certificate;\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, monitor);
	IProblem[] problems = astRoot.getProblems();
	List<Diagnostic> diagnostics = DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problems), true);
	assertEquals(2, diagnostics.size());
	List<DiagnosticTag> tags = diagnostics.get(0).getTags();
	assertEquals(1, tags.size());
	assertEquals(DiagnosticTag.Deprecated, tags.get(0));
}
 
Example 4
Source File: JavaProjectUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates an {@link ICompilationUnit} with the given fully qualified name and
 * code in the <code>javaProject</code>.
 *
 * @param javaProject java project to host the new class
 * @param fullyQualifiedClassName fully qualified name for the class
 * @param source code for the classs
 * @return newly created {@link ICompilationUnit}
 * @throws JavaModelException
 */
public static ICompilationUnit createCompilationUnit(
    IJavaProject javaProject, String fullyQualifiedClassName, String source)
    throws JavaModelException {
  IPackageFragmentRoot root = javaProject.findPackageFragmentRoot(javaProject.getPath());
  if (root == null) {
    addRawClassPathEntry(javaProject,
        JavaCore.newSourceEntry(javaProject.getPath()));
    root = javaProject.findPackageFragmentRoot(javaProject.getPath());
  }

  String qualifier = Signature.getQualifier(fullyQualifiedClassName);
  IProgressMonitor monitor = new NullProgressMonitor();
  IPackageFragment packageFragment = root.createPackageFragment(qualifier,
      true, monitor);
  String name = Signature.getSimpleName(fullyQualifiedClassName);
  ICompilationUnit cu = packageFragment.createCompilationUnit(name + ".java",
      source, false, monitor);
  JobsUtilities.waitForIdle();
  return cu;
}
 
Example 5
Source File: CreatePackageChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Change perform(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask(RefactoringCoreMessages.CreatePackageChange_Creating_package, 1);

		if (fPackageFragment.exists()) {
			return new NullChange();
		} else {
			IPackageFragmentRoot root= (IPackageFragmentRoot) fPackageFragment.getParent();
			root.createPackageFragment(fPackageFragment.getElementName(), false, pm);

			return new DeleteResourceChange(fPackageFragment.getPath(), true);
		}
	} finally {
		pm.done();
	}
}
 
Example 6
Source File: UnresolvedTypesQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDontImportTestClassesInMainCode() throws Exception {
	IPackageFragmentRoot testSourceFolder = JavaProjectHelper.addSourceContainer(fJProject1, "src-tests", new Path[0], new Path[0], "bin-tests",
			new IClasspathAttribute[] { JavaCore.newClasspathAttribute(IClasspathAttribute.TEST, "true") });

	IPackageFragment pack1 = fSourceFolder.createPackageFragment("pp", false, null);
	StringBuilder buf1 = new StringBuilder();
	buf1.append("package pp;\n");
	buf1.append("public class C1 {\n");
	buf1.append("    Tests at=new Tests();\n");
	buf1.append("}\n");
	ICompilationUnit cu1 = pack1.createCompilationUnit("C1.java", buf1.toString(), false, null);

	IPackageFragment pack2 = testSourceFolder.createPackageFragment("pt", false, null);
	StringBuilder buf2 = new StringBuilder();
	buf2.append("package pt;\n");
	buf2.append("public class Tests {\n");
	buf2.append("}\n");
	pack2.createCompilationUnit("Tests.java", buf2.toString(), false, null);

	assertCodeActionNotExists(cu1, "Import 'Tests' (pt)");
}
 
Example 7
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testReconcile() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E123 {\n");
	buf.append("    public void testing() {\n");
	buf.append("        int someIntegerChanged = 5;\n");
	buf.append("        int i = someInteger + 5\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu1 = pack1.createCompilationUnit("E123.java", buf.toString(), false, null);
	openDocument(cu1, cu1.getSource(), 1);
	assertEquals(true, cu1.isWorkingCopy());
	assertEquals(false, cu1.hasUnsavedChanges());
	List<PublishDiagnosticsParams> diagnosticsParams = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticsParams.size());
	PublishDiagnosticsParams diagnosticsParam = diagnosticsParams.get(0);
	List<Diagnostic> diagnostics = diagnosticsParam.getDiagnostics();
	assertEquals(2, diagnostics.size());
	diagnosticsParams.clear();
	closeDocument(cu1);
}
 
Example 8
Source File: AbstractGWTPluginTestCase.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void addToTestProject() throws Exception {
  IProject testProject = Util.getWorkspaceRoot().getProject(TEST_PROJECT_NAME);
  if (!testProject.exists()) {
    throw new Exception("The test project does not exist");
  }

  IJavaProject javaProject = JavaCore.create(testProject);

  IPath srcPath = new Path("/" + TEST_PROJECT_NAME + "/src");
  IPackageFragmentRoot pckgRoot = javaProject.findPackageFragmentRoot(srcPath);

  String packageName = Signature.getQualifier(typeName);
  String cuName = Signature.getSimpleName(typeName) + ".java";

  // If the package fragment already exists, this call does nothing
  IPackageFragment pckg = pckgRoot.createPackageFragment(packageName, false, null);

  cu = pckg.createCompilationUnit(cuName, contents, true, null);
  JobsUtilities.waitForIdle();
}
 
Example 9
Source File: MoveCompilationUnitChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IPackageFragment[] createDestination(IPackageFragmentRoot root, IPackageFragment destination, IProgressMonitor pm) throws JavaModelException {
	String packageName= destination.getElementName();
	String[] split= packageName.split("\\."); //$NON-NLS-1$

	ArrayList<IPackageFragment> created= new ArrayList<IPackageFragment>();

	StringBuffer name= new StringBuffer();
	name.append(split[0]);
	for (int i= 0; i < split.length; i++) {
		IPackageFragment fragment= root.getPackageFragment(name.toString());
		if (!fragment.exists()) {
			created.add(fragment);
		}

		if (fragment.equals(destination)) {
			root.createPackageFragment(name.toString(), true, pm);
			return created.toArray(new IPackageFragment[created.size()]);
		}

		name.append("."); //$NON-NLS-1$
		name.append(split[i + 1]);
	}

	return null;
}
 
Example 10
Source File: DiagnosticsCommandTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRefreshDiagnosticsWithReportAllErrors() throws Exception {
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo extends UnknownType {\n"+
			"	public void method1(){\n"+
			"		super.whatever()\n"+
			"	}\n"+
			"}";
	// @formatter:on

	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);

	openDocument(cu1, cu1.getSource(), 1);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals(2, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only syntax errors are reported", diagParam.getDiagnostics().get(0).getMessage());

	DiagnosticsCommand.refreshDiagnostics(JDTUtils.toURI(cu1), "thisFile", false);

	diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(2, diagnosticReports.size());
	diagParam = diagnosticReports.get(1);
	assertEquals(4, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only JDK classes are added to its build path", diagParam.getDiagnostics().get(0).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(1).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(2).getMessage());
	assertEquals("Syntax error, insert \";\" to complete BlockStatements", diagParam.getDiagnostics().get(3).getMessage());
}
 
Example 11
Source File: DiagnosticHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMultipleLineRange() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	Hashtable<String, String> options = JavaCore.getOptions();
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, JavaCore.WARNING);
	javaProject.setOptions(options);
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean foo(boolean b1) {\n");
	buf.append("        if (false) {\n");
	buf.append("            return true;\n");
	buf.append("        }\n");
	buf.append("        return false;\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, monitor);
	IProblem[] problems = astRoot.getProblems();
	List<Diagnostic> diagnostics = DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problems), true);
	assertEquals(1, diagnostics.size());
	Range range = diagnostics.get(0).getRange();
	assertNotEquals(range.getStart().getLine(), range.getEnd().getLine());
}
 
Example 12
Source File: WorkspaceEventHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDiscardStaleWorkingCopies() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IFolder src = javaProject.getProject().getFolder("src");
	IPackageFragmentRoot srcRoot = javaProject.getPackageFragmentRoot(src);
	IPackageFragment mypack = srcRoot.createPackageFragment("mypack", true, null);
	// @formatter:off
	String contents = "package mypack;\n" +
					"public class Foo {" +
					"}\n";
	// @formatter:on
	ICompilationUnit unit = mypack.createCompilationUnit("Foo.java", contents, true, null);
	openDocument(unit, contents, 1);
	assertTrue(unit.isWorkingCopy());

	String oldUri = JDTUtils.getFileURI(srcRoot.getResource());
	String parentUri = JDTUtils.getFileURI(src);
	String newUri = oldUri.replace("mypack", "mynewpack");
	File oldPack = mypack.getResource().getLocation().toFile();
	File newPack = new File(oldPack.getParent(), "mynewpack");
	Files.move(oldPack, newPack);
	assertTrue(unit.isWorkingCopy());
	DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams(Arrays.asList(
		new FileEvent(newUri, FileChangeType.Created),
		new FileEvent(parentUri, FileChangeType.Changed),
		new FileEvent(oldUri, FileChangeType.Deleted)
	));
	new WorkspaceEventsHandler(projectsManager, javaClient, lifeCycleHandler).didChangeWatchedFiles(params);
	assertFalse(unit.isWorkingCopy());
}
 
Example 13
Source File: SemanticHighlightingTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDidOpen() throws Exception {
	IJavaProject project = newEmptyProject();
	IPackageFragmentRoot src = project.getPackageFragmentRoot(project.getProject().getFolder("src"));
	IPackageFragment _package = src.createPackageFragment("_package", false, null);
	ICompilationUnit unit = _package.createCompilationUnit("ClassName.java", CONTENT, false, null);
	openDocument(unit, unit.getSource(), 1);
	assertEquals(1, javaClient.params.size());
	assertTrue(!javaClient.params.get(0).getLines().isEmpty());
}
 
Example 14
Source File: DiagnosticsCommandTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRefreshDiagnosticsWithReportSyntaxErrors() throws Exception {
	JavaLanguageServerPlugin.getNonProjectDiagnosticsState().setGlobalErrorLevel(ErrorLevel.COMPILATION_ERROR);
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo extends UnknownType {\n"+
			"	public void method1(){\n"+
			"		super.whatever()\n"+
			"	}\n"+
			"}";
	// @formatter:on

	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);

	openDocument(cu1, cu1.getSource(), 1);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals(4, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only JDK classes are added to its build path", diagParam.getDiagnostics().get(0).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(1).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(2).getMessage());
	assertEquals("Syntax error, insert \";\" to complete BlockStatements", diagParam.getDiagnostics().get(3).getMessage());

	DiagnosticsCommand.refreshDiagnostics(JDTUtils.toURI(cu1), "thisFile", true);

	diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(2, diagnosticReports.size());
	diagParam = diagnosticReports.get(1);
	assertEquals(2, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only syntax errors are reported", diagParam.getDiagnostics().get(0).getMessage());
	assertEquals("Syntax error, insert \";\" to complete BlockStatements", diagParam.getDiagnostics().get(1).getMessage());
}
 
Example 15
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testFixInDependencyScenario() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class F123 {\n");
	buf.append("}\n");
	ICompilationUnit cu1 = pack1.createCompilationUnit("F123.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class F456 {\n");
	buf.append("  { F123.foo(); }\n");
	buf.append("}\n");
	ICompilationUnit cu2 = pack1.createCompilationUnit("F456.java", buf.toString(), false, null);

	assertEquals(false, cu1.isWorkingCopy());
	assertEquals(false, cu1.hasUnsavedChanges());
	assertEquals(false, cu2.isWorkingCopy());
	assertEquals(false, cu2.hasUnsavedChanges());
	assertNewProblemReported();
	assertEquals(0, getCacheSize());
	assertNewASTsCreated(0);

	openDocument(cu2, cu2.getSource(), 1);

	assertEquals(false, cu1.isWorkingCopy());
	assertEquals(false, cu1.hasUnsavedChanges());
	assertEquals(true, cu2.isWorkingCopy());
	assertEquals(false, cu2.hasUnsavedChanges());
	assertNewProblemReported(new ExpectedProblemReport(cu2, 1));
	assertEquals(1, getCacheSize());
	assertNewASTsCreated(1);

	openDocument(cu1, cu1.getSource(), 1);

	assertEquals(true, cu1.isWorkingCopy());
	assertEquals(false, cu1.hasUnsavedChanges());
	assertEquals(true, cu2.isWorkingCopy());
	assertEquals(false, cu2.hasUnsavedChanges());
	assertNewProblemReported(new ExpectedProblemReport(cu2, 1), new ExpectedProblemReport(cu1, 0));
	assertEquals(1, getCacheSize());
	assertNewASTsCreated(2);

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class F123 {\n");
	buf.append("  public static void foo() {}\n");
	buf.append("}\n");

	changeDocumentFull(cu1, buf.toString(), 2);

	assertEquals(true, cu1.isWorkingCopy());
	assertEquals(true, cu1.hasUnsavedChanges());
	assertEquals(true, cu2.isWorkingCopy());
	assertEquals(false, cu2.hasUnsavedChanges());
	assertNewProblemReported(new ExpectedProblemReport(cu2, 0), new ExpectedProblemReport(cu1, 0));
	assertEquals(1, getCacheSize());
	assertNewASTsCreated(2);

	saveDocument(cu1);

	assertEquals(true, cu1.isWorkingCopy());
	assertEquals(false, cu1.hasUnsavedChanges());
	assertEquals(true, cu2.isWorkingCopy());
	assertEquals(false, cu2.hasUnsavedChanges());
	assertNewProblemReported();
	assertEquals(1, getCacheSize());
	assertNewASTsCreated(0);

	closeDocument(cu1);

	assertEquals(false, cu1.isWorkingCopy());
	assertEquals(false, cu1.hasUnsavedChanges());
	assertEquals(true, cu2.isWorkingCopy());
	assertEquals(false, cu2.hasUnsavedChanges());
	assertNewProblemReported();
	assertEquals(0, getCacheSize());
	assertNewASTsCreated(0);

	closeDocument(cu2);

	assertEquals(false, cu1.isWorkingCopy());
	assertEquals(false, cu1.hasUnsavedChanges());
	assertEquals(false, cu2.isWorkingCopy());
	assertEquals(false, cu2.hasUnsavedChanges());
	assertNewProblemReported();
	assertEquals(0, getCacheSize());
	assertNewASTsCreated(0);
}
 
Example 16
Source File: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the necessary source code for the refactoring.
 *
 * @param monitor
 *            the progress monitor to use
 * @return
 *            the resulting status
 */
private RefactoringStatus createNecessarySourceCode(final IProgressMonitor monitor) {
	final RefactoringStatus status= new RefactoringStatus();
	try {
		monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 240);
		final IPackageFragmentRoot root= getPackageFragmentRoot();
		if (root != null && fSourceFolder != null && fJavaProject != null) {
			try {
				final SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 40, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
				final IJavaElement[] elements= root.getChildren();
				final List<IPackageFragment> list= new ArrayList<IPackageFragment>(elements.length);
				try {
					subMonitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, elements.length);
					for (int index= 0; index < elements.length; index++) {
						final IJavaElement element= elements[index];
						if (!fProcessedFragments.contains(element) && !element.getElementName().equals(META_INF_FRAGMENT))
							list.add((IPackageFragment) element);
						subMonitor.worked(1);
					}
				} finally {
					subMonitor.done();
				}
				if (!list.isEmpty()) {
					fProcessedFragments.addAll(list);
					final URI uri= fSourceFolder.getRawLocationURI();
					if (uri != null) {
						final IPackageFragmentRoot sourceFolder= fJavaProject.getPackageFragmentRoot(fSourceFolder);
						IWorkspaceRunnable runnable= null;
						if (canUseSourceAttachment()) {
							runnable= new SourceCreationOperation(uri, list) {

								private IPackageFragment fFragment= null;

								@Override
								protected final void createCompilationUnit(final IFileStore store, final String name, final String content, final IProgressMonitor pm) throws CoreException {
									fFragment.createCompilationUnit(name, content, true, pm);
								}

								@Override
								protected final void createPackageFragment(final IFileStore store, final String name, final IProgressMonitor pm) throws CoreException {
									fFragment= sourceFolder.createPackageFragment(name, true, pm);
								}
							};
						} else {
							runnable= new StubCreationOperation(uri, list, true) {

								private IPackageFragment fFragment= null;

								@Override
								protected final void createCompilationUnit(final IFileStore store, final String name, final String content, final IProgressMonitor pm) throws CoreException {
									fFragment.createCompilationUnit(name, content, true, pm);
								}

								@Override
								protected final void createPackageFragment(final IFileStore store, final String name, final IProgressMonitor pm) throws CoreException {
									fFragment= sourceFolder.createPackageFragment(name, true, pm);
								}
							};
						}
						try {
							runnable.run(new SubProgressMonitor(monitor, 150, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
						} finally {
							fSourceFolder.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 50, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
						}
					}
				}
			} catch (CoreException exception) {
				status.addFatalError(exception.getLocalizedMessage());
			}
		}
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 17
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testDidOpenStandaloneFileWithNonSyntaxErrors() throws Exception {
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo {\n"+
			"	public static void notThis(){\n"+
			"		System.out.println(this);\n"+
			"	}\n"+
			"	public void method1(){\n"+
			"	}\n"+
			"	public void method1(){\n"+
			"	}\n"+
			"}";
	// @formatter:on

	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);

	openDocument(cu1, cu1.getSource(), 1);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);

	assertEquals("Unexpected number of errors " + diagParam.getDiagnostics(), 4, diagParam.getDiagnostics().size());
	Diagnostic d = diagParam.getDiagnostics().get(0);
	assertEquals("Foo.java is a non-project file, only syntax errors are reported", d.getMessage());
	assertRange(0, 0, 1, d.getRange());
	
	d = diagParam.getDiagnostics().get(1);
	assertEquals("Cannot use this in a static context", d.getMessage());
	assertRange(3, 21, 25, d.getRange());

	d = diagParam.getDiagnostics().get(2);
	assertEquals("Duplicate method method1() in type Foo", d.getMessage());
	assertRange(5, 13, 22, d.getRange());

	d = diagParam.getDiagnostics().get(3);
	assertEquals("Duplicate method method1() in type Foo", d.getMessage());
	assertRange(7, 13, 22, d.getRange());
}
 
Example 18
Source File: NonProjectFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testReportAllErrorsFixForNonProjectFile() throws Exception {
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo extends UnknownType {\n"+
			"	public void method1(){\n"+
			"		super.whatever()\n"+
			"	}\n"+
			"}";
	// @formatter:on

	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);
	final DiagnosticsHandler handler = new DiagnosticsHandler(javaClient, cu1);
	WorkingCopyOwner wcOwner = createWorkingCopyOwner(cu1, handler);
	cu1.becomeWorkingCopy(null);
	try {
		cu1.reconcile(ICompilationUnit.NO_AST, true, wcOwner, null);
		List<IProblem> problems = handler.getProblems();
		assertFalse(problems.isEmpty());

		List<Either<Command, CodeAction>> actions = getCodeActions(cu1, problems.get(0));
		assertEquals(2, actions.size());
		CodeAction action = actions.get(0).getRight();
		assertEquals(CodeActionKind.QuickFix, action.getKind());
		assertEquals(ActionMessages.ReportAllErrorsForThisFile, action.getCommand().getTitle());
		assertEquals(3, action.getCommand().getArguments().size());
		assertEquals("thisFile", action.getCommand().getArguments().get(1));
		assertEquals(false, action.getCommand().getArguments().get(2));

		action = actions.get(1).getRight();
		assertEquals(CodeActionKind.QuickFix, action.getKind());
		assertEquals(ActionMessages.ReportAllErrorsForAnyNonProjectFile, action.getCommand().getTitle());
		assertEquals(3, action.getCommand().getArguments().size());
		assertEquals("anyNonProjectFile", action.getCommand().getArguments().get(1));
		assertEquals(false, action.getCommand().getArguments().get(2));
	} finally {
		cu1.discardWorkingCopy();
	}
}
 
Example 19
Source File: NonProjectFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testReportSyntaxErrorsFixForNonProjectFile() throws Exception {
	JavaLanguageServerPlugin.getNonProjectDiagnosticsState().setGlobalErrorLevel(false);
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo extends UnknownType {\n"+
			"	public void method1(){\n"+
			"		super.whatever()\n"+
			"	}\n"+
			"}";
	// @formatter:on

	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);
	final DiagnosticsHandler handler = new DiagnosticsHandler(javaClient, cu1);
	WorkingCopyOwner wcOwner = createWorkingCopyOwner(cu1, handler);
	cu1.becomeWorkingCopy(null);
	try {
		cu1.reconcile(ICompilationUnit.NO_AST, true, wcOwner, null);
		List<IProblem> problems = handler.getProblems();
		assertFalse(problems.isEmpty());

		List<Either<Command, CodeAction>> actions = getCodeActions(cu1, problems.get(0));
		assertEquals(2, actions.size());
		CodeAction action = actions.get(0).getRight();
		assertEquals(CodeActionKind.QuickFix, action.getKind());
		assertEquals(ActionMessages.ReportSyntaxErrorsForThisFile, action.getCommand().getTitle());
		assertEquals(3, action.getCommand().getArguments().size());
		assertEquals("thisFile", action.getCommand().getArguments().get(1));
		assertEquals(true, action.getCommand().getArguments().get(2));

		action = actions.get(1).getRight();
		assertEquals(CodeActionKind.QuickFix, action.getKind());
		assertEquals(ActionMessages.ReportSyntaxErrorsForAnyNonProjectFile, action.getCommand().getTitle());
		assertEquals(3, action.getCommand().getArguments().size());
		assertEquals("anyNonProjectFile", action.getCommand().getArguments().get(1));
		assertEquals(true, action.getCommand().getArguments().get(2));
	} finally {
		cu1.discardWorkingCopy();
	}
}
 
Example 20
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void test1WithOrder() throws Exception {
	requireJUnitSources();
	ICompilationUnit cu = (ICompilationUnit) javaProject.findElement(new Path("junit/runner/BaseTestRunner.java"));
	assertNotNull("BaseTestRunner.java is missing", cu);
	IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
	IPackageFragment pack= root.createPackageFragment("mytest", true, null);
	ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
	colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
	String[] order= new String[] { "junit", "java.text", "java.io", "java" };
	IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		//@formatter:off
		assertImports(cu, new String[] {
			"junit.framework.AssertionFailedError",
			"junit.framework.Test",
			"junit.framework.TestListener",
			"junit.framework.TestSuite",
			"java.text.NumberFormat",
			"java.io.BufferedReader",
			"java.io.File",
			"java.io.FileInputStream",
			"java.io.FileOutputStream",
			"java.io.IOException",
			"java.io.InputStream",
			"java.io.PrintWriter",
			"java.io.StringReader",
			"java.io.StringWriter",
			"java.lang.reflect.InvocationTargetException",
			"java.lang.reflect.Method",
			"java.lang.reflect.Modifier",
			"java.util.Properties"
		});
		//@formatter:on
	} finally {
		cu.discardWorkingCopy();
	}
}