Java Code Examples for org.eclipse.jdt.core.ICompilationUnit#reconcile()

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#reconcile() . 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: RenameAnalyzeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
static ICompilationUnit createNewWorkingCopy(ICompilationUnit cu, TextChangeManager manager,
		WorkingCopyOwner owner, SubProgressMonitor pm) throws CoreException {
	ICompilationUnit newWc= cu.getWorkingCopy(owner, null);
	String previewContent= manager.get(cu).getPreviewContent(new NullProgressMonitor());
	newWc.getBuffer().setContents(previewContent);
	newWc.reconcile(ICompilationUnit.NO_AST, false, owner, pm);
	return newWc;
}
 
Example 2
Source File: MavenClasspathTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMain() throws Exception {
	IProject project = importMavenProject("classpathtest");
	IJavaProject javaProject = JavaCore.create(project);
	IType type = javaProject.findType("main.App");
	ICompilationUnit cu = type.getCompilationUnit();
	openDocument(cu, cu.getSource(), 1);
	final DiagnosticsHandler handler = new DiagnosticsHandler(javaClient, cu);
	WorkingCopyOwner wcOwner = getWorkingCopy(handler);
	cu.reconcile(ICompilationUnit.NO_AST, true, wcOwner, null);
	assertTrue("There aren't any problems", handler.getProblems().size() == 1);
}
 
Example 3
Source File: MavenClasspathTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTest() throws Exception {
	IProject project = importMavenProject("classpathtest");
	IJavaProject javaProject = JavaCore.create(project);
	IType type = javaProject.findType("test.AppTest");
	ICompilationUnit cu = type.getCompilationUnit();
	openDocument(cu, cu.getSource(), 1);
	final DiagnosticsHandler handler = new DiagnosticsHandler(javaClient, cu);
	WorkingCopyOwner wcOwner = getWorkingCopy(handler);
	cu.reconcile(ICompilationUnit.NO_AST, true, wcOwner, null);
	assertTrue("There is a problem", handler.getProblems().size() == 0);
}
 
Example 4
Source File: RenameAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
static ICompilationUnit createNewWorkingCopy(ICompilationUnit cu, TextChangeManager manager,
		WorkingCopyOwner owner, SubProgressMonitor pm) throws CoreException {
	ICompilationUnit newWc= cu.getWorkingCopy(owner, null);
	String previewContent= manager.get(cu).getPreviewContent(new NullProgressMonitor());
	newWc.getBuffer().setContents(previewContent);
	newWc.reconcile(ICompilationUnit.NO_AST, false, owner, pm);
	return newWc;
}
 
Example 5
Source File: JavaModelUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Force a reconcile of a compilation unit.
 * @param unit the compilation unit
 * @throws JavaModelException thrown when the compilation unit can not be accessed
 */
public static void reconcile(ICompilationUnit unit) throws JavaModelException {
	unit.reconcile(
			ICompilationUnit.NO_AST,
			false /* don't force problem detection */,
			null /* use primary owner */,
			null /* no progress monitor */);
}
 
Example 6
Source File: JavaReconcilingStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Performs the reconcile and returns the AST if it was computed.
 *
 * @param unit the compilation unit
 * @param initialReconcile <code>true</code> if this is the initial reconcile
 * @return the AST or <code>null</code> if none
 * @throws JavaModelException if the original Java element does not exist
 * @since 3.4
 */
private CompilationUnit reconcile(ICompilationUnit unit, boolean initialReconcile) throws JavaModelException {
	/* fix for missing cancel flag communication */
	IProblemRequestorExtension extension= getProblemRequestorExtension();
	if (extension != null) {
		extension.setProgressMonitor(fProgressMonitor);
		extension.setIsActive(true);
	}

	try {
		boolean isASTNeeded= initialReconcile || JavaPlugin.getDefault().getASTProvider().isActive(unit);
		// reconcile
		if (fIsJavaReconcilingListener && isASTNeeded) {
			int reconcileFlags= ICompilationUnit.FORCE_PROBLEM_DETECTION;
			if (ASTProvider.SHARED_AST_STATEMENT_RECOVERY)
				reconcileFlags|= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY;
			if (ASTProvider.SHARED_BINDING_RECOVERY)
				reconcileFlags|= ICompilationUnit.ENABLE_BINDINGS_RECOVERY;

			CompilationUnit ast= unit.reconcile(ASTProvider.SHARED_AST_LEVEL, reconcileFlags, null, fProgressMonitor);
			if (ast != null) {
				// mark as unmodifiable
				ASTNodes.setFlagsToAST(ast, ASTNode.PROTECT);
				return ast;
			}
		} else
			unit.reconcile(ICompilationUnit.NO_AST, true, null, fProgressMonitor);
	} catch (OperationCanceledException ex) {
		Assert.isTrue(fProgressMonitor == null || fProgressMonitor.isCanceled());
	} finally {
		/* fix for missing cancel flag communication */
		if (extension != null) {
			extension.setProgressMonitor(null);
			extension.setIsActive(false);
		}
	}

	return null;
}
 
Example 7
Source File: JavadocCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public List<CompletionItem> getProposals(ICompilationUnit cu, int offset, CompletionProposalRequestor collector, IProgressMonitor monitor) throws JavaModelException {
	if (cu == null) {
		throw new IllegalArgumentException("Compilation unit must not be null"); //$NON-NLS-1$
	}
	List<CompletionItem> result = new ArrayList<>();
	IDocument d = JsonRpcHelpers.toDocument(cu.getBuffer());
	if (offset < 0 || d.getLength() == 0) {
		return result;
	}
	try {
		int p = (offset == d.getLength() ? offset - 1 : offset);
		IRegion line = d.getLineInformationOfOffset(p);
		String lineStr = d.get(line.getOffset(), line.getLength()).trim();
		if (!lineStr.startsWith("/**")) {
			return result;
		}
		if (!hasEndJavadoc(d, offset)) {
			return result;
		}
		String text = collector.getContext().getToken() == null ? "" : new String(collector.getContext().getToken());
		StringBuilder buf = new StringBuilder(text);
		IRegion prefix = findPrefixRange(d, line);
		String indentation = d.get(prefix.getOffset(), prefix.getLength());
		int lengthToAdd = Math.min(offset - prefix.getOffset(), prefix.getLength());
		buf.append(indentation.substring(0, lengthToAdd));
		String lineDelimiter = TextUtilities.getDefaultLineDelimiter(d);
		ICompilationUnit unit = cu;
		try {
			unit.reconcile(ICompilationUnit.NO_AST, false, null, null);
			String string = createJavaDocTags(d, offset, indentation, lineDelimiter, unit);
			if (string != null && !string.trim().equals(ASTERISK)) {
				buf.append(string);
			} else {
				return result;
			}
			int nextNonWS = findEndOfWhiteSpace(d, offset, d.getLength());
			if (!Character.isWhitespace(d.getChar(nextNonWS))) {
				buf.append(lineDelimiter);
			}
		} catch (CoreException e) {
			// ignore
		}
		final CompletionItem ci = new CompletionItem();
		Range range = JDTUtils.toRange(unit, offset, 0);
		boolean isSnippetSupported = JavaLanguageServerPlugin.getPreferencesManager().getClientPreferences().isCompletionSnippetsSupported();
		String replacement = prepareTemplate(buf.toString(), lineDelimiter, isSnippetSupported);
		ci.setTextEdit(new TextEdit(range, replacement));
		ci.setFilterText(JAVA_DOC_COMMENT);
		ci.setLabel(JAVA_DOC_COMMENT);
		ci.setSortText(SortTextHelper.convertRelevance(0));
		ci.setKind(CompletionItemKind.Snippet);
		ci.setInsertTextFormat(isSnippetSupported ? InsertTextFormat.Snippet : InsertTextFormat.PlainText);
		String documentation = prepareTemplate(buf.toString(), lineDelimiter, false);
		if (documentation.indexOf(lineDelimiter) == 0) {
			documentation = documentation.replaceFirst(lineDelimiter, "");
		}
		ci.setDocumentation(documentation);
		Map<String, String> data = new HashMap<>(3);
		data.put(CompletionResolveHandler.DATA_FIELD_URI, JDTUtils.toURI(cu));
		data.put(CompletionResolveHandler.DATA_FIELD_REQUEST_ID, "0");
		data.put(CompletionResolveHandler.DATA_FIELD_PROPOSAL_ID, "0");
		ci.setData(data);
		result.add(ci);
	} catch (BadLocationException excp) {
		// stop work
	}
	return result;
}
 
Example 8
Source File: CallHierarchyHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void reconcile(ICompilationUnit unit, IProgressMonitor monitor) throws JavaModelException {
	unit.reconcile(NO_AST, false, null, monitor);
}
 
Example 9
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void test1() throws Exception {
	requireJUnitSources();
	ICompilationUnit cu= (ICompilationUnit) javaProject.findElement(new Path("junit/runner/BaseTestRunner.java"));
	assertNotNull("BaseTestRunner.java", 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[0];
	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[] {
			"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.text.NumberFormat",
			"java.util.Properties",
			"junit.framework.AssertionFailedError",
			"junit.framework.Test",
			"junit.framework.TestListener",
			"junit.framework.TestSuite"
		});
		//@formatter:on
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 10
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();
	}
}
 
Example 11
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testStaticImports1() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package pack1;\n");
	buf.append("\n");
	buf.append("import static java.lang.System.out;\n");
	buf.append("\n");
	buf.append("public class C {\n");
	buf.append("    public int foo() {\n");
	buf.append("        out.print(File.separator);\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
	String[] order= new String[] { "java", "pack", "#java" };
	IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
	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());
		buf = new StringBuilder();
		buf.append("package pack1;\n");
		buf.append("\n");
		buf.append("import java.io.File;\n");
		buf.append("\n");
		buf.append("import static java.lang.System.out;\n");
		buf.append("\n");
		buf.append("public class C {\n");
		buf.append("    public int foo() {\n");
		buf.append("        out.print(File.separator);\n");
		buf.append("    }\n");
		buf.append("}\n");
		assertTrue(cu.getSource().equals(buf.toString()));
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 12
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testStaticImports2() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package pack1;\n");
	buf.append("\n");
	buf.append("import static java.io.File.*;\n");
	buf.append("\n");
	buf.append("public class C {\n");
	buf.append("    public String foo() {\n");
	buf.append("        return pathSeparator + separator + File.separator;\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
	String[] order= new String[] { "#java.io.File", "java", "pack" };
	IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
	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());
		buf = new StringBuilder();
		buf.append("package pack1;\n");
		buf.append("\n");
		buf.append("import static java.io.File.pathSeparator;\n");
		buf.append("import static java.io.File.separator;\n");
		buf.append("\n");
		buf.append("import java.io.File;\n");
		buf.append("\n");
		buf.append("public class C {\n");
		buf.append("    public String foo() {\n");
		buf.append("        return pathSeparator + separator + File.separator;\n");
		buf.append("    }\n");
		buf.append("}\n");
		assertTrue(cu.getSource().equals(buf.toString()));
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 13
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 14
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();
	}
}