Java Code Examples for org.eclipse.jdt.internal.corext.util.JavaModelUtil#applyEdit()

The following examples show how to use org.eclipse.jdt.internal.corext.util.JavaModelUtil#applyEdit() . 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: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addImportsToTargetUnit(final ICompilationUnit targetUnit, final IProgressMonitor monitor) throws CoreException, JavaModelException {
	monitor.beginTask("", 2); //$NON-NLS-1$
	try {
		ImportRewrite rewrite= StubUtility.createImportRewrite(targetUnit, true);
		if (fTypeImports != null) {
			ITypeBinding type= null;
			for (final Iterator<ITypeBinding> iterator= fTypeImports.iterator(); iterator.hasNext();) {
				type= iterator.next();
				rewrite.addImport(type);
			}
		}
		if (fStaticImports != null) {
			IBinding binding= null;
			for (final Iterator<IBinding> iterator= fStaticImports.iterator(); iterator.hasNext();) {
				binding= iterator.next();
				rewrite.addStaticImport(binding);
			}
		}
		fTypeImports= null;
		fStaticImports= null;
		TextEdit edits= rewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
		JavaModelUtil.applyEdit(targetUnit, edits, false, new SubProgressMonitor(monitor, 1));
	} finally {
		monitor.done();
	}
}
 
Example 2
Source File: GenerateConstructorsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGenerateConstructors_enum() throws ValidateEditException, CoreException, IOException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public enum B {\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "enum B");
	CheckConstructorsResponse response = GenerateConstructorsHandler.checkConstructorsStatus(params);
	assertNotNull(response.constructors);
	assertEquals(1, response.constructors.length);
	assertNotNull(response.fields);
	assertEquals(0, response.fields.length);

	CodeGenerationSettings settings = new CodeGenerationSettings();
	settings.createComments = false;
	TextEdit edit = GenerateConstructorsHandler.generateConstructors(unit.findPrimaryType(), response.constructors, response.fields, settings);
	assertNotNull(edit);
	JavaModelUtil.applyEdit(unit, edit, true, null);

	/* @formatter:off */
	String expected = "package p;\r\n" +
			"\r\n" +
			"public enum B {\r\n" +
			"	;\r\n" +
			"\r\n" +
			"	private B() {\r\n" +
			"	}\r\n" +
			"}";
	/* @formatter:on */

	compareSource(expected, unit.getSource());
}
 
Example 3
Source File: HashCodeEqualsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void generateHashCodeEquals(ICompilationUnit unit, String hoverOnText, boolean regenerate, boolean useJava7Objects, boolean useInstanceof, boolean useBlocks, boolean generateComments)
		throws ValidateEditException, CoreException {
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, hoverOnText);
	CheckHashCodeEqualsResponse response = HashCodeEqualsHandler.checkHashCodeEqualsStatus(params);
	GenerateHashCodeEqualsParams genParams = new GenerateHashCodeEqualsParams();
	genParams.context = params;
	genParams.fields = response.fields;
	genParams.regenerate = regenerate;
	TextEdit edit = HashCodeEqualsHandler.generateHashCodeEqualsTextEdit(genParams, useJava7Objects, useInstanceof, useBlocks, generateComments);
	assertNotNull(edit);
	JavaModelUtil.applyEdit(unit, edit, true, null);
}
 
Example 4
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void addAndApplyOverridableMethods(IType type, List<OverridableMethod> overridableMethods) throws ValidateEditException, CoreException {
	TextEdit edit = OverrideMethodsOperation.addOverridableMethods(type, overridableMethods.toArray(new OverridableMethod[overridableMethods.size()]));
	if (edit == null) {
		return;
	}
	ICompilationUnit unit = type.getCompilationUnit();
	JavaModelUtil.applyEdit(unit, edit, true, null);
	//		JavaModelUtil.reconcile(unit);
}
 
Example 5
Source File: AccessorClassCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addImportsToAccessorCu(ICompilationUnit newCu, IProgressMonitor pm) throws CoreException {
	ImportRewrite is= StubUtility.createImportRewrite(newCu, true);
	if (fIsEclipseNLS) {
		is.addImport("org.eclipse.osgi.util.NLS"); //$NON-NLS-1$
	} else {
		is.addImport("java.util.MissingResourceException"); //$NON-NLS-1$
		is.addImport("java.util.ResourceBundle"); //$NON-NLS-1$
	}
	TextEdit edit= is.rewriteImports(pm);
	JavaModelUtil.applyEdit(newCu, edit, false, null);
}
 
Example 6
Source File: GenerateToStringHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void generateToString(IType type, ToStringGenerationSettingsCore settings) throws ValidateEditException, CoreException {
	CheckToStringResponse response = GenerateToStringHandler.checkToStringStatus(type);
	TextEdit edit = GenerateToStringHandler.generateToString(type, response.fields, settings);
	assertNotNull(edit);
	JavaModelUtil.applyEdit(type.getCompilationUnit(), edit, true, null);
}
 
Example 7
Source File: AdvancedOrganizeImportsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testChooseImport() throws ValidateEditException, CoreException, IOException {
	//@formatter:off
	IPackageFragment package1 = fRoot.createPackageFragment("p1", true, null);
	ICompilationUnit unit1 = package1.createCompilationUnit("C.java", "package p1;\r\n" +
			"\r\n" +
			"public class C {\r\n" +
			"}"
			, true, null);
	IPackageFragment package2 = fRoot.createPackageFragment("p2", true, null);
	ICompilationUnit unit2 = package2.createCompilationUnit("C.java", "package p2;\r\n" +
			"\r\n" +
			"public class C {\r\n" +
			"}"
			, true, null);
	ICompilationUnit unit = fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"	C c;\r\n" +
			"}"
			, true, null);
	//@formatter:on

	TextEdit edit = OrganizeImportsHandler.organizeImports(unit, (selections) -> {
		assertEquals(1, selections.length);
		ImportSelection selection = selections[0];
		assertEquals(2, selection.candidates.length);
		assertEquals("p1.C", selection.candidates[0].fullyQualifiedName);
		assertEquals("p2.C", selection.candidates[1].fullyQualifiedName);
		assertEquals(3, selection.range.getStart().getLine());
		assertEquals(1, selection.range.getStart().getCharacter());
		assertEquals(3, selection.range.getEnd().getLine());
		assertEquals(2, selection.range.getEnd().getCharacter());
		return new ImportCandidate[] { selection.candidates[0] };
	});
	assertNotNull(edit);
	JavaModelUtil.applyEdit(unit, edit, true, null);

	/* @formatter:off */
	String expected = "package p;\r\n" +
			"\r\n" +
			"import p1.C;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"	C c;\r\n" +
			"}";
	//@formatter:on
	compareSource(expected, unit.getSource());
}
 
Example 8
Source File: AdvancedOrganizeImportsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testStaticImports() throws ValidateEditException, CoreException, IOException {
	String[] favourites = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().getJavaCompletionFavoriteMembers();
	try {
		List<String> list = new ArrayList<>();
		list.add("java.lang.Math.*");
		list.add("java.util.stream.Collectors.*");
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setJavaCompletionFavoriteMembers(list);
		//@formatter:off
		IPackageFragment pack = fRoot.createPackageFragment("p1", true, null);
		ICompilationUnit unit = pack.createCompilationUnit("C.java",
				"package p1;\n" +
				"\n" +
				"public class C {\n" +
				"    List list = List.of(1).stream().collect(toList());\n" +
				"    double i = abs(-1);\n" +
				"    double pi = PI;\n" +
				"}\n"
				, true, null);
		//@formatter:on
		TextEdit edit = OrganizeImportsHandler.organizeImports(unit, (selections) -> {
			return new ImportCandidate[0];
		});
		assertNotNull(edit);
		JavaModelUtil.applyEdit(unit, edit, true, null);
		/* @formatter:off */
		String expected = "package p1;\n" +
				"\n" +
				"import static java.lang.Math.PI;\n" +
				"import static java.lang.Math.abs;\n" +
				"import static java.util.stream.Collectors.toList;\n" +
				"\n" +
				"import java.util.List;\n" +
				"\n" +
				"public class C {\n" +
				"    List list = List.of(1).stream().collect(toList());\n" +
				"    double i = abs(-1);\n" +
				"    double pi = PI;\n" +
				"}\n";
		//@formatter:on
		compareSource(expected, unit.getSource());
	} finally {
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setJavaCompletionFavoriteMembers(Arrays.asList(favourites));
	}
}
 
Example 9
Source File: AdvancedOrganizeImportsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testAmbiguousStaticImports() throws Exception {
	importProjects("maven/salut4");
	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("salut4");
	assertTrue(ProjectUtils.isMavenProject(project));
	String[] favourites = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().getJavaCompletionFavoriteMembers();
	try {
		List<String> list = new ArrayList<>();
		list.add("org.junit.jupiter.api.Assertions.*");
		list.add("org.junit.jupiter.api.Assumptions.*");
		list.add("org.junit.jupiter.api.DynamicContainer.*");
		list.add("org.junit.jupiter.api.DynamicTest.*");
		list.add("org.hamcrest.MatcherAssert.*");
		list.add("org.hamcrest.Matchers.*");
		list.add("org.mockito.Mockito.*");
		list.add("org.mockito.ArgumentMatchers.*");
		list.add("org.mockito.Answers.*");
		list.add("org.mockito.hamcrest.MockitoHamcrest.*");
		list.add("org.mockito.Matchers.*");
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setJavaCompletionFavoriteMembers(list);
		IJavaProject javaProject = JavaCore.create(project);
		IType type = javaProject.findType("org.sample.MyTest");
		ICompilationUnit unit = type.getCompilationUnit();
		TextEdit edit = OrganizeImportsHandler.organizeImports(unit, (selections) -> {
			return new ImportCandidate[0];
		});
		assertNotNull(edit);
		JavaModelUtil.applyEdit(unit, edit, true, null);
		/* @formatter:off */
		String expected = "package org.sample;\n" +
				"\n" +
				"import static org.hamcrest.MatcherAssert.assertThat;\n" +
				"import static org.junit.jupiter.api.Assertions.assertEquals;\n" +
				"\n" +
				"import org.junit.jupiter.api.Test;\n" +
				"\n" +
				"public class MyTest {\n" +
				"    @Test\n" +
				"    public void test() {\n" +
				"        assertEquals(1, 1, \"message\");\n" +
				"        assertThat(\"test\", true);\n" +
				"        any();\n" +
				"    }\n" +
				"}\n";
		//@formatter:on
		compareSource(expected, unit.getSource());
	} finally {
		JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setJavaCompletionFavoriteMembers(Arrays.asList(favourites));
	}
}
 
Example 10
Source File: GenerateConstructorsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testGenerateConstructors() throws ValidateEditException, CoreException, IOException {
	//@formatter:off
	fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"	public B(String name) {\r\n" +
			"	}\r\n" +
			"	public B(String name, int id) {\r\n" +
			"	}\r\n" +
			"	private B() {\r\n" +
			"	}\r\n" +
			"}"
			, true, null);
	ICompilationUnit unit = fPackageP.createCompilationUnit("C.java", "package p;\r\n" +
			"\r\n" +
			"public class C extends B {\r\n" +
			"	private static String logger;\r\n" +
			"	private final String uuid = \"123\";\r\n" +
			"	private final String instance;\r\n" +
			"	private String address;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String address");
	CheckConstructorsResponse response = GenerateConstructorsHandler.checkConstructorsStatus(params);
	assertNotNull(response.constructors);
	assertEquals(2, response.constructors.length);
	assertNotNull(response.fields);
	assertEquals(2, response.fields.length);

	CodeGenerationSettings settings = new CodeGenerationSettings();
	settings.createComments = false;
	TextEdit edit = GenerateConstructorsHandler.generateConstructors(unit.findPrimaryType(), response.constructors, response.fields, settings);
	assertNotNull(edit);
	JavaModelUtil.applyEdit(unit, edit, true, null);

	/* @formatter:off */
	String expected = "package p;\r\n" +
			"\r\n" +
			"public class C extends B {\r\n" +
			"	private static String logger;\r\n" +
			"	private final String uuid = \"123\";\r\n" +
			"	private final String instance;\r\n" +
			"	private String address;\r\n" +
			"	public C(String name, String instance, String address) {\r\n" +
			"		super(name);\r\n" +
			"		this.instance = instance;\r\n" +
			"		this.address = address;\r\n" +
			"	}\r\n" +
			"	public C(String name, int id, String instance, String address) {\r\n" +
			"		super(name, id);\r\n" +
			"		this.instance = instance;\r\n" +
			"		this.address = address;\r\n" +
			"	}\r\n" +
			"}";
	/* @formatter:on */

	compareSource(expected, unit.getSource());
}
 
Example 11
Source File: GenerateAccessorsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void generateAccessors(IType type) throws ValidateEditException, CoreException {
	AccessorField[] accessors = GenerateAccessorsHandler.getUnimplementedAccessors(type);
	TextEdit edit = GenerateAccessorsHandler.generateAccessors(type, accessors, true);
	assertNotNull(edit);
	JavaModelUtil.applyEdit(type.getCompilationUnit(), edit, true, null);
}
 
Example 12
Source File: GenerateDelegateMethodsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testGenerateDelegateMethods() throws ValidateEditException, CoreException, IOException {
	//@formatter:off
	fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"	private String name;\r\n" +
			"	public String getName() {\r\n" +
			"		return this.name;\r\n" +
			"	}\r\n" +
			"	public void setName(String name) {\r\n" +
			"		this.name = name;\r\n" +
			"	}\r\n" +
			"}"
			, true, null);
	ICompilationUnit unit = fPackageP.createCompilationUnit("C.java", "package p;\r\n" +
			"\r\n" +
			"public class C {\r\n" +
			"	private int id;\r\n" +
			"	private int B[] array;\r\n" +
			"	private B b;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "B b;");
	CheckDelegateMethodsResponse response = GenerateDelegateMethodsHandler.checkDelegateMethodsStatus(params);
	assertNotNull(response.delegateFields);
	assertEquals(1, response.delegateFields.length);
	LspDelegateField delegateField = response.delegateFields[0];
	assertEquals("b", delegateField.field.name);
	assertNotNull(delegateField.delegateMethods);
	assertEquals(5, delegateField.delegateMethods.length);
	assertEquals("getName", delegateField.delegateMethods[0].name);
	assertEquals("setName", delegateField.delegateMethods[1].name);

	List<LspDelegateEntry> entries = new ArrayList<>();
	entries.add(new LspDelegateEntry(delegateField.field, delegateField.delegateMethods[0]));
	entries.add(new LspDelegateEntry(delegateField.field, delegateField.delegateMethods[1]));
	CodeGenerationSettings settings = new CodeGenerationSettings();
	settings.createComments = false;
	TextEdit edit = GenerateDelegateMethodsHandler.generateDelegateMethods(unit.findPrimaryType(), entries.toArray(new LspDelegateEntry[0]), settings);
	assertNotNull(edit);
	JavaModelUtil.applyEdit(unit, edit, true, null);

	/* @formatter:off */
	String expected = "package p;\r\n" +
			"\r\n" +
			"public class C {\r\n" +
			"	private int id;\r\n" +
			"	private int B[] array;\r\n" +
			"	private B b;\r\n" +
			"	public String getName() {\r\n" +
			"		return b.getName();\r\n" +
			"	}\r\n" +
			"	public void setName(String name) {\r\n" +
			"		b.setName(name);\r\n" +
			"	}\r\n" +
			"}";
	/* @formatter:on */

	compareSource(expected, unit.getSource());
}
 
Example 13
Source File: GenerateGetterAndSetterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void runAndApplyOperation(IType type, boolean generateComments) throws OperationCanceledException, CoreException, MalformedTreeException, BadLocationException {
	TextEdit edit = runOperation(type, generateComments);
	ICompilationUnit unit = type.getCompilationUnit();
	JavaModelUtil.applyEdit(unit, edit, true, null);
}
 
Example 14
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
void create(boolean needsSave, IProgressMonitor monitor) throws CoreException {
	TextEdit edit= fImportsRewrite.rewriteImports(monitor);
	JavaModelUtil.applyEdit(fImportsRewrite.getCompilationUnit(), edit, needsSave, null);
}