Java Code Examples for org.eclipse.jdt.core.ICompilationUnit#discardWorkingCopy()
The following examples show how to use
org.eclipse.jdt.core.ICompilationUnit#discardWorkingCopy() .
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: HoverHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@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 2
Source File: CodeActionHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@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 3
Source File: MoveInnerToTopRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private Change createCompilationUnitForMovedType(IProgressMonitor pm) throws CoreException { ICompilationUnit newCuWC= null; try { newCuWC= fType.getPackageFragment().getCompilationUnit(JavaModelUtil.getRenamedCUName(fType.getCompilationUnit(), fType.getElementName())).getWorkingCopy(null); String source= createSourceForNewCu(newCuWC, pm); return new CreateCompilationUnitChange(fType.getPackageFragment().getCompilationUnit(JavaModelUtil.getRenamedCUName(fType.getCompilationUnit(), fType.getElementName())), source, null); } finally { if (newCuWC != null) newCuWC.discardWorkingCopy(); } }
Example 4
Source File: CreateCopyOfCompilationUnitChange.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private static String getCopiedFileSource(IProgressMonitor monitor, ICompilationUnit unit, String newTypeName) throws CoreException { ICompilationUnit copy= unit.getPrimary().getWorkingCopy(null); try { TextChangeManager manager= createChangeManager(monitor, copy, newTypeName); String result= manager.get(copy).getPreviewContent(new NullProgressMonitor()); return result; } finally { copy.discardWorkingCopy(); } }
Example 5
Source File: WorkspaceEventHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@After public void tearDown() throws Exception { javaClient.disconnect(); handler.removeResourceChangeListener(); for (ICompilationUnit cu : JavaCore.getWorkingCopies(null)) { cu.discardWorkingCopy(); } }
Example 6
Source File: BugResolution.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
@CheckForNull private PendingRewrite resolveWithoutWriting(IMarker marker) { requireNonNull(marker, "marker"); ICompilationUnit originalUnit = null; try { BugInstance bug = MarkerUtil.findBugInstanceForMarker(marker); if (bug == null) { throw new BugResolutionException(MISSING_BUG_INSTANCE); } IProject project = marker.getResource().getProject(); originalUnit = getCompilationUnit(marker); if (originalUnit == null) { throw new BugResolutionException("No compilation unit found for marker " + marker.getType() + " (" + marker.getId() + ')'); } Document doc = new Document(originalUnit.getBuffer().getContents()); CompilationUnit workingUnit = makeOrReuseWorkingCopy(originalUnit); ASTRewrite rewrite = makeOrReuseRewrite(workingUnit); repairBug(rewrite, workingUnit, bug); marker.delete(); FindbugsPlugin.getBugCollection(project, monitor).remove(bug); return new PendingRewrite(rewrite, doc, originalUnit); } catch (BugResolutionException | CoreException e) { try { if (originalUnit != null) { originalUnit.discardWorkingCopy(); } } catch (JavaModelException e1) { reportException(e1); } reportException(e); return null; } }
Example 7
Source File: SemanticHighlightingTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@After public void tearDown() throws Exception { javaClient.disconnect(); for (ICompilationUnit unit : JavaCore.getWorkingCopies(null)) { unit.discardWorkingCopy(); } }
Example 8
Source File: MavenClasspathTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@After public void tearDown() throws Exception { sharedASTProvider.disposeAST(); javaClient.disconnect(); for (ICompilationUnit cu : JavaCore.getWorkingCopies(null)) { cu.discardWorkingCopy(); } }
Example 9
Source File: SuperTypeRefactoringProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Resets the working copies. */ protected void resetWorkingCopies() { final ICompilationUnit[] units= JavaCore.getWorkingCopies(fOwner); for (int index= 0; index < units.length; index++) { final ICompilationUnit unit= units[index]; try { unit.discardWorkingCopy(); } catch (Exception exception) { // Do nothing } } }
Example 10
Source File: AccessorClassCreator.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private String getUnformattedSource(IProgressMonitor pm) throws CoreException { ICompilationUnit newCu= null; try { newCu= fAccessorPackage.getCompilationUnit(fAccessorPath.lastSegment()).getWorkingCopy(null); String typeComment= null, fileComment= null; final IJavaProject project= newCu.getJavaProject(); final String lineDelim= StubUtility.getLineDelimiterUsed(project); if (StubUtility.doAddComments(project)) { typeComment= CodeGeneration.getTypeComment(newCu, fAccessorClassName, lineDelim); fileComment= CodeGeneration.getFileComment(newCu, lineDelim); } String classContent= createClass(lineDelim); String cuContent= CodeGeneration.getCompilationUnitContent(newCu, fileComment, typeComment, classContent, lineDelim); if (cuContent == null) { StringBuffer buf= new StringBuffer(); if (fileComment != null) { buf.append(fileComment).append(lineDelim); } if (!fAccessorPackage.isDefaultPackage()) { buf.append("package ").append(fAccessorPackage.getElementName()).append(';'); //$NON-NLS-1$ } buf.append(lineDelim).append(lineDelim); if (typeComment != null) { buf.append(typeComment).append(lineDelim); } buf.append(classContent); cuContent= buf.toString(); } newCu.getBuffer().setContents(cuContent); addImportsToAccessorCu(newCu, pm); return newCu.getSource(); } finally { if (newCu != null) { newCu.discardWorkingCopy(); } } }
Example 11
Source File: TypeContextChecker.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private ITypeBinding[] resolveBindings(String[] types, RefactoringStatus[] results, boolean firstPass) throws CoreException { //TODO: split types into parameterTypes and returnType int parameterCount= types.length - 1; ITypeBinding[] typeBindings= new ITypeBinding[types.length]; StringBuffer cuString= new StringBuffer(); cuString.append(fStubTypeContext.getBeforeString()); int offsetBeforeMethodName= appendMethodDeclaration(cuString, types, parameterCount); cuString.append(fStubTypeContext.getAfterString()); // need a working copy to tell the parser where to resolve (package visible) types ICompilationUnit wc= fMethod.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor()); try { wc.getBuffer().setContents(cuString.toString()); CompilationUnit compilationUnit= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(wc, true); ASTNode method= NodeFinder.perform(compilationUnit, offsetBeforeMethodName, METHOD_NAME.length()).getParent(); Type[] typeNodes= new Type[types.length]; if (method instanceof MethodDeclaration) { MethodDeclaration methodDeclaration= (MethodDeclaration) method; typeNodes[parameterCount]= methodDeclaration.getReturnType2(); List<SingleVariableDeclaration> parameters= methodDeclaration.parameters(); for (int i= 0; i < parameterCount; i++) typeNodes[i]= parameters.get(i).getType(); } else if (method instanceof AnnotationTypeMemberDeclaration) { typeNodes[0]= ((AnnotationTypeMemberDeclaration) method).getType(); } for (int i= 0; i < types.length; i++) { Type type= typeNodes[i]; if (type == null) { String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_couldNotResolveType, BasicElementLabels.getJavaElementName(types[i])); results[i]= RefactoringStatus.createErrorStatus(msg); continue; } results[i]= new RefactoringStatus(); IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS); if (problems.length > 0) { for (int p= 0; p < problems.length; p++) if (isError(problems[p], type)) results[i].addError(problems[p].getMessage()); } ITypeBinding binding= handleBug84585(type.resolveBinding()); if (firstPass && (binding == null || binding.isRecovered())) { types[i]= qualifyTypes(type, results[i]); } typeBindings[i]= binding; } return typeBindings; } finally { wc.discardWorkingCopy(); } }
Example 12
Source File: NonProjectFixTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
@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 13
Source File: NonProjectFixTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
@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 14
Source File: TypeCreator.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 4 votes |
/** * 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 15
Source File: NewPackageWizardPage.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
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 16
Source File: SimilarElementsRequestor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
public static String[] getStaticImportFavorites(ICompilationUnit cu, final String elementName, boolean isMethod, String[] favorites) throws JavaModelException { StringBuffer dummyCU= new StringBuffer(); String packName= cu.getParent().getElementName(); IType type= cu.findPrimaryType(); if (type == null) return new String[0]; if (packName.length() > 0) { dummyCU.append("package ").append(packName).append(';'); //$NON-NLS-1$ } dummyCU.append("public class ").append(type.getElementName()).append("{\n static {\n").append(elementName); // static initializer //$NON-NLS-1$//$NON-NLS-2$ int offset= dummyCU.length(); dummyCU.append("\n}\n }"); //$NON-NLS-1$ ICompilationUnit newCU= null; try { newCU= cu.getWorkingCopy(null); newCU.getBuffer().setContents(dummyCU.toString()); final HashSet<String> result= new HashSet<String>(); CompletionRequestor requestor= new CompletionRequestor(true) { @Override public void accept(CompletionProposal proposal) { if (elementName.equals(new String(proposal.getName()))) { CompletionProposal[] requiredProposals= proposal.getRequiredProposals(); for (int i= 0; i < requiredProposals.length; i++) { CompletionProposal curr= requiredProposals[i]; if (curr.getKind() == CompletionProposal.METHOD_IMPORT || curr.getKind() == CompletionProposal.FIELD_IMPORT) { result.add(JavaModelUtil.concatenateName(Signature.toCharArray(curr.getDeclarationSignature()), curr.getName())); } } } } }; if (isMethod) { requestor.setIgnored(CompletionProposal.METHOD_REF, false); requestor.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT, true); } else { requestor.setIgnored(CompletionProposal.FIELD_REF, false); requestor.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT, true); } requestor.setFavoriteReferences(favorites); newCU.codeComplete(offset, requestor); return result.toArray(new String[result.size()]); } finally { if (newCU != null) { newCU.discardWorkingCopy(); } } }
Example 17
Source File: SimilarElementsRequestor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
public static String[] getStaticImportFavorites(ICompilationUnit cu, final String elementName, boolean isMethod, String[] favorites) throws JavaModelException { StringBuffer dummyCU= new StringBuffer(); String packName= cu.getParent().getElementName(); IType type= cu.findPrimaryType(); if (type == null) { return new String[0]; } if (packName.length() > 0) { dummyCU.append("package ").append(packName).append(';'); //$NON-NLS-1$ } dummyCU.append("public class ").append(type.getElementName()).append("{\n static {\n").append(elementName); // static initializer //$NON-NLS-1$//$NON-NLS-2$ int offset= dummyCU.length(); dummyCU.append("\n}\n }"); //$NON-NLS-1$ ICompilationUnit newCU= null; try { newCU= cu.getWorkingCopy(null); newCU.getBuffer().setContents(dummyCU.toString()); final HashSet<String> result= new HashSet<>(); CompletionRequestor requestor= new CompletionRequestor(true) { @Override public void accept(CompletionProposal proposal) { if (elementName.equals(new String(proposal.getName()))) { CompletionProposal[] requiredProposals= proposal.getRequiredProposals(); for (int i= 0; i < requiredProposals.length; i++) { CompletionProposal curr= requiredProposals[i]; if (curr.getKind() == CompletionProposal.METHOD_IMPORT || curr.getKind() == CompletionProposal.FIELD_IMPORT) { result.add(JavaModelUtil.concatenateName(Signature.toCharArray(curr.getDeclarationSignature()), curr.getName())); } } } } }; if (isMethod) { requestor.setIgnored(CompletionProposal.METHOD_REF, false); requestor.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT, true); } else { requestor.setIgnored(CompletionProposal.FIELD_REF, false); requestor.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT, true); } requestor.setFavoriteReferences(favorites); newCU.codeComplete(offset, requestor); return result.toArray(new String[result.size()]); } finally { if (newCU != null) { newCU.discardWorkingCopy(); } } }
Example 18
Source File: ImportOrganizeTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
@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 19
Source File: TypeContextChecker.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
public static ITypeBinding[] resolveSuperInterfaces(String[] interfaces, IType typeHandle, StubTypeContext superInterfaceContext) { ITypeBinding[] result= new ITypeBinding[interfaces.length]; int[] interfaceOffsets= new int[interfaces.length]; StringBuffer cuString= new StringBuffer(); cuString.append(superInterfaceContext.getBeforeString()); int last= interfaces.length - 1; for (int i= 0; i <= last; i++) { interfaceOffsets[i]= cuString.length(); cuString.append(interfaces[i]); if (i != last) cuString.append(", "); //$NON-NLS-1$ } cuString.append(superInterfaceContext.getAfterString()); try { ICompilationUnit wc= typeHandle.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor()); try { wc.getBuffer().setContents(cuString.toString()); CompilationUnit compilationUnit= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(wc, true); for (int i= 0; i <= last; i++) { ASTNode type= NodeFinder.perform(compilationUnit, interfaceOffsets[i], interfaces[i].length()); if (type instanceof Type) { result[i]= handleBug84585(((Type) type).resolveBinding()); } else if (type instanceof Name) { ASTNode parent= type.getParent(); if (parent instanceof Type) { result[i]= handleBug84585(((Type) parent).resolveBinding()); } else { throw new IllegalStateException(); } } else { throw new IllegalStateException(); } } } finally { wc.discardWorkingCopy(); } } catch (JavaModelException e) { // won't happen } return result; }
Example 20
Source File: ParameterObjectFactory.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
public List<ResourceChange> createTopLevelParameterObject(IPackageFragmentRoot packageFragmentRoot, CreationListener listener) throws CoreException { List<ResourceChange> changes= new ArrayList<ResourceChange>(); IPackageFragment packageFragment= packageFragmentRoot.getPackageFragment(getPackage()); if (!packageFragment.exists()) { changes.add(new CreatePackageChange(packageFragment)); } ICompilationUnit unit= packageFragment.getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX); Assert.isTrue(!unit.exists()); IJavaProject javaProject= unit.getJavaProject(); ICompilationUnit workingCopy= unit.getWorkingCopy(null); try { // create stub with comments and dummy type String lineDelimiter= StubUtility.getLineDelimiterUsed(javaProject); String fileComment= getFileComment(workingCopy, lineDelimiter); String typeComment= getTypeComment(workingCopy, lineDelimiter); String content= CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment, "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$ workingCopy.getBuffer().setContents(content); CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(workingCopy); ASTRewrite rewriter= cuRewrite.getASTRewrite(); CompilationUnit root= cuRewrite.getRoot(); AST ast= cuRewrite.getAST(); ImportRewrite importRewrite= cuRewrite.getImportRewrite(); // retrieve&replace dummy type with real class ListRewrite types= rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY); ASTNode dummyType= (ASTNode) types.getOriginalList().get(0); String newTypeName= JavaModelUtil.concatenateName(getPackage(), getClassName()); TypeDeclaration classDeclaration= createClassDeclaration(newTypeName, cuRewrite, listener); classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); Javadoc javadoc= (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY); rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null); types.replace(dummyType, classDeclaration, null); // Apply rewrites and discard workingcopy // Using CompilationUnitRewrite.createChange() leads to strange // results String charset= ResourceUtil.getFile(unit).getCharset(false); Document document= new Document(content); try { rewriter.rewriteAST().apply(document); TextEdit rewriteImports= importRewrite.rewriteImports(null); rewriteImports.apply(document); } catch (BadLocationException e) { throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error, e)); } String docContent= document.get(); CreateCompilationUnitChange compilationUnitChange= new CreateCompilationUnitChange(unit, docContent, charset); changes.add(compilationUnitChange); } finally { workingCopy.discardWorkingCopy(); } return changes; }