org.eclipse.jdt.core.ICompilationUnit Java Examples

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit. 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: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSnippet_context_method3() throws JavaModelException {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Test.java",
	//@formatter:off
			"package org.sample;\n"
		+	"public class Test {\n\n"
		+	"	void test() {\n\n"
		+	"		int \n"
		+	"	}\n"
		+	"}\n");
		//@formatter:off
	int[] loc = findCompletionLocation(unit, "int ");
	CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();
	assertNotNull(list);
	CompletionItem ci = list.getItems().stream()
			.filter( item->  (item.getLabel().matches("class") && item.getKind() == CompletionItemKind.Snippet))
			.findFirst().orElse(null);
	assertNull(ci);
	ci = list.getItems().stream()
			.filter( item->  (item.getLabel().matches("interface") && item.getKind() == CompletionItemKind.Snippet))
			.findFirst().orElse(null);
	assertNull(ci);
}
 
Example #2
Source File: CorrectPackageDeclarationProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
	super.addEdits(doc, root);

	ICompilationUnit cu= getCompilationUnit();

	IPackageFragment parentPack= (IPackageFragment) cu.getParent();
	IPackageDeclaration[] decls= cu.getPackageDeclarations();

	if (parentPack.isDefaultPackage() && decls.length > 0) {
		for (int i= 0; i < decls.length; i++) {
			ISourceRange range= decls[i].getSourceRange();
			root.addChild(new DeleteEdit(range.getOffset(), range.getLength()));
		}
		return;
	}
	if (!parentPack.isDefaultPackage() && decls.length == 0) {
		String lineDelim = "\n";
		String str= "package " + parentPack.getElementName() + ';' + lineDelim + lineDelim; //$NON-NLS-1$
		root.addChild(new InsertEdit(0, str));
		return;
	}

	root.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), parentPack.getElementName()));
}
 
Example #3
Source File: DocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ICompilationUnit handleOpen(DidOpenTextDocumentParams params) {
	ICompilationUnit unit = super.handleOpen(params);

	if (unit == null || unit.getResource() == null || unit.getResource().isDerived()) {
		return unit;
	}

	try {
		installSemanticHighlightings(unit);
	} catch (JavaModelException | BadPositionCategoryException e) {
		JavaLanguageServerPlugin.logException("Error while opening document. URI: " + params.getTextDocument().getUri(), e);
	}

	return unit;
}
 
Example #4
Source File: CollectingSearchRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean isBinaryElement(Object element) throws JavaModelException {
	if (element instanceof IMember) {
		return ((IMember)element).isBinary();

	} else if (element instanceof ICompilationUnit) {
		return true;

	} else if (element instanceof IClassFile) {
		return false;

	} else if (element instanceof IPackageFragment) {
		return isBinaryElement(((IPackageFragment) element).getParent());

	} else if (element instanceof IPackageFragmentRoot) {
		return ((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_BINARY;

	}
	return false;

}
 
Example #5
Source File: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean selectStatusEntry(final RefactoringStatusEntry entry) {
	if (fSourceFolder != null) {
		final IPath source= fSourceFolder.getFullPath();
		final RefactoringStatusContext context= entry.getContext();
		if (context instanceof JavaStatusContext) {
			final JavaStatusContext extended= (JavaStatusContext) context;
			final ICompilationUnit unit= extended.getCompilationUnit();
			if (unit != null) {
				final IResource resource= unit.getResource();
				if (resource != null && source.isPrefixOf(resource.getFullPath()))
					return false;
			}
		}
	}
	return super.selectStatusEntry(entry);
}
 
Example #6
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testJavaFormatEnable() throws Exception {
	String text =
	//@formatter:off
			"package org.sample   ;\n\n" +
			"      public class Baz {  String name;}\n";
		//@formatter:on"
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", text);
	preferenceManager.getPreferences().setJavaFormatEnabled(false);
	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces
	DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
	List<? extends TextEdit> edits = server.formatting(params).get();
	assertNotNull(edits);
	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(text, newText);
}
 
Example #7
Source File: DeleteChangeCreator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static TextChange addTextEditFromRewrite(TextChangeManager manager, ICompilationUnit cu, ASTRewrite rewrite) throws CoreException {
	try {
		ITextFileBuffer buffer= RefactoringFileBuffers.acquire(cu);
		TextEdit resultingEdits= rewrite.rewriteAST(buffer.getDocument(), cu.getJavaProject().getOptions(true));
		TextChange textChange= manager.get(cu);
		if (textChange instanceof TextFileChange) {
			TextFileChange tfc= (TextFileChange) textChange;
			tfc.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
		}
		String message= RefactoringCoreMessages.DeleteChangeCreator_1;
		TextChangeCompatibility.addTextEdit(textChange, message, resultingEdits);
		return textChange;
	} finally {
		RefactoringFileBuffers.release(cu);
	}
}
 
Example #8
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ICompilationUnit findCompilationUnitForBinding(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding) throws JavaModelException {
	if (binding == null || !binding.isFromSource() || binding.isTypeVariable() || binding.isWildcardType()) {
		return null;
	}
	ASTNode node= astRoot.findDeclaringNode(binding.getTypeDeclaration());
	if (node == null) {
		ICompilationUnit targetCU= Bindings.findCompilationUnit(binding, cu.getJavaProject());
		if (targetCU != null) {
			return targetCU;
		}
		return null;
	} else if (node instanceof AbstractTypeDeclaration || node instanceof AnonymousClassDeclaration) {
		return cu;
	}
	return null;
}
 
Example #9
Source File: RenameNonVirtualMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm) {
	SearchResultGroup[] grouped= getOccurrences();
	for (int i= 0; i < grouped.length; i++) {
		SearchResultGroup group= grouped[i];
		SearchMatch[] results= group.getSearchResults();
		ICompilationUnit cu= group.getCompilationUnit();
		TextChange change= manager.get(cu);
		for (int j= 0; j < results.length; j++){
			SearchMatch match= results[j];
			if (!(match instanceof MethodDeclarationMatch)) {
				ReplaceEdit replaceEdit= createReplaceEdit(match, cu);
				String editName= RefactoringCoreMessages.RenamePrivateMethodRefactoring_update;
				addTextEdit(change, editName, replaceEdit);
			}
		}
	}
	pm.done();
}
 
Example #10
Source File: ReorgQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testWrongDefaultPackageStatement() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test2", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("public class E {\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu);

	Either<Command, CodeAction> codeAction = findAction(codeActions, "Add package declaration 'test2;'");
	assertNotNull(codeAction);
	buf = new StringBuilder();
	buf.append("package test2;\n");
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("}\n");
	assertEquals(buf.toString(), evaluateCodeActionCommand(codeAction));

	codeAction = findAction(codeActions, "Move 'E.java' to the default package");
	assertNotNull(codeAction);
	assertRenameFileOperation(codeAction, ResourceUtils.fixURI(pack1.getResource().getRawLocation().append("../E.java").toFile().toURI()));
}
 
Example #11
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void getAmbiguousTypeReferenceProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) throws CoreException {
	final ICompilationUnit cu= context.getCompilationUnit();
	int offset= problem.getOffset();
	int len= problem.getLength();

	IJavaElement[] elements= cu.codeSelect(offset, len);
	for (int i= 0; i < elements.length; i++) {
		IJavaElement curr= elements[i];
		if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) {
			String qualifiedTypeName= ((IType) curr).getFullyQualifiedName('.');

			CompilationUnit root= context.getASTRoot();

			String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importexplicit_description, BasicElementLabels.getJavaElementName(qualifiedTypeName));
			ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, ASTRewrite.create(root.getAST()), IProposalRelevance.IMPORT_EXPLICIT);

			ImportRewrite imports= proposal.createImportRewrite(root);
			imports.addImport(qualifiedTypeName);

			proposals.add(proposal);
		}
	}
}
 
Example #12
Source File: CreateTypeMemberOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String removeIndentAndNewLines(String code, ICompilationUnit cu) throws JavaModelException {
	IJavaProject project = cu.getJavaProject();
	Map options = project.getOptions(true/*inherit JavaCore options*/);
	int tabWidth = IndentManipulation.getTabWidth(options);
	int indentWidth = IndentManipulation.getIndentWidth(options);
	int indent = IndentManipulation.measureIndentUnits(code, tabWidth, indentWidth);
	int firstNonWhiteSpace = -1;
	int length = code.length();
	while (firstNonWhiteSpace < length-1)
		if (!ScannerHelper.isWhitespace(code.charAt(++firstNonWhiteSpace)))
			break;
	int lastNonWhiteSpace = length;
	while (lastNonWhiteSpace > 0)
		if (!ScannerHelper.isWhitespace(code.charAt(--lastNonWhiteSpace)))
			break;
	String lineDelimiter = cu.findRecommendedLineSeparator();
	return IndentManipulation.changeIndent(code.substring(firstNonWhiteSpace, lastNonWhiteSpace+1), indent, tabWidth, indentWidth, "", lineDelimiter); //$NON-NLS-1$
}
 
Example #13
Source File: MoveCuUpdateCreator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private boolean simpleReferencesNeedNewImport(ICompilationUnit movedUnit, ICompilationUnit referencingCu, List<ICompilationUnit> cuList) {
	if (referencingCu.equals(movedUnit)) {
		return false;
	}
	if (cuList.contains(referencingCu)) {
		return false;
	}
	if (isReferenceInAnotherFragmentOfSamePackage(referencingCu, movedUnit)) {
		/* Destination package is different from source, since
		 * isDestinationAnotherFragmentOfSamePackage(movedUnit) was false in addUpdates(.) */
		return true;
	}

	//heuristic
	if (referencingCu.getImport(movedUnit.getParent().getElementName() + ".*").exists()) {
		return true; // has old star import
	}
	if (referencingCu.getParent().equals(movedUnit.getParent())) {
		return true; //is moved away from same package
	}
	return false;
}
 
Example #14
Source File: ModelBasedCompletionEngine.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void codeComplete(ICompilationUnit cu, int position, CompletionRequestor requestor, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
	if (!(cu instanceof CompilationUnit)) {
		return;
	}

	if (requestor == null) {
		throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
	}

	IBuffer buffer = cu.getBuffer();
	if (buffer == null) {
		return;
	}

	if (position < -1 || position > buffer.getLength()) {
		throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
	}

	JavaProject project = (JavaProject) cu.getJavaProject();
	ModelBasedSearchableEnvironment environment = new ModelBasedSearchableEnvironment(project, owner, requestor.isTestCodeExcluded());
	environment.setUnitToSkip((CompilationUnit) cu);

	// code complete
	CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project, owner, monitor);
	engine.complete((CompilationUnit) cu, position, 0, cu);
}
 
Example #15
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static RefactorWorkspaceEdit moveTypeToClass(CodeActionParams params, String destinationTypeName, IProgressMonitor monitor) {
	final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
	if (unit == null) {
		return new RefactorWorkspaceEdit("Failed to move type to another class because cannot find the compilation unit associated with " + params.getTextDocument().getUri());
	}

	IType type = getSelectedType(unit, params);
	if (type == null) {
		return new RefactorWorkspaceEdit("Failed to move type to another class because no type is selected.");
	}

	try {
		if (RefactoringAvailabilityTesterCore.isMoveStaticAvailable(type)) {
			return moveStaticMember(new IMember[] { type }, destinationTypeName, monitor);
		}

		return new RefactorWorkspaceEdit("Moving non-static type to another class is not supported.");
	} catch (JavaModelException e) {
		return new RefactorWorkspaceEdit("Failed to move type to another class. Reason: " + e.toString());
	}
}
 
Example #16
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public IJavaElement[] getActualJavaElementsToReorg() throws JavaModelException {
	List<IJavaElement> result= new ArrayList<>();
	for (int i= 0; i < fJavaElements.length; i++) {
		IJavaElement element= fJavaElements[i];
		if (element == null) {
			continue;
		}
		if (element instanceof IType) {
			IType type= (IType) element;
			ICompilationUnit cu= type.getCompilationUnit();
			if (cu != null && type.getDeclaringType() == null && cu.exists() && cu.getTypes().length == 1 && !result.contains(cu)) {
				result.add(cu);
			} else if (!result.contains(type)) {
				result.add(type);
			}
		} else if (!result.contains(element)) {
			result.add(element);
		}
	}
	return result.toArray(new IJavaElement[result.size()]);
}
 
Example #17
Source File: SearchUtils.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param match the search match
 * @return the enclosing {@link ICompilationUnit} of the given match, or null iff none
 */
public static ICompilationUnit getCompilationUnit(SearchMatch match) {
	IJavaElement enclosingElement = getEnclosingJavaElement(match);
	if (enclosingElement != null){
		if (enclosingElement instanceof ICompilationUnit)
			return (ICompilationUnit) enclosingElement;
		ICompilationUnit cu= (ICompilationUnit) enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT);
		if (cu != null)
			return cu;
	}

	IJavaElement jElement= JavaCore.create(match.getResource());
	if (jElement != null && jElement.exists() && jElement.getElementType() == IJavaElement.COMPILATION_UNIT)
		return (ICompilationUnit) jElement;
	return null;
}
 
Example #18
Source File: HTMLTagCompletionProposalComputer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
	if (!(context instanceof JavadocContentAssistInvocationContext))
		return Collections.emptyList();

	JavadocContentAssistInvocationContext docContext= (JavadocContentAssistInvocationContext) context;
	int flags= docContext.getFlags();
	fCurrentPos= docContext.getInvocationOffset();
	fCurrentLength= docContext.getSelectionLength();
	fRestrictToMatchingCase= (flags & IJavadocCompletionProcessor.RESTRICT_TO_MATCHING_CASE) != 0;

	ICompilationUnit cu= docContext.getCompilationUnit();
	if (cu == null)
		return Collections.emptyList();
	fDocument= docContext.getDocument();
	if (fDocument == null) {
		return Collections.emptyList();
	}

	try {
		fResult= new ArrayList<ICompletionProposal>(100);
		evalProposals();
		return fResult;
	} finally {
		fResult= null;
	}
}
 
Example #19
Source File: StaticReferenceQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testStaticMethodRequested() throws Exception {
	// Problem we are testing
	int problem = IProblem.StaticMethodRequested;

	IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class A {\n");
	buf.append("	public static void main(String[] args) {\n");
	buf.append("		b();\n"); // referencing in static context
	buf.append("	}\n");
	buf.append("	");
	buf.append("	public void b() {\n"); // non static
	buf.append("	}\n");
	buf.append("}\n");
	ICompilationUnit cu = pack.createCompilationUnit("A.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class A {\n");
	buf.append("	public static void main(String[] args) {\n");
	buf.append("		b();\n");
	buf.append("	}\n");
	buf.append("	");
	buf.append("	public static void b() {\n");
	buf.append("	}\n");
	buf.append("}\n");

	Expected e1 = new Expected("Change 'b()' to 'static'", buf.toString());

	Range selection = CodeActionUtil.getRange(cu, "FOOBAR");
	assertCodeActions(cu, selection, e1);
}
 
Example #20
Source File: JavaScriptVisualizeSelectedDiagramsHandler.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	JavaScriptVisualizeWizard wizard = new JavaScriptVisualizeWizard();
	WizardDialog wizardDialog = new WizardDialog(null, wizard);
	wizardDialog.create();

	VisualizeTxtUMLPage page = ((VisualizeTxtUMLPage) wizardDialog.getSelectedPage());

	// get selected files
	ISelection selection = HandlerUtil.getCurrentSelection(event);
	IStructuredSelection strSelection = (IStructuredSelection) selection;

	List<ICompilationUnit> selectedCompilationUnits = new ArrayList<>();
	Stream.of(strSelection.toArray()).forEach(s -> selectedCompilationUnits
			.add((ICompilationUnit) ((IAdaptable) s).getAdapter(ICompilationUnit.class)));
	try {
		List<IType> types = new ArrayList<>();
		for (ICompilationUnit cu : selectedCompilationUnits) {
			types.addAll(Arrays.asList(cu.getTypes()));
		}
		page.selectElementsInDiagramTree(types.toArray(), false);
		page.setExpandedLayouts(types);
	} catch (JavaModelException ex) {
	}

	wizardDialog.open();
	return null;
}
 
Example #21
Source File: ConvertNestedToTopAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IType getSingleSelectedType(IStructuredSelection selection) throws JavaModelException {
	if (selection.isEmpty() || selection.size() != 1)
		return null;

	Object first= selection.getFirstElement();
	if (first instanceof IType)
		return (IType)first;
	if (first instanceof ICompilationUnit)
		return JavaElementUtil.getMainType((ICompilationUnit)first);
	return null;
}
 
Example #22
Source File: OrganizeImportsActionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testOrganizeImportsModuleInfo() throws Exception {

	setupJava9();

	IPackageFragment pack1 = fSourceFolder.createPackageFragment("", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("import foo.bar.MyDriverAction;\n");
	buf.append("import java.sql.DriverAction;\n");
	buf.append("import java.sql.SQLException;\n");
	buf.append("\n");
	buf.append("module mymodule.nine {\n");
	buf.append("	requires java.sql;\n");
	buf.append("	exports foo.bar;\n");
	buf.append("	provides DriverAction with MyDriverAction;\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("module-info.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("import java.sql.DriverAction;\n");
	buf.append("\n");
	buf.append("import foo.bar.MyDriverAction;\n");
	buf.append("\n");
	buf.append("module mymodule.nine {\n");
	buf.append("	requires java.sql;\n");
	buf.append("	exports foo.bar;\n");
	buf.append("	provides DriverAction with MyDriverAction;\n");
	buf.append("}\n");

	Expected e1 = new Expected("Organize imports", buf.toString());

	assertCodeActions(cu, e1);
}
 
Example #23
Source File: ExtractMethodTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExtractMethodGeneric() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("\n");
	buf.append("import java.util.ArrayList;\n");
	buf.append("import java.util.List;\n");
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("    public <E> void foo(E param) {\n");
	buf.append("        /*[*/List<E> list = new ArrayList<E>();\n");
	buf.append("        foo(param);/*]*/\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("\n");
	buf.append("import java.util.ArrayList;\n");
	buf.append("import java.util.List;\n");
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("    public <E> void foo(E param) {\n");
	buf.append("        extracted(param);\n");
	buf.append("    }\n");
	buf.append("\n");
	buf.append("    private <E> void extracted(E param) {\n");
	buf.append("        /*[*/List<E> list = new ArrayList<E>();\n");
	buf.append("        foo(param);/*]*/\n");
	buf.append("    }\n");
	buf.append("}\n");

	Expected e1 = new Expected("Extract to method", buf.toString(), JavaCodeActionKind.REFACTOR_EXTRACT_METHOD);
	assertCodeActions(cu, e1);
}
 
Example #24
Source File: PostfixTemplateEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void complete(ITextViewer viewer, int completionPosition, ICompilationUnit compilationUnit) {
	IDocument document = viewer.getDocument();

	if (!(getContextType() instanceof JavaStatementPostfixContextType))
		return;

	Point selection = viewer.getSelectedRange();

	String selectedText = null;
	if (selection.y != 0) {
		return;
	}

	JavaStatementPostfixContext context = ((JavaStatementPostfixContextType) getContextType()).createContext(document, completionPosition, selection.y, compilationUnit, currentNode, parentNode);
	context.setVariable("selection", selectedText); //$NON-NLS-1$
	int start = context.getStart();
	int end = context.getEnd();
	IRegion region = new Region(start, end - start);

	Template[] templates = JavaPlugin.getDefault().getTemplateStore().getTemplates(getContextType().getId());

	for (int i = 0; i != templates.length; i++) {
		Template template = templates[i];
		if (context.canEvaluate(template)) {
			getProposals().add(new PostfixTemplateProposal(template, context, region, getImage()));
		}
	}
}
 
Example #25
Source File: JavadocQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInvalidQualification2() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package pack;\n");
	buf.append("\n");
	buf.append("public class A {\n");
	buf.append("    public static class B {\n");
	buf.append("    }\n");
	buf.append("}\n");
	pack1.createCompilationUnit("A.java", buf.toString(), false, null);

	IPackageFragment pack2 = fSourceFolder.createPackageFragment("pack2", false, null);
	buf = new StringBuilder();
	buf.append("package pack2;\n");
	buf.append("\n");
	buf.append("import pack.A;\n");
	buf.append("\n");
	buf.append("/**\n");
	buf.append(" * {@link A.B} \n");
	buf.append(" */\n");
	buf.append("public class E {\n");
	buf.append("}\n");
	ICompilationUnit cu = pack2.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package pack2;\n");
	buf.append("\n");
	buf.append("import pack.A;\n");
	buf.append("\n");
	buf.append("/**\n");
	buf.append(" * {@link pack.A.B} \n");
	buf.append(" */\n");
	buf.append("public class E {\n");
	buf.append("}\n");
	Expected e1 = new Expected("Qualify inner type name", buf.toString());
	assertCodeActions(cu, e1);
}
 
Example #26
Source File: JavaModelUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Force a reconcile of a compilation unit.
 * @param unit the compilation unit
 * @throws JavaModelException thrown when the compilation unit can not be accessed
 */
public static void reconcile(ICompilationUnit unit) throws JavaModelException {
	unit.reconcile(
			ICompilationUnit.NO_AST,
			false /* don't force problem detection */,
			null /* use primary owner */,
			null /* no progress monitor */);
}
 
Example #27
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addStaticImport(ICompilationUnit movedUnit, IImportDeclaration importDecl, ImportRewrite rewrite) {
	String old= importDecl.getElementName();
	int oldPackLength= movedUnit.getParent().getElementName().length();

	StringBuffer result= new StringBuffer(fDestination.getElementName());
	if (oldPackLength == 0) // move FROM default package
		result.append('.').append(old);
	else if (result.length() == 0) // move TO default package
		result.append(old.substring(oldPackLength + 1)); // cut "."
	else
		result.append(old.substring(oldPackLength));
	int index= result.lastIndexOf("."); //$NON-NLS-1$
	if (index > 0 && index < result.length() - 1)
		rewrite.addStaticImport(result.substring(0, index), result.substring(index + 1, result.length()), true);
}
 
Example #28
Source File: DOMImport.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see IDOMNode#getJavaElement
 */
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
	if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
		return ((ICompilationUnit)parent).getImport(getName());
	} else {
		throw new IllegalArgumentException(Messages.element_illegalParent);
	}
}
 
Example #29
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private FieldDeclaration createNewFieldDeclarationNode(MemberActionInfo info, CompilationUnit declaringCuNode, TypeVariableMaplet[] mapping, ASTRewrite rewrite, VariableDeclarationFragment oldFieldFragment) throws JavaModelException {
	Assert.isTrue(info.isFieldInfo());
	IField field= (IField) info.getMember();
	AST ast= rewrite.getAST();
	VariableDeclarationFragment newFragment= ast.newVariableDeclarationFragment();
	copyExtraDimensions(oldFieldFragment, newFragment);
	Expression initializer= oldFieldFragment.getInitializer();
	if (initializer != null) {
		Expression newInitializer= null;
		if (mapping.length > 0)
			newInitializer= createPlaceholderForExpression(initializer, field.getCompilationUnit(), mapping, rewrite);
		else
			newInitializer= createPlaceholderForExpression(initializer, field.getCompilationUnit(), rewrite);
		newFragment.setInitializer(newInitializer);
	}
	newFragment.setName(ast.newSimpleName(oldFieldFragment.getName().getIdentifier()));
	FieldDeclaration newField= ast.newFieldDeclaration(newFragment);
	FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, declaringCuNode);
	if (info.copyJavadocToCopiesInSubclasses())
		copyJavadocNode(rewrite, oldField, newField);
	copyAnnotations(oldField, newField);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(ast, info.getNewModifiersForCopyInSubclass(oldField.getModifiers())));
	Type oldType= oldField.getType();
	ICompilationUnit cu= field.getCompilationUnit();
	Type newType= null;
	if (mapping.length > 0) {
		newType= createPlaceholderForType(oldType, cu, mapping, rewrite);
	} else
		newType= createPlaceholderForType(oldType, cu, rewrite);
	newField.setType(newType);
	return newField;
}
 
Example #30
Source File: ConversionProblemsDialog.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void okPressed() {
	for (ICompilationUnit iCompilationUnit : excluded) {
		input.remove(iCompilationUnit);
	}
	super.okPressed();
}