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: 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 #2
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 #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: 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 #5
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 #6
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 #7
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 #8
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 #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: AnonymousClassCreationToLambdaTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testConvertToLambda3() throws Exception {
	IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("interface I {\n");
	buf.append("    void count(int test);\n");
	buf.append("}\n");
	buf.append("public class E {\n");
	buf.append("    void foo() {\n");
	buf.append("        I i = new I() {\n");
	buf.append("            /*[*/public void count(int test) {\n");
	buf.append("                System.out.println(test);\n");
	buf.append("            }/*]*/\n");
	buf.append("        };\n");
	buf.append("        i.count(10);\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("interface I {\n");
	buf.append("    void count(int test);\n");
	buf.append("}\n");
	buf.append("public class E {\n");
	buf.append("    void foo() {\n");
	buf.append("        I i = test -> System.out.println(test);\n");
	buf.append("        i.count(10);\n");
	buf.append("    }\n");
	buf.append("}\n");
	Expected e = new Expected("Convert to lambda expression", buf.toString());

	assertCodeActions(cu, e);
}
 
Example #20
Source File: CompletionProposalReplacementProvider.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public CompletionProposalReplacementProvider(ICompilationUnit compilationUnit, CompletionContext context, int offset, Preferences preferences, ClientPreferences clientPrefs) {
	super();
	this.compilationUnit = compilationUnit;
	this.context = context;
	this.offset = offset;
	this.preferences = preferences == null ? new Preferences() : preferences;
	this.client = clientPrefs;
}
 
Example #21
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();
}
 
Example #22
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 #23
Source File: JavaElementAdapterFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IResource getResource(IJavaElement element) {
// can't use IJavaElement.getResource directly as we are interested in the
// corresponding resource
switch (element.getElementType()) {
	case IJavaElement.TYPE:
		// top level types behave like the CU
		IJavaElement parent= element.getParent();
		if (parent instanceof ICompilationUnit) {
			return ((ICompilationUnit) parent).getPrimary().getResource();
		}
		return null;
	case IJavaElement.COMPILATION_UNIT:
		return ((ICompilationUnit) element).getPrimary().getResource();
	case IJavaElement.CLASS_FILE:
	case IJavaElement.PACKAGE_FRAGMENT:
		// test if in a archive
		IPackageFragmentRoot root= (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
		if (!root.isArchive() && !root.isExternal()) {
			return element.getResource();
		}
		return null;
	case IJavaElement.PACKAGE_FRAGMENT_ROOT:
	case IJavaElement.JAVA_PROJECT:
	case IJavaElement.JAVA_MODEL:
		return element.getResource();
	default:
		return null;
}
  }
 
Example #24
Source File: GenerateConstructorsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGenerateConstructors_enum() throws ValidateEditException, CoreException, IOException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public enum B {\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "enum B");
	CheckConstructorsResponse response = GenerateConstructorsHandler.checkConstructorsStatus(params);
	assertNotNull(response.constructors);
	assertEquals(1, response.constructors.length);
	assertNotNull(response.fields);
	assertEquals(0, response.fields.length);

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

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

	compareSource(expected, unit.getSource());
}
 
Example #25
Source File: ResourceMacro.java    From ContentAssist with MIT License 5 votes vote down vote up
/**
 * Obtains source code after this resource change.
 * @param elem the changed resource
 * @return the contents of the source code, or an empty string if the changed resource is not a file
 */
private String getCode(IJavaElement elem) {
    if (elem instanceof ICompilationUnit) {
        ICompilationUnit cu = (ICompilationUnit)elem;
        
        try {
            return cu.getSource();
        } catch (JavaModelException e) {
        }
    }
    return "";
}
 
Example #26
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IType getSingleSelectedType(IStructuredSelection selection) throws JavaModelException {
	Object first= selection.getFirstElement();
	if (first instanceof IType)
		return (IType) first;
	if (first instanceof ICompilationUnit) {
		final ICompilationUnit unit= (ICompilationUnit) first;
		if (unit.exists())
			return  JavaElementUtil.getMainType(unit);
	}
	return null;
}
 
Example #27
Source File: JavaUI.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the {@link ITypeRoot} wrapped by the given editor input.
 *
 * @param editorInput the editor input
 * @return the {@link ITypeRoot} wrapped by <code>editorInput</code> or <code>null</code> if the editor input
 * does not stand for a ITypeRoot
 *
 * @since 3.4
 */
public static ITypeRoot getEditorInputTypeRoot(IEditorInput editorInput) {
	// Performance: check working copy manager first: this is faster
	ICompilationUnit cu= JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editorInput);
	if (cu != null)
		return cu;

	IJavaElement je= (IJavaElement) editorInput.getAdapter(IJavaElement.class);
	if (je instanceof ITypeRoot)
		return (ITypeRoot) je;

	return null;
}
 
Example #28
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IType[] getDestinationPackageTypes() throws JavaModelException {
	List<IType> types= new ArrayList<IType>();
	if (fDestination.exists()) {
		ICompilationUnit[] cus= fDestination.getCompilationUnits();
		for (int i= 0; i < cus.length; i++) {
			types.addAll(Arrays.asList(cus[i].getAllTypes()));
		}
	}
	return types.toArray(new IType[types.size()]);
}
 
Example #29
Source File: FindBrokenNLSKeysAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean importsOSGIUtil(ICompilationUnit unit) throws JavaModelException {
	IImportDeclaration[] imports= unit.getImports();
	for (int i= 0; i < imports.length; i++) {
		if (imports[i].getElementName().startsWith("org.eclipse.osgi.util.")) //$NON-NLS-1$
			return true;
	}

	return false;
}
 
Example #30
Source File: CompilationUnitDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ICompilationUnit getWorkingCopy(Object element) {
	FileInfo fileInfo= getFileInfo(element);
	if (fileInfo instanceof CompilationUnitInfo) {
		CompilationUnitInfo info= (CompilationUnitInfo)fileInfo;
		return info.fCopy;
	}
	CompilationUnitInfo cuInfo= fFakeCUMapForMissingInfo.get(element);
	if (cuInfo != null)
		return cuInfo.fCopy;

	return null;
}