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

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#getImports() . 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: CreateImportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets the correct position for the new import:<ul>
 * <li> after the last import
 * <li> if no imports, before the first type
 * <li> if no type, after the package statement
 * <li> and if no package statement - first thing in the CU
 */
protected void initializeDefaultPosition() {
	try {
		ICompilationUnit cu = getCompilationUnit();
		IImportDeclaration[] imports = cu.getImports();
		if (imports.length > 0) {
			createAfter(imports[imports.length - 1]);
			return;
		}
		IType[] types = cu.getTypes();
		if (types.length > 0) {
			createBefore(types[0]);
			return;
		}
		IJavaElement[] children = cu.getChildren();
		//look for the package declaration
		for (int i = 0; i < children.length; i++) {
			if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION) {
				createAfter(children[i]);
				return;
			}
		}
	} catch (JavaModelException e) {
		// cu doesn't exit: ignore
	}
}
 
Example 2
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test1() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test1.java");
	IType testClass = cu.createType("public class Test1 extends A implements B {\n}\n", null, true, null);

	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	checkUnimplementedMethods(new String[] { "a()", "b(Vector<Date>)", "c(Hashtable)" }, overridableMethods);

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "a", "b", "c", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[] { "java.util.Date", "java.util.Hashtable", "java.util.Vector" }, imports);
}
 
Example 3
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test2() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test2.java");
	IType testClass = cu.createType("public class Test2 extends C implements B {\n}\n", null, true, null);

	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	checkUnimplementedMethods(new String[] { "d(Hashtable)" }, overridableMethods);
	checkOverridableMethods(new String[] { "c(Hashtable)" }, overridableMethods);

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "c", "d", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[] { "java.util.Enumeration", "java.util.Hashtable" }, imports);
}
 
Example 4
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test3() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test3.java");
	IType testClass = cu.createType("public class Test3 extends D {\n}\n", null, true, null);

	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	checkUnimplementedMethods(new String[] { "c(Hashtable)", "d(Hashtable)" }, overridableMethods);

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "c", "d", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[] { "java.util.Hashtable", "java.util.Enumeration" }, imports);
}
 
Example 5
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test4() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test4.java");
	IType testClass = cu.createType("public class Test4 implements B, E {\n}\n", null, true, null);

	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	checkUnimplementedMethods(new String[] { "c(Hashtable)", "e()" }, overridableMethods);

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "c", "e", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[] { "java.util.Hashtable", "java.util.NoSuchElementException" }, imports);
}
 
Example 6
Source File: CreatePackageDeclarationOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets the correct position for new package declaration:<ul>
 * <li> before the first import
 * <li> if no imports, before the first type
 * <li> if no type - first thing in the CU
 * <li>
 */
protected void initializeDefaultPosition() {
	try {
		ICompilationUnit cu = getCompilationUnit();
		IImportDeclaration[] imports = cu.getImports();
		if (imports.length > 0) {
			createBefore(imports[0]);
			return;
		}
		IType[] types = cu.getTypes();
		if (types.length > 0) {
			createBefore(types[0]);
			return;
		}
	} catch (JavaModelException e) {
		// cu doesn't exist: ignore
	}
}
 
Example 7
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void assertImports(ICompilationUnit cu, String[] imports) throws Exception {
	IImportDeclaration[] desc= cu.getImports();
	assertEquals(cu.getElementName() + "-count", imports.length, desc.length);
	for (int i= 0; i < imports.length; i++) {
		assertEquals(cu.getElementName() + "-cmpentries" + i, desc[i].getElementName(), imports[i]);
	}
}
 
Example 8
Source File: Jdt2Ecore.java    From sarl with Apache License 2.0 5 votes vote down vote up
private String resolve(IMethod operation, String typename) throws JavaModelException {
	if (Signature.C_UNRESOLVED == Signature.getElementType(typename).charAt(0)) {
		final ICompilationUnit unit = operation.getCompilationUnit();
		if (unit != null) {
			final String post = "." + Signature.toString(typename); //$NON-NLS-1$
			for (final IImportDeclaration decl : unit.getImports()) {
				if (decl.getElementName().endsWith(post)) {
					return decl.getElementName();
				}
			}
		}
	}
	return Signature.toString(typename);
}
 
Example 9
Source File: DeleteElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Deletes this element from its compilation unit.
 * @see MultiOperation
 */
protected void processElement(IJavaElement element) throws JavaModelException {
	ICompilationUnit cu = (ICompilationUnit) element;

	// keep track of the import statements - if all are removed, delete
	// the import container (and report it in the delta)
	int numberOfImports = cu.getImports().length;

	JavaElementDelta delta = new JavaElementDelta(cu);
	IJavaElement[] cuElements = ((IRegion) this.childrenToRemove.get(cu)).getElements();
	for (int i = 0, length = cuElements.length; i < length; i++) {
		IJavaElement e = cuElements[i];
		if (e.exists()) {
			deleteElement(e, cu);
			delta.removed(e);
			if (e.getElementType() == IJavaElement.IMPORT_DECLARATION) {
				numberOfImports--;
				if (numberOfImports == 0) {
					delta.removed(cu.getImportContainer());
				}
			}
		}
	}
	if (delta.getAffectedChildren().length > 0) {
		cu.save(getSubProgressMonitor(1), this.force);
		if (!cu.isWorkingCopy()) { // if unit is working copy, then save will have already fired the delta
			addDelta(delta);
			setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
		}
	}
}
 
Example 10
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 11
Source File: NLSAccessorFieldRenameParticipant.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 12
Source File: RenameTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IImportDeclaration getImportedType(ICompilationUnit cu, String typeName) throws CoreException {
	IImportDeclaration[] imports= cu.getImports();
	String dotTypeName= "." + typeName; //$NON-NLS-1$
	for (int i= 0; i < imports.length; i++){
		if (imports[i].getElementName().endsWith(dotTypeName))
			return imports[i];
	}
	return null;
}
 
Example 13
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBug297183() throws Exception {
	StringBuilder buf = new StringBuilder();
	buf.append("package p;\n");
	buf.append("interface Shape {\r\n");
	buf.append("  int getX();\r\n");
	buf.append("  int getY();\r\n");
	buf.append("  int getEdges();\r\n");
	buf.append("  int getArea();\r\n");
	buf.append("}\r\n");
	fPackageP.createCompilationUnit("Shape.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package p;\n");
	buf.append("interface Circle extends Shape {\r\n");
	buf.append("  int getR();\r\n");
	buf.append("}\r\n");
	buf.append("\r\n");
	fPackageP.createCompilationUnit("Circle.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package P;\n");
	buf.append("public class DefaultCircle implements Circle {\n");
	buf.append("}\n");
	ICompilationUnit cu = fPackageP.getCompilationUnit("DefaultCircle.java");
	IType testClass = cu.createType(buf.toString(), null, true, null);

	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	checkUnimplementedMethods(new String[] { "getX()", "getY()", "getEdges()", "getArea()", "getR()" }, overridableMethods);
	List<OverridableMethod> unimplementedMethods = overridableMethods.stream().filter((method) -> method.unimplemented).collect(Collectors.toList());
	addAndApplyOverridableMethods(testClass, unimplementedMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "getX", "getY", "getEdges", "getArea", "getR" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[0], imports);
}
 
Example 14
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBug119171() throws Exception {
	StringBuilder buf = new StringBuilder();
	buf.append("package p;\n");
	buf.append("import java.util.Properties;\n");
	buf.append("public interface F {\n");
	buf.append("    public void b(Properties p);\n");
	buf.append("}\n");
	fPackageP.createCompilationUnit("F.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package p;\n");
	buf.append("public class Properties {\n");
	buf.append("    public int get() {return 0;}\n");
	buf.append("}\n");
	fPackageP.createCompilationUnit("Properties.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("public class Test5 implements F {\n");
	buf.append("    public void foo() {\n");
	buf.append("        Properties p= new Properties();\n");
	buf.append("        p.get();\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test5.java");
	IType testClass = cu.createType(buf.toString(), null, true, null);
	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "foo", "b", "clone", "equals", "finalize", "hashCode", "toString" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[0], imports);
}
 
Example 15
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IImportDeclaration getImportedType(ICompilationUnit cu, String typeName) throws CoreException {
	IImportDeclaration[] imports = cu.getImports();
	String dotTypeName = "." + typeName; //$NON-NLS-1$
	for (int i = 0; i < imports.length; i++) {
		if (imports[i].getElementName().endsWith(dotTypeName)) {
			return imports[i];
		}
	}
	return null;
}
 
Example 16
Source File: RenameTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus checkConflictingTypes(IProgressMonitor pm) throws CoreException {
	RefactoringStatus result= new RefactoringStatus();
	IJavaSearchScope scope= RefactoringScopeFactory.create(fType);
	SearchPattern pattern= SearchPattern.createPattern(getNewElementName(),
			IJavaSearchConstants.TYPE, IJavaSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	ICompilationUnit[] cusWithReferencesToConflictingTypes= RefactoringSearchEngine.findAffectedCompilationUnits(pattern, scope, pm, result);
	if (cusWithReferencesToConflictingTypes.length == 0)
		return result;
	ICompilationUnit[] 	cusWithReferencesToRenamedType= getCus(fReferences);

	Set<ICompilationUnit> conflicts= getIntersection(cusWithReferencesToRenamedType, cusWithReferencesToConflictingTypes);
	if (cusWithReferencesToConflictingTypes.length > 0) {
		cus: for (ICompilationUnit cu : cusWithReferencesToConflictingTypes) {
			String packageName= fType.getPackageFragment().getElementName();
			if (((IPackageFragment) cu.getParent()).getElementName().equals(packageName)) {
				boolean hasOnDemandImport= false;
				IImportDeclaration[] imports= cu.getImports();
				for (IImportDeclaration importDecl : imports) {
					if (importDecl.isOnDemand()) {
						hasOnDemandImport= true;
					} else {
						String importName= importDecl.getElementName();
						int packageLength= importName.length() - getNewElementName().length() - 1;
						if (packageLength > 0
								&& importName.endsWith(getNewElementName())
								&& importName.charAt(packageLength) == '.') {
							continue cus; // explicit import from another package => no problem
						}
					}
				}
				if (hasOnDemandImport) {
					// the renamed type in the same package will shadow the *-imported type
					conflicts.add(cu);
				}
			}
		}
	}
	
	for (ICompilationUnit conflict : conflicts) {
		RefactoringStatusContext context= JavaStatusContext.create(conflict);
		String message= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_another_type,
			new String[] { getNewElementLabel(), BasicElementLabels.getFileName(conflict)});
		result.addError(message, context);
	}
	return result;
}
 
Example 17
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private RefactoringStatus checkConflictingTypes(IProgressMonitor pm) throws CoreException {
	RefactoringStatus result = new RefactoringStatus();
	IJavaSearchScope scope = RefactoringScopeFactory.create(fType);
	SearchPattern pattern = SearchPattern.createPattern(getNewElementName(), IJavaSearchConstants.TYPE, IJavaSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	ICompilationUnit[] cusWithReferencesToConflictingTypes = RefactoringSearchEngine.findAffectedCompilationUnits(pattern, scope, pm, result);
	if (cusWithReferencesToConflictingTypes.length == 0) {
		return result;
	}
	ICompilationUnit[] cusWithReferencesToRenamedType = getCus(fReferences);

	Set<ICompilationUnit> conflicts = getIntersection(cusWithReferencesToRenamedType, cusWithReferencesToConflictingTypes);
	if (cusWithReferencesToConflictingTypes.length > 0) {
		cus: for (ICompilationUnit cu : cusWithReferencesToConflictingTypes) {
			String packageName = fType.getPackageFragment().getElementName();
			if (((IPackageFragment) cu.getParent()).getElementName().equals(packageName)) {
				boolean hasOnDemandImport = false;
				IImportDeclaration[] imports = cu.getImports();
				for (IImportDeclaration importDecl : imports) {
					if (importDecl.isOnDemand()) {
						hasOnDemandImport = true;
					} else {
						String importName = importDecl.getElementName();
						int packageLength = importName.length() - getNewElementName().length() - 1;
						if (packageLength > 0 && importName.endsWith(getNewElementName()) && importName.charAt(packageLength) == '.') {
							continue cus; // explicit import from another package => no problem
						}
					}
				}
				if (hasOnDemandImport) {
					// the renamed type in the same package will shadow the *-imported type
					conflicts.add(cu);
				}
			}
		}
	}

	for (ICompilationUnit conflict : conflicts) {
		RefactoringStatusContext context = JavaStatusContext.create(conflict);
		String message = Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_another_type, new String[] { getNewElementLabel(), BasicElementLabels.getFileName(conflict) });
		result.addError(message, context);
	}
	return result;
}
 
Example 18
Source File: PackageParser.java    From aDoctor with MIT License 3 votes vote down vote up
public static PackageBean parse(IPackageFragment pPackage) throws JavaModelException {
    PackageBean packageBean = new PackageBean();
    CodeParser codeParser = new CodeParser();
    String textualContent = "";

    ArrayList<ClassBean> classes = new ArrayList<>();

    packageBean.setName(pPackage.getElementName());

    for (ICompilationUnit cu : pPackage.getCompilationUnits()) {

        textualContent += cu.getSource();

        CompilationUnit parsed = codeParser.createParser(cu.getSource());
        TypeDeclaration typeDeclaration = (TypeDeclaration) parsed.types().get(0);

        ArrayList<String> imported = new ArrayList<>();

        for (IImportDeclaration importedResource : cu.getImports()) {
            imported.add(importedResource.getElementName());
        }

        classes.add(ClassParser.parse(typeDeclaration, packageBean.getName(), imported));
    }

    packageBean.setTextContent(textualContent);

    return packageBean;
}