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

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#getJavaProject() . 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: FillArgumentNamesCompletionProposalCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
IJavaCompletionProposal createTypeProposal(CompletionProposal typeProposal) {
	final ICompilationUnit cu= getCompilationUnit();
	if (cu == null || getContext() != null && getContext().isInJavadoc())
		return super.createJavaCompletionProposal(typeProposal);

	IJavaProject project= cu.getJavaProject();
	if (!shouldProposeGenerics(project))
		return super.createJavaCompletionProposal(typeProposal);

	char[] completion= typeProposal.getCompletion();
	// don't add parameters for import-completions nor for proposals with an empty completion (e.g. inside the type argument list)
	if (completion.length > 0 && (completion[completion.length - 1] == ';' || completion[completion.length - 1] == '.'))
		return super.createJavaCompletionProposal(typeProposal);

	LazyJavaCompletionProposal newProposal= new LazyGenericTypeProposal(typeProposal, getInvocationContext());
	return newProposal;
}
 
Example 2
Source File: CleanUpPostSaveListener.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private CompilationUnit createAst(ICompilationUnit unit, Map<String, String> cleanUpOptions, IProgressMonitor monitor) {
	IJavaProject project= unit.getJavaProject();
	if (compatibleOptions(project, cleanUpOptions)) {
		CompilationUnit ast= SharedASTProvider.getAST(unit, SharedASTProvider.WAIT_NO, monitor);
		if (ast != null)
			return ast;
	}

	ASTParser parser= CleanUpRefactoring.createCleanUpASTParser();
	parser.setSource(unit);

	Map<String, String> compilerOptions= RefactoringASTParser.getCompilerOptions(unit.getJavaProject());
	compilerOptions.putAll(cleanUpOptions);
	parser.setCompilerOptions(compilerOptions);

	return (CompilationUnit)parser.createAST(monitor);
}
 
Example 3
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Don't use this method directly, use CodeGeneration.
 * 
 * @param templateID the template id of the type body to get. Valid id's are
 *            {@link CodeTemplateContextType#CLASSBODY_ID},
 *            {@link CodeTemplateContextType#INTERFACEBODY_ID},
 *            {@link CodeTemplateContextType#ENUMBODY_ID},
 *            {@link CodeTemplateContextType#ANNOTATIONBODY_ID},
 * @param cu the compilation unit to which the template is added
 * @param typeName the type name
 * @param lineDelim the line delimiter to use
 * @return return the type body template or <code>null</code>
 * @throws CoreException thrown if the template could not be evaluated
 * @see org.eclipse.jdt.ui.CodeGeneration#getTypeBody(String, ICompilationUnit, String, String)
 */
public static String getTypeBody(String templateID, ICompilationUnit cu, String typeName, String lineDelim) throws CoreException {
	if (!VALID_TYPE_BODY_TEMPLATES.contains(templateID)) {
		throw new IllegalArgumentException("Invalid code template ID: " + templateID); //$NON-NLS-1$
	}

	Template template= getCodeTemplate(templateID, cu.getJavaProject());
	if (template == null) {
		return null;
	}
	CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelim);
	context.setCompilationUnitVariables(cu);
	context.setVariable(CodeTemplateContextType.TYPENAME, typeName);

	return evaluateTemplate(context, template);
}
 
Example 4
Source File: NLSScanner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static NLSLine[] scan(ICompilationUnit cu) throws JavaModelException, BadLocationException, InvalidInputException {
	IJavaProject javaProject= cu.getJavaProject();
	IScanner scanner= null;
	if (javaProject != null) {
		String complianceLevel= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
		String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
		scanner= ToolFactory.createScanner(true, true, true, sourceLevel, complianceLevel);
	} else {
		scanner= ToolFactory.createScanner(true, true, false, true);
	}
	return scan(scanner, cu.getBuffer().getCharacters());
}
 
Example 5
Source File: IndentAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the <code>IJavaProject</code> of the current editor input, or
 * <code>null</code> if it cannot be found.
 *
 * @return the <code>IJavaProject</code> of the current editor input, or
 *         <code>null</code> if it cannot be found
 * @since 3.1
 */
private IJavaProject getJavaProject() {
	ITextEditor editor= getTextEditor();
	if (editor == null)
		return null;

	ICompilationUnit cu= JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
	if (cu == null)
		return null;
	return cu.getJavaProject();
}
 
Example 6
Source File: CuCollectingSearchRequestor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected IScanner getScanner(ICompilationUnit unit) {
	IJavaProject project= unit.getJavaProject();
	if (project.equals(fProjectCache)) {
		return fScannerCache;
	}

	fProjectCache= project;
	String sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true);
	String complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	fScannerCache= ToolFactory.createScanner(false, false, false, sourceLevel, complianceLevel);
	return fScannerCache;
}
 
Example 7
Source File: NLSScanner.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static NLSLine[] scan(ICompilationUnit cu) throws JavaModelException, BadLocationException, InvalidInputException {
	IJavaProject javaProject= cu.getJavaProject();
	IScanner scanner= null;
	if (javaProject != null) {
		String complianceLevel= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
		String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
		scanner= ToolFactory.createScanner(true, true, true, sourceLevel, complianceLevel);
	} else {
		scanner= ToolFactory.createScanner(true, true, false, true);
	}
	return scan(scanner, cu.getBuffer().getCharacters());
}
 
Example 8
Source File: JFaceCompletionProposalComputer.java    From saneclipse with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected TemplateEngine computeCompletionEngine(JavaContentAssistInvocationContext context) {
	final ICompilationUnit unit = context.getCompilationUnit();
	if (unit == null) {
		return null;
	}

	final IJavaProject javaProject = unit.getJavaProject();
	if (javaProject == null) {
		return null;
	}

	if (isJFaceOnClasspath(javaProject)) {
		final CompletionContext coreContext = context.getCoreContext();
		if (coreContext != null) {
			final int tokenLocation = coreContext.getTokenLocation();
			if ((tokenLocation & CompletionContext.TL_MEMBER_START) != 0) {
				return jFaceMembersTemplateEngine;
			}
			if ((tokenLocation & CompletionContext.TL_STATEMENT_START) != 0) {
				return jFaceStatementsTemplateEngine;
			}
		}
		return jFaceTemplateEngine;
	}

	return null;
}
 
Example 9
Source File: LazyJavaCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected FormatterPrefs getFormatterPrefs() {
	if (fFormatterPrefs == null) {
		ICompilationUnit cu= fInvocationContext.getCompilationUnit();
		fFormatterPrefs= new FormatterPrefs(cu == null ? null : cu.getJavaProject());
	}
	return fFormatterPrefs;
}
 
Example 10
Source File: SurroundWithTryMultiCatchAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(ITextSelection selection) {
	ICompilationUnit compilationUnit= SelectionConverter.getInputAsCompilationUnit(fEditor);
	IJavaProject javaProject= compilationUnit.getJavaProject();
	if (!JavaModelUtil.is17OrHigher(javaProject)) {
		String message= Messages.format(RefactoringMessages.SurroundWithTryMultiCatchAction_not17, BasicElementLabels.getJavaElementName(javaProject.getElementName()));
		MessageDialog.openInformation(JavaPlugin.getActiveWorkbenchShell(), getDialogTitle(), message);
		return;
	}
	super.run(selection);
}
 
Example 11
Source File: AccessorClassCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 12
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createSetter(ParameterInfo pi, String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit cu= cuRewrite.getCu();
	IJavaProject project= cu.getJavaProject();

	MethodDeclaration methodDeclaration= ast.newMethodDeclaration();
	String fieldName= pi.getNewName();
	String setterName= getSetterName(pi, ast, project);
	String lineDelim= StubUtility.getLineDelimiterUsed(cu);
	String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project);
	String paramName= StubUtility.suggestArgumentName(project, bareFieldname, null);
	if (createComments(project)) {
		String comment= CodeGeneration.getSetterComment(cu, declaringType, setterName, fieldName, pi.getNewTypeName(), paramName, bareFieldname, lineDelim);
		if (comment != null)
			methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC));
	}
	methodDeclaration.setName(ast.newSimpleName(setterName));
	methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
	variable.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	variable.setName(ast.newSimpleName(paramName));
	methodDeclaration.parameters().add(variable);
	Block block= ast.newBlock();
	methodDeclaration.setBody(block);
	boolean useThis= StubUtility.useThisForFieldAccess(project);
	if (useThis || fieldName.equals(paramName)) {
		fieldName= "this." + fieldName; //$NON-NLS-1$
	}
	String bodyContent= CodeGeneration.getSetterMethodBodyContent(cu, declaringType, setterName, fieldName, paramName, lineDelim);
	ASTNode setterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT);
	block.statements().add(setterBody);
	return methodDeclaration;
}
 
Example 13
Source File: PackageExplorerContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isOnClassPath(ICompilationUnit element) {
	IJavaProject project= element.getJavaProject();
	if (project == null || !project.exists())
		return false;
	return project.isOnClasspath(element);
}
 
Example 14
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static boolean isOnClassPath(ICompilationUnit unit) {
	if (unit != null && unit.getJavaProject() != null && !unit.getJavaProject().getProject().equals(JavaLanguageServerPlugin.getProjectsManager().getDefaultProject())) {
		return unit.getJavaProject().isOnClasspath(unit);
	}
	return false;
}
 
Example 15
Source File: ReorgCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	boolean isLinked = cu.getResource().isLinked();

	IJavaProject javaProject= cu.getJavaProject();
	String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String compliance= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);

	CompilationUnit root= context.getASTRoot();

	ASTNode coveredNode= problem.getCoveredNode(root);
	if (!(coveredNode instanceof SimpleName)) {
		return;
	}

	ASTNode parentType= coveredNode.getParent();
	if (!(parentType instanceof AbstractTypeDeclaration)) {
		return;
	}

	String currTypeName= ((SimpleName) coveredNode).getIdentifier();
	String newTypeName= JavaCore.removeJavaLikeExtension(cu.getElementName());


	boolean hasOtherPublicTypeBefore = false;

	boolean found = false;
	List<AbstractTypeDeclaration> types= root.types();
	for (int i= 0; i < types.size(); i++) {
		AbstractTypeDeclaration curr= types.get(i);
		if (parentType != curr) {
			if (newTypeName.equals(curr.getName().getIdentifier())) {
				return;
			}
			if (!found && Modifier.isPublic(curr.getModifiers())) {
				hasOtherPublicTypeBefore = true;
			}
		} else {
			found = true;
		}
	}

	if (!JavaConventions.validateJavaTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
		proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, IProposalRelevance.RENAME_TYPE));
	}

	if (!hasOtherPublicTypeBefore && JavaLanguageServerPlugin.getPreferencesManager().getClientPreferences().isResourceOperationSupported()) {
		String newCUName = JavaModelUtil.getRenamedCUName(cu, currTypeName);
		ICompilationUnit newCU = ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
		if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
			RenameCompilationUnitChange change = new RenameCompilationUnitChange(cu, newCUName);

			// rename CU
			String label = Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, BasicElementLabels.getResourceName(newCUName));
			proposals.add(new ChangeCorrectionProposal(label, CodeActionKind.QuickFix, change, IProposalRelevance.RENAME_CU));
		}
	}

}
 
Example 16
Source File: OrganizeImportsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static TextEdit wrapStaticImports(TextEdit edit, CompilationUnit root, ICompilationUnit unit) throws MalformedTreeException, CoreException {
	String[] favourites = PreferenceManager.getPrefs(unit.getResource()).getJavaCompletionFavoriteMembers();
	if (favourites.length == 0) {
		return edit;
	}
	IJavaProject project = unit.getJavaProject();
	if (JavaModelUtil.is50OrHigher(project)) {
		List<SimpleName> typeReferences = new ArrayList<>();
		List<SimpleName> staticReferences = new ArrayList<>();
		ImportReferencesCollector.collect(root, project, null, typeReferences, staticReferences);
		if (staticReferences.isEmpty()) {
			return edit;
		}
		ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(root, true);
		AST ast = root.getAST();
		ASTRewrite astRewrite = ASTRewrite.create(ast);
		for (SimpleName node : staticReferences) {
			addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, true);
			addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, false);
		}
		TextEdit staticEdit = importRewrite.rewriteImports(null);
		if (staticEdit != null && staticEdit.getChildrenSize() > 0) {
			TextEdit lastStatic = staticEdit.getChildren()[staticEdit.getChildrenSize() - 1];
			if (lastStatic instanceof DeleteEdit) {
				if (edit.getChildrenSize() > 0) {
					TextEdit last = edit.getChildren()[edit.getChildrenSize() - 1];
					if (last instanceof DeleteEdit && lastStatic.getOffset() == last.getOffset() && lastStatic.getLength() == last.getLength()) {
						edit.removeChild(last);
					}
				}
			}
			TextEdit firstStatic = staticEdit.getChildren()[0];
			if (firstStatic instanceof InsertEdit) {
				if (edit.getChildrenSize() > 0) {
					TextEdit firstEdit = edit.getChildren()[0];
					if (firstEdit instanceof InsertEdit) {
						if (areEqual((InsertEdit) firstEdit, (InsertEdit) firstStatic)) {
							edit.removeChild(firstEdit);
						}
					}
				}
			}
			try {
				staticEdit.addChild(edit);
				return staticEdit;
			} catch (MalformedTreeException e) {
				JavaLanguageServerPlugin.logException("Failed to resolve static organize imports source action", e);
			}
		}
	}
	return edit;
}
 
Example 17
Source File: AddJavaDocStubOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void addJavadocComments(IProgressMonitor monitor) throws CoreException {
	ICompilationUnit cu= fMembers[0].getCompilationUnit();

	ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
	IPath path= cu.getPath();

	manager.connect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1));
	try {
		IDocument document= manager.getTextFileBuffer(path, LocationKind.IFILE).getDocument();

		String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
		MultiTextEdit edit= new MultiTextEdit();

		for (int i= 0; i < fMembers.length; i++) {
			IMember curr= fMembers[i];
			int memberStartOffset= getMemberStartOffset(curr, document);

			String comment= null;
			switch (curr.getElementType()) {
				case IJavaElement.TYPE:
					comment= createTypeComment((IType) curr, lineDelim);
					break;
				case IJavaElement.FIELD:
					comment= createFieldComment((IField) curr, lineDelim);
					break;
				case IJavaElement.METHOD:
					comment= createMethodComment((IMethod) curr, lineDelim);
					break;
			}
			if (comment == null) {
				StringBuffer buf= new StringBuffer();
				buf.append("/**").append(lineDelim); //$NON-NLS-1$
				buf.append(" *").append(lineDelim); //$NON-NLS-1$
				buf.append(" */").append(lineDelim); //$NON-NLS-1$
				comment= buf.toString();
			} else {
				if (!comment.endsWith(lineDelim)) {
					comment= comment + lineDelim;
				}
			}

			final IJavaProject project= cu.getJavaProject();
			IRegion region= document.getLineInformationOfOffset(memberStartOffset);

			String line= document.get(region.getOffset(), region.getLength());
			String indentString= Strings.getIndentString(line, project);

			String indentedComment= Strings.changeIndent(comment, 0, project, indentString, lineDelim);

			edit.addChild(new InsertEdit(memberStartOffset, indentedComment));

			monitor.worked(1);
		}
		edit.apply(document); // apply all edits
	} catch (BadLocationException e) {
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
	} finally {
		manager.disconnect(path, LocationKind.IFILE,new SubProgressMonitor(monitor, 1));
	}
}
 
Example 18
Source File: PostfixCompletionProposalComputer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected TemplateEngine computeCompletionEngine(JavaContentAssistInvocationContext context) {
	ICompilationUnit unit = context.getCompilationUnit();
	if (unit == null)
		return null;

	IJavaProject javaProject = unit.getJavaProject();
	if (javaProject == null)
		return null;

	CompletionContext coreContext = context.getCoreContext();
	if (coreContext != null) {
		int tokenLocation= coreContext.getTokenLocation();
		int tokenStart= coreContext.getTokenStart();
		int tokenKind= coreContext.getTokenKind();
		
		/*
		// XXX print out tokenlocation stuff (debugging)
		System.out.println("All Tokens: " + CompletionContext.TL_CONSTRUCTOR_START + " " + CompletionContext.TL_MEMBER_START + " " + CompletionContext.TL_STATEMENT_START);
		System.out.println("Token Start: " + coreContext.getTokenStart());
		System.out.println("Token End: " + coreContext.getTokenEnd());
		System.out.println("Token Kind: " + coreContext.getTokenKind());
		System.out.println("Token Location: " + coreContext.getTokenLocation());
		System.out.println("Enclosing Element: " + coreContext.getEnclosingElement());
		System.out.println("Offset: " + coreContext.getOffset());
		System.out.println("Token Array: " + Arrays.toString(coreContext.getToken()));
		System.out.println("Kind Tokens: " + CompletionContext.TOKEN_KIND_NAME + ", " + CompletionContext.TOKEN_KIND_STRING_LITERAL + ", " + CompletionContext.TOKEN_KIND_UNKNOWN);
		*/
		if (context.getViewer().getSelectedRange().y > 0) { // If there is an active selection we do not want to contribute to the CA
			return null;
		}
		
		if ((tokenLocation == 0 && tokenStart > -1)
				|| ((tokenLocation & CompletionContext.TL_MEMBER_START) != 0 && tokenKind == CompletionContext.TOKEN_KIND_NAME && tokenStart > -1)
				|| (tokenLocation == 0 && isAfterDot(context.getDocument(), context.getInvocationOffset()))) {
			
			analyzeCoreContext(context, coreContext);

			return postfixCompletionTemplateEngine;
		}
	}
	return null;
}
 
Example 19
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
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;
}
 
Example 20
Source File: CompletionProposalCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates a new instance ready to collect proposals. If the passed
 * <code>ICompilationUnit</code> is not contained in an
 * {@link IJavaProject}, no javadoc will be available as
 * {@link org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo() additional info}
 * on the created proposals.
 *
 * @param cu the compilation unit that the result collector will operate on
 * @param ignoreAll <code>true</code> to ignore all kinds of completion proposals
 * @since 3.4
 */
public CompletionProposalCollector(ICompilationUnit cu, boolean ignoreAll) {
	this(cu.getJavaProject(), cu, ignoreAll);
}