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

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#becomeWorkingCopy() . 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: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCodeAction_exception() throws JavaModelException {
	URI uri = project.getFile("nopackage/Test.java").getRawLocationURI();
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		CodeActionParams params = new CodeActionParams();
		params.setTextDocument(new TextDocumentIdentifier(uri.toString()));
		final Range range = new Range();
		range.setStart(new Position(0, 17));
		range.setEnd(new Position(0, 17));
		params.setRange(range);
		CodeActionContext context = new CodeActionContext();
		context.setDiagnostics(Collections.emptyList());
		params.setContext(context);
		List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
		Assert.assertNotNull(codeActions);
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 2
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCompletion_javadoc() throws Exception {
	IJavaProject javaProject = JavaCore.create(project);
	ICompilationUnit unit = (ICompilationUnit) javaProject.findElement(new Path("org/sample/TestJavadoc.java"));
	unit.becomeWorkingCopy(null);
	String joinOnCompletion = System.getProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
	try {
		System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, "true");
		int[] loc = findCompletionLocation(unit, "inner.");
		CompletionParams position = JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]));
		String source = unit.getSource();
		changeDocument(unit, source, 3);
		Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, new NullProgressMonitor());
		changeDocument(unit, source, 4);
		CompletionList list = server.completion(position).join().getRight();
		CompletionItem resolved = server.resolveCompletionItem(list.getItems().get(0)).join();
		assertEquals("Test ", resolved.getDocumentation().getLeft());
	} finally {
		unit.discardWorkingCopy();
		if (joinOnCompletion == null) {
			System.clearProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
		} else {
			System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, joinOnCompletion);
		}
	}
}
 
Example 3
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCompletion_nojavadoc() throws Exception {
	IJavaProject javaProject = JavaCore.create(project);
	ClientPreferences mockCapabilies = Mockito.mock(ClientPreferences.class);
	Mockito.when(preferenceManager.getClientPreferences()).thenReturn(mockCapabilies);
	Mockito.when(mockCapabilies.isSupportsCompletionDocumentationMarkdown()).thenReturn(true);
	ICompilationUnit unit = (ICompilationUnit) javaProject.findElement(new Path("org/sample/Foo5.java"));
	unit.becomeWorkingCopy(null);
	try {
		int[] loc = findCompletionLocation(unit, "nam");
		CompletionParams position = JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]));
		CompletionList list = server.completion(position).join().getRight();
		CompletionItem resolved = server.resolveCompletionItem(list.getItems().get(0)).join();
		assertNull(resolved.getDocumentation());
	} catch (Exception e) {
		fail("Unexpected exception " + e);
	} finally {
		unit.discardWorkingCopy();
	}
}
 
Example 4
Source File: HoverHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testInvalidJavadoc() throws Exception {
	importProjects("maven/aspose");
	IProject project = null;
	ICompilationUnit unit = null;
	try {
		project = ResourcesPlugin.getWorkspace().getRoot().getProject("aspose");
		IJavaProject javaProject = JavaCore.create(project);
		IType type = javaProject.findType("org.sample.TestJavadoc");
		unit = type.getCompilationUnit();
		unit.becomeWorkingCopy(null);
		String uri = JDTUtils.toURI(unit);
		TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
		TextDocumentPositionParams position = new TextDocumentPositionParams(textDocument, new Position(8, 24));
		Hover hover = handler.hover(position, monitor);
		assertNotNull(hover);
		assertNotNull(hover.getContents());
		assertEquals(1, hover.getContents().getLeft().size());
		assertEquals("com.aspose.words.Document.Document(String fileName) throws Exception", hover.getContents().getLeft().get(0).getRight().getValue());
	} finally {
		if (unit != null) {
			unit.discardWorkingCopy();
		}
	}
}
 
Example 5
Source File: BaseDocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public ICompilationUnit handleClosed(DidCloseTextDocumentParams params) {
	String uri = params.getTextDocument().getUri();
	ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
	if (unit == null) {
		return unit;
	}
	try {
		synchronized (toReconcile) {
			toReconcile.remove(unit);
		}
		if (isSyntaxMode(unit) || unit.getResource().isDerived()) {
			createDiagnosticsHandler(unit).clearDiagnostics();
		} else if (hasUnsavedChanges(unit)) {
			unit.discardWorkingCopy();
			unit.becomeWorkingCopy(new NullProgressMonitor());
			publishDiagnostics(unit, new NullProgressMonitor());
		}
		if (unit.equals(sharedASTProvider.getActiveJavaElement())) {
			sharedASTProvider.disposeAST();
		}
		unit.discardWorkingCopy();
		if (JDTUtils.isDefaultProject(unit)) {
			File f = new File(unit.getUnderlyingResource().getLocationURI());
			if (!f.exists()) {
				unit.delete(true, null);
			}
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Error while handling document close. URI: " + uri, e);
	}

	return unit;
}
 
Example 6
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletion_javadocMarkdown() throws Exception {
	IJavaProject javaProject = JavaCore.create(project);
	ClientPreferences mockCapabilies = Mockito.mock(ClientPreferences.class);
	Mockito.when(preferenceManager.getClientPreferences()).thenReturn(mockCapabilies);
	Mockito.when(mockCapabilies.isSupportsCompletionDocumentationMarkdown()).thenReturn(true);
	ICompilationUnit unit = (ICompilationUnit) javaProject.findElement(new Path("org/sample/TestJavadoc.java"));
	unit.becomeWorkingCopy(null);
	String joinOnCompletion = System.getProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
	try {
		System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, "true");
		int[] loc = findCompletionLocation(unit, "inner.");
		CompletionParams position = JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]));
		String source = unit.getSource();
		changeDocument(unit, source, 3);
		Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, new NullProgressMonitor());
		changeDocument(unit, source, 4);
		CompletionList list = server.completion(position).join().getRight();
		CompletionItem resolved = server.resolveCompletionItem(list.getItems().get(0)).join();
		MarkupContent markup = resolved.getDocumentation().getRight();
		assertNotNull(markup);
		assertEquals(MarkupKind.MARKDOWN, markup.getKind());
		assertEquals("Test", markup.getValue());
	} finally {
		unit.discardWorkingCopy();
		if (joinOnCompletion == null) {
			System.clearProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
		} else {
			System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, joinOnCompletion);
		}
	}
}
 
Example 7
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Nonnull
protected final CompilationUnit createWorkingCopy(@Nonnull ICompilationUnit unit) throws JavaModelException {
    unit.becomeWorkingCopy(monitor);
    ASTParser parser = createAstParser();
    parser.setSource(unit);
    parser.setResolveBindings(resolveBindings());
    return (CompilationUnit) parser.createAST(monitor);
}
 
Example 8
Source File: BaseDocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ICompilationUnit checkPackageDeclaration(String uri, ICompilationUnit unit) {
	if (unit.getResource() != null && unit.getJavaProject() != null && unit.getJavaProject().getProject().getName().equals(ProjectsManager.DEFAULT_PROJECT_NAME)) {
		try {
			CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
			IProblem[] problems = astRoot.getProblems();
			for (IProblem problem : problems) {
				if (problem.getID() == IProblem.PackageIsNotExpectedPackage) {
					IResource file = unit.getResource();
					boolean toRemove = file.isLinked();
					if (toRemove) {
						IPath path = file.getParent().getProjectRelativePath();
						if (path.segmentCount() > 0 && JDTUtils.SRC.equals(path.segments()[0])) {
							String packageNameResource = path.removeFirstSegments(1).toString().replace(JDTUtils.PATH_SEPARATOR, JDTUtils.PERIOD);
							path = file.getLocation();
							if (path != null && path.segmentCount() > 0) {
								path = path.removeLastSegments(1);
								String pathStr = path.toString().replace(JDTUtils.PATH_SEPARATOR, JDTUtils.PERIOD);
								if (pathStr.endsWith(packageNameResource)) {
									toRemove = false;
								}
							}
						}
					}
					if (toRemove) {
						file.delete(true, new NullProgressMonitor());
						if (unit.equals(sharedASTProvider.getActiveJavaElement())) {
							sharedASTProvider.disposeAST();
						}
						unit.discardWorkingCopy();
						unit = JDTUtils.resolveCompilationUnit(uri);
						unit.becomeWorkingCopy(new NullProgressMonitor());
						triggerValidation(unit);
					}
					break;
				}
			}

		} catch (CoreException e) {
			JavaLanguageServerPlugin.logException(e.getMessage(), e);
		}
	}
	return unit;
}
 
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();
	}
}
 
Example 15
Source File: TypeCreator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the new type.
 *
 * NOTE: If this method throws a {@link JavaModelException}, its {@link JavaModelException#getJavaModelStatus()}
 * method can provide more detailed information about the problem.
 */
public IType createType() throws CoreException {
  IProgressMonitor monitor = new NullProgressMonitor();

  ICompilationUnit cu = null;
  try {
    String cuName = simpleTypeName + ".java";

    // Create empty compilation unit
    cu = pckg.createCompilationUnit(cuName, "", false, monitor);
    cu.becomeWorkingCopy(monitor);
    IBuffer buffer = cu.getBuffer();

    // Need to create a minimal type stub here so we can create an import
    // rewriter a few lines down. The rewriter has to be in place when we
    // create the real type stub, so we can use it to transform the names of
    // any interfaces this type extends/implements.
    String dummyTypeStub = createDummyTypeStub();

    // Generate the content (file comment, package declaration, type stub)
    String cuContent = createCuContent(cu, dummyTypeStub);
    buffer.setContents(cuContent);

    ImportRewrite imports = StubUtility.createImportRewrite(cu, true);

    // Create the real type stub and replace the dummy one
    int typeDeclOffset = cuContent.lastIndexOf(dummyTypeStub);
    if (typeDeclOffset != -1) {
      String typeStub = createTypeStub(cu, imports);
      buffer.replace(typeDeclOffset, dummyTypeStub.length(), typeStub);
    }

    // Let our subclasses add members
    IType type = cu.getType(simpleTypeName);
    createTypeMembers(type, imports);

    // Rewrite the imports and apply the edit
    TextEdit edit = imports.rewriteImports(monitor);
    applyEdit(cu, edit, false, null);

    // Format the Java code
    String formattedSource = formatJava(type);
    buffer.setContents(formattedSource);

    // Save the new type
    JavaModelUtil.reconcile(cu);
    cu.commitWorkingCopy(true, monitor);

    return type;
  } finally {
    if (cu != null) {
      cu.discardWorkingCopy();
    }
  }
}
 
Example 16
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createPackageInfoJava(IProgressMonitor monitor) throws CoreException {
	String lineDelimiter= StubUtility.getLineDelimiterUsed(fCreatedPackageFragment.getJavaProject());
	StringBuilder content = new StringBuilder();
	String fileComment= getFileComment(lineDelimiter);
	String typeComment= getTypeComment(lineDelimiter);
	
	if (fileComment != null) {
		content.append(fileComment);
		content.append(lineDelimiter);
	}

	if (typeComment != null) {
		content.append(typeComment);
		content.append(lineDelimiter);
	} else if (fileComment != null) {
		// insert an empty file comment to avoid that the file comment becomes the type comment
		content.append("/**");  //$NON-NLS-1$
		content.append(lineDelimiter);
		content.append(" *"); //$NON-NLS-1$
		content.append(lineDelimiter);
		content.append(" */"); //$NON-NLS-1$
		content.append(lineDelimiter);
	}

	content.append("package "); //$NON-NLS-1$
	content.append(fCreatedPackageFragment.getElementName());
	content.append(";"); //$NON-NLS-1$

	ICompilationUnit compilationUnit= fCreatedPackageFragment.createCompilationUnit(PACKAGE_INFO_JAVA_FILENAME, content.toString(), true, monitor);

	JavaModelUtil.reconcile(compilationUnit);

	compilationUnit.becomeWorkingCopy(monitor);
	try {
		IBuffer buffer= compilationUnit.getBuffer();
		ISourceRange sourceRange= compilationUnit.getSourceRange();
		String originalContent= buffer.getText(sourceRange.getOffset(), sourceRange.getLength());

		String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_COMPILATION_UNIT, originalContent, 0, lineDelimiter, fCreatedPackageFragment.getJavaProject());
		formattedContent= Strings.trimLeadingTabsAndSpaces(formattedContent);
		buffer.replace(sourceRange.getOffset(), sourceRange.getLength(), formattedContent);
		compilationUnit.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
	} finally {
		compilationUnit.discardWorkingCopy();
	}
}
 
Example 17
Source File: CompilationUnitDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected FileInfo createFileInfo(Object element) throws CoreException {
	ICompilationUnit original= null;
	if (element instanceof IFileEditorInput) {
		IFileEditorInput input= (IFileEditorInput) element;
		original= createCompilationUnit(input.getFile());
		if (original == null)
			return null;
	}

	FileInfo info= super.createFileInfo(element);
	if (!(info instanceof CompilationUnitInfo))
		return null;

	if (original == null)
		original= createFakeCompiltationUnit(element, false);
	if (original == null)
		return null;

	CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
	setUpSynchronization(cuInfo);

	IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null;
	if (requestor instanceof IProblemRequestorExtension) {
		IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor;
		extension.setIsActive(false);
		extension.setIsHandlingTemporaryProblems(isHandlingTemporaryProblems());
	}

	IResource resource= original.getResource();
	if (JavaModelUtil.isPrimary(original) && (resource == null || resource.exists()))
		original.becomeWorkingCopy(requestor, getProgressMonitor());
	cuInfo.fCopy= original;

	if (cuInfo.fModel instanceof CompilationUnitAnnotationModel)   {
		CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel;
		model.setCompilationUnit(cuInfo.fCopy);
	}

	if (cuInfo.fModel != null)
		cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener);

	return cuInfo;
}