Java Code Examples for org.eclipse.jdt.core.IPackageFragment#getCompilationUnits()

The following examples show how to use org.eclipse.jdt.core.IPackageFragment#getCompilationUnits() . 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: FindStringsToExternalizeAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<NonNLSElement> analyze(IPackageFragment pack, IProgressMonitor pm) throws CoreException {
	try{
		if (pack == null)
			return new ArrayList<NonNLSElement>(0);

		ICompilationUnit[] cus= pack.getCompilationUnits();

		pm.beginTask("", cus.length); //$NON-NLS-1$
		pm.setTaskName(pack.getElementName());

		List<NonNLSElement> l= new ArrayList<NonNLSElement>(cus.length);
		for (int i= 0; i < cus.length; i++){
			pm.subTask(BasicElementLabels.getFileName(cus[i]));
			NonNLSElement element= analyze(cus[i]);
			if (element != null)
				l.add(element);
			pm.worked(1);
			if (pm.isCanceled())
				throw new OperationCanceledException();
		}
		return l;
	} finally {
		pm.done();
	}
}
 
Example 2
Source File: TypeCheckingEvolution.java    From JDeodorant with MIT License 6 votes vote down vote up
private List<TypeCheckElimination> generateTypeCheckEliminationsWithinJavaProject(IJavaProject javaProject, TypeCheckElimination elimination) {
	List<TypeCheckElimination> typeCheckEliminations = new ArrayList<TypeCheckElimination>();
	try {
		IPackageFragmentRoot[] iPackageFragmentRoots = javaProject.getPackageFragmentRoots();
		for(IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
			IJavaElement[] children = iPackageFragmentRoot.getChildren();
			for(IJavaElement child : children) {
				if(child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
					IPackageFragment iPackageFragment = (IPackageFragment)child;
					ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
					for(ICompilationUnit iCompilationUnit : iCompilationUnits) {
						ASTParser parser = ASTParser.newParser(ASTReader.JLS);
				        parser.setKind(ASTParser.K_COMPILATION_UNIT);
				        parser.setSource(iCompilationUnit);
				        parser.setResolveBindings(true); // we need bindings later on
				        CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
						typeCheckEliminations.addAll(generateTypeCheckEliminationsWithinCompilationUnit(compilationUnit, elimination));
					}
				}
			}
		}
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	return typeCheckEliminations;
}
 
Example 3
Source File: RenamePackageChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void renamePackage(IPackageFragment pack, IProgressMonitor pm, IPath newPath, String newName) throws JavaModelException, CoreException {
	if (! pack.exists())
	 {
		return; // happens if empty parent with single subpackage is renamed, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=199045
	}
	pack.rename(newName, false, pm);
	if (fCompilationUnitStamps != null) {
		IPackageFragment newPack= (IPackageFragment) JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getFolder(newPath));
		if (newPack.exists()) {
			ICompilationUnit[] units= newPack.getCompilationUnits();
			for (int i= 0; i < units.length; i++) {
				IResource resource= units[i].getResource();
				if (resource != null) {
					Long stamp= fCompilationUnitStamps.get(resource);
					if (stamp != null) {
						resource.revertModificationStamp(stamp.longValue());
					}
				}
			}
		}
	}
}
 
Example 4
Source File: ProjectAwareUniqueClassNameValidator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private SourceTraversal doCheckUniqueInProjectSource(String packageName, String typeName, JvmDeclaredType type,
		List<IPackageFragmentRoot> sourceFolders) throws JavaModelException {
	IndexManager indexManager = JavaModelManager.getIndexManager();
	for (IPackageFragmentRoot sourceFolder : sourceFolders) {
		if (indexManager.awaitingJobsCount() > 0) {
			if (!isDerived(sourceFolder.getResource())) {
				IPackageFragment packageFragment = sourceFolder.getPackageFragment(packageName);
				if (packageFragment.exists()) {
					for (ICompilationUnit unit : packageFragment.getCompilationUnits()) {
						if (!isDerived(unit.getResource())) {
							IType javaType = unit.getType(typeName);
							if (javaType.exists()) {
								addIssue(type, unit.getElementName());
								return SourceTraversal.DUPLICATE;
							}
						}
					}
				}
			}
		} else {
			return SourceTraversal.INTERRUPT;
		}
	}
	return SourceTraversal.UNIQUE;
}
 
Example 5
Source File: ExternalizeStringsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<NonNLSElement> analyze(IPackageFragment pack, IProgressMonitor pm) throws CoreException {
	try{
		if (pack == null)
			return new ArrayList<NonNLSElement>(0);

		ICompilationUnit[] cus= pack.getCompilationUnits();

		pm.beginTask("", cus.length); //$NON-NLS-1$
		pm.setTaskName(pack.getElementName());

		List<NonNLSElement> l= new ArrayList<NonNLSElement>(cus.length);
		for (int i= 0; i < cus.length; i++){
			pm.subTask(BasicElementLabels.getFileName(cus[i]));
			NonNLSElement element= analyze(cus[i]);
			if (element != null)
				l.add(element);
			pm.worked(1);
			if (pm.isCanceled())
				throw new OperationCanceledException();
		}
		return l;
	} finally {
		pm.done();
	}
}
 
Example 6
Source File: ASTReader.java    From JDeodorant with MIT License 6 votes vote down vote up
public static int getNumberOfCompilationUnits(IJavaProject iJavaProject) {
	int numberOfCompilationUnits = 0;
	try {
		IPackageFragmentRoot[] iPackageFragmentRoots = iJavaProject.getPackageFragmentRoots();
		for(IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
			IJavaElement[] children = iPackageFragmentRoot.getChildren();
			for(IJavaElement child : children) {
				if(child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
					IPackageFragment iPackageFragment = (IPackageFragment)child;
					ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
					numberOfCompilationUnits += iCompilationUnits.length;
				}
			}
		}
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	return numberOfCompilationUnits;
}
 
Example 7
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkTypeNameConflicts(IPackageFragmentRoot root, String newName, Set<String> topLevelTypeNames) throws CoreException {
	IPackageFragment otherPack= root.getPackageFragment(newName);
	if (fPackage.equals(otherPack))
		return null;
	ICompilationUnit[] cus= otherPack.getCompilationUnits();
	RefactoringStatus result= new RefactoringStatus();
	for (int i= 0; i < cus.length; i++) {
		result.merge(checkTypeNameConflicts(cus[i], topLevelTypeNames));
	}
	return result;
}
 
Example 8
Source File: ElementTypeTeller.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isModelRootPackage(IPackageFragment pack) throws JavaModelException {
	ICompilationUnit[] compilationUnits = pack.getCompilationUnits();
	for (ICompilationUnit compUnit : compilationUnits) {
		if (compUnit.getElementName().equals("package-info.java")) {
			if (checkPackageInfo(compUnit)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 9
Source File: WizardUtils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 
 * @return the list of classes in the given package which extends at least
 *         one of the given superclasses directly.
 */
public static List<IType> getTypesBySuperclass(IPackageFragment packageFragment, Class<?>... superClasses) {
	List<IType> typesWithGivenSuperclass = new ArrayList<>();

	ICompilationUnit[] compilationUnits;
	try {
		compilationUnits = packageFragment.getCompilationUnits();
	} catch (JavaModelException ex) {
		return Collections.emptyList();
	}

	List<SuperTypeListJob> jobs = new ArrayList<>();
	for (ICompilationUnit cUnit : compilationUnits) {
		SuperTypeListJob job = new SuperTypeListJob("Get supertype list", cUnit, superClasses);
		jobs.add(job);
		job.setPriority(Job.INTERACTIVE);
		job.schedule();
	}

	jobs.stream().forEach(job -> {
		try {
			job.join();
			typesWithGivenSuperclass.addAll(job.gettypesWithGivenSuperclass());
		} catch (InterruptedException e) {
		}
	});

	return typesWithGivenSuperclass;
}
 
Example 10
Source File: JavaModelSearch.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static List<IType> findAllTopLevelTypes(IPackageFragment pckg)
    throws JavaModelException {
  List<IType> types = new ArrayList<IType>();
  for (ICompilationUnit cu : pckg.getCompilationUnits()) {
    types.addAll(Arrays.asList(cu.getTypes()));
  }
  return types;
}
 
Example 11
Source File: BuilderUtils.java    From JReFrameworker with MIT License 5 votes vote down vote up
/**
 * Returns a collection of K_SOURCE Compilation units in the project's package fragments
 * Reference: https://www.eclipse.org/forums/index.php/t/68072/
 * @param javaproject
 * @return
 */
public static final ICompilationUnit[] getSourceCompilationUnits(IJavaProject jProject) {
	ArrayList<ICompilationUnit> sourceCompilationUnits = new ArrayList<ICompilationUnit>();
	try {
		IPackageFragmentRoot[] roots = jProject.getPackageFragmentRoots();
		for (int i = 0; i < roots.length; i++) {
			IPackageFragmentRoot root = roots[i];
			if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
				IJavaElement[] javaElements = root.getChildren();
				for (int j = 0; j < javaElements.length; j++) {
					IJavaElement javaElement = javaElements[j];
					if (javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
						IPackageFragment pf = (IPackageFragment) javaElement;
						ICompilationUnit[] compilationUnits = pf.getCompilationUnits();
						for (int k = 0; k < compilationUnits.length; k++) {
							ICompilationUnit unit = compilationUnits[k];
							if (unit.isStructureKnown()) {
								sourceCompilationUnits.add(unit);
							}
						}
					}
				}
			}
		}
	} catch (CoreException e) {
		e.printStackTrace();
	}
	ICompilationUnit[] sourceCompilationUnitsArray = new ICompilationUnit[sourceCompilationUnits.size()];
	sourceCompilationUnits.toArray(sourceCompilationUnitsArray);
	return sourceCompilationUnitsArray;
}
 
Example 12
Source File: RenamePackageChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void isValid(RefactoringStatus result, IPackageFragment pack, IProgressMonitor pm) throws JavaModelException {
	ICompilationUnit[] units= pack.getCompilationUnits();
	pm.beginTask("", units.length); //$NON-NLS-1$
	for (int i= 0; i < units.length; i++) {
		pm.subTask(Messages.format(RefactoringCoreMessages.RenamePackageChange_checking_change, JavaElementLabels.getElementLabel(pack, JavaElementLabels.ALL_DEFAULT)));
		checkIfModifiable(result, units[i].getResource(), VALIDATE_NOT_READ_ONLY | VALIDATE_NOT_DIRTY);
		pm.worked(1);
	}
	pm.done();
}
 
Example 13
Source File: JavaEditorBreadcrumb.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Object[] getPackageContent(IPackageFragment pack) {
	ArrayList<Object> result= new ArrayList<Object>();
	try {
		ICompilationUnit[] units= pack.getCompilationUnits();
		for (int i= 0; i < units.length; i++) {
			if (JavaModelUtil.isPackageInfo(units[i]))
				result.add(units[i]);
			IType[] types= units[i].getTypes();
			for (int j= 0; j < types.length; j++) {
				if (isValidType(types[j]))
					result.add(types[j]);
			}
		}

		IClassFile[] classFiles= pack.getClassFiles();
		for (int i= 0; i < classFiles.length; i++) {
			if (isValidType(classFiles[i].getType()))
				result.add(classFiles[i].getType());
		}

		Object[] nonJavaResources= pack.getNonJavaResources();
		for (int i= 0; i < nonJavaResources.length; i++) {
			result.add(nonJavaResources[i]);
		}
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
	}

	return result.toArray();
}
 
Example 14
Source File: ASTReader.java    From JDeodorant with MIT License 5 votes vote down vote up
public ASTReader(IJavaProject iJavaProject, IProgressMonitor monitor) throws CompilationErrorDetectedException {
	List<IMarker> markers = buildProject(iJavaProject, monitor);
	if(!markers.isEmpty()) {
		throw new CompilationErrorDetectedException(markers);
	}
	if(monitor != null)
		monitor.beginTask("Parsing selected Java Project", getNumberOfCompilationUnits(iJavaProject));
	systemObject = new SystemObject();
	examinedProject = iJavaProject;
	try {
		IPackageFragmentRoot[] iPackageFragmentRoots = iJavaProject.getPackageFragmentRoots();
		for(IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
			IJavaElement[] children = iPackageFragmentRoot.getChildren();
			for(IJavaElement child : children) {
				if(child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
					IPackageFragment iPackageFragment = (IPackageFragment)child;
					ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
					for(ICompilationUnit iCompilationUnit : iCompilationUnits) {
						if(monitor != null && monitor.isCanceled())
			    			throw new OperationCanceledException();
						systemObject.addClasses(parseAST(iCompilationUnit));
						if(monitor != null)
							monitor.worked(1);
					}
				}
			}
		}
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	if(monitor != null)
		monitor.done();
}
 
Example 15
Source File: UserJavaProject.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * List all methods located in the source folder of a javaProject
 *
 * @param javaProject
 * @return list of methods
 * @throws CoreException
 */
public List<IMethod> listOfAllMethods() throws CoreException {
	final IJavaProject javaProject = toJavaProject(this.project);
	if (javaProject != null) {
		final List<IMethod> methodsList = new ArrayList<IMethod>();
		final IPackageFragment[] packages = javaProject.getPackageFragments();
		for (final IPackageFragment pack : packages) {
			// look at the package from the source folder
			if (pack.getKind() == IPackageFragmentRoot.K_SOURCE) {

				for (final ICompilationUnit unit : pack.getCompilationUnits()) {

					final IType[] allTypes = unit.getAllTypes();
					for (final IType type : allTypes) {
						final IMethod[] methods = type.getMethods();

						for (final IMethod method : methods) {
							methodsList.add(method);
						}
					}
				}
			}
		}
		return methodsList;
	}
	return null;
}
 
Example 16
Source File: ProblemMarkerBuilder.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * getUnitForParser Method to get the CompilationUnits from the PackageFragments and start the parsing process from there
 *
 * @param mypackage IPackageFragment from startMarking
 * @throws JavaModelException
 */
private void getUnitForParser(final IPackageFragment mypackage) throws JavaModelException {
	if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
		for (final ICompilationUnit unit : mypackage.getCompilationUnits()) {
			setupParser(unit);
		}
	}
}
 
Example 17
Source File: PackagesViewLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isEmpty(IPackageFragment fragment) {
	try {
		return (fragment.getCompilationUnits().length == 0) && (fragment.getClassFiles().length == 0);
	} catch (JavaModelException e) {
		// ignore
	}
	return false;
}
 
Example 18
Source File: ChangeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void convertRenamePackcageChange(WorkspaceEdit edit, RenamePackageChange packageChange) throws CoreException {
	IPackageFragment pack = (IPackageFragment) packageChange.getModifiedElement();
	IPath newPackageFragment = new Path(packageChange.getNewName().replace('.', IPath.SEPARATOR));
	IPath oldPackageFragment = new Path(packageChange.getOldName().replace('.', IPath.SEPARATOR));
	IPath newPackagePath = pack.getResource().getLocation().removeLastSegments(oldPackageFragment.segmentCount()).append(newPackageFragment);
	if (packageChange.getRenameSubpackages()) {
		IPackageFragment[] allPackages = JavaElementUtil.getPackageAndSubpackages(pack);
		String oldPrefix = packageChange.getOldName();
		for (IPackageFragment currentPackage : allPackages) {
			String newPkgName = packageChange.getNewName() + currentPackage.getElementName().substring(oldPrefix.length());
			//update package's declaration
			convertPackageUpdateEdit(currentPackage.getCompilationUnits(), newPkgName, edit);
		}

		RenameFile renameFile = new RenameFile();
		renameFile.setNewUri(ResourceUtils.fixURI(newPackagePath.toFile().toURI()));
		renameFile.setOldUri(ResourceUtils.fixURI(pack.getResource().getRawLocationURI()));
		edit.getDocumentChanges().add(Either.forRight(renameFile));
	} else {
		//update package's declaration
		convertPackageUpdateEdit(pack.getCompilationUnits(), packageChange.getNewName(), edit);
	
		CreateFile createFile = new CreateFile();
		createFile.setUri(ResourceUtils.fixURI(newPackagePath.append(TEMP_FILE_NAME).toFile().toURI()));
		createFile.setOptions(new CreateFileOptions(false, true));
		edit.getDocumentChanges().add(Either.forRight(createFile));

		for (ICompilationUnit unit : pack.getCompilationUnits()) {
			RenameFile cuResourceChange = new RenameFile();
			cuResourceChange.setOldUri(ResourceUtils.fixURI(unit.getResource().getLocationURI()));
			IPath newCUPath = newPackagePath.append(unit.getPath().lastSegment());
			cuResourceChange.setNewUri(ResourceUtils.fixURI(newCUPath.toFile().toURI()));
			edit.getDocumentChanges().add(Either.forRight(cuResourceChange));
		}

		// Workaround: https://github.com/Microsoft/language-server-protocol/issues/272
		DeleteFile deleteFile = new DeleteFile();
		deleteFile.setUri(ResourceUtils.fixURI(newPackagePath.append(TEMP_FILE_NAME).toFile().toURI()));
		deleteFile.setOptions(new DeleteFileOptions(false, true));
		edit.getDocumentChanges().add(Either.forRight(deleteFile));

	}
}
 
Example 19
Source File: JavaUtils.java    From developer-studio with Apache License 2.0 4 votes vote down vote up
public static boolean isClassImplement(IProject project, String interfaceTocheck) throws JavaModelException{
		IJavaProject jp = JavaCore.create(project);
		try {
			IPackageFragment[] packageFragments = jp.getPackageFragments();
			for (IPackageFragment fragment : packageFragments) {
				IJavaElement[] children = fragment.getChildren();
				for (IJavaElement element : children) {
						ICompilationUnit[] compilationUnits = fragment.getCompilationUnits();
						for (ICompilationUnit unit : compilationUnits) {
							String a = unit.getElementName();
							IType[] types = unit.getTypes();
							for (IType type : types) {
								String[] superInterfaceNames = type.getSuperInterfaceNames();
								if(superInterfaceNames != null){
									for (String interfaceName : superInterfaceNames) {
										if(interfaceName.equals(interfaceTocheck)){
											return true;
										}
									}
								}
							}
						}
				}
			}
		} catch (JavaModelException e) {
			e.printStackTrace();
		}
		
//		IType findType = getJavaITypeForClass(jp, fullyQualifiedClassName);
//		if (findType!=null && findType.getSuperclassName()!=null){
//			String[][] resolveType = findType.resolveType(findType.getSuperclassName());
//			if (resolveType!=null){
//				String fullyQualifiedSuperClassName=(resolveType[0][0]).toString()+"."+(resolveType[0][1]).toString();
//				boolean result = isClassImplement(project, fullyQualifiedSuperClassName,classNameToCheck);
//				if (result){
//					return true;
//				}
//			}
//		}
	
	return false;
		
	}
 
Example 20
Source File: JavadocOptionsManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean containsCompilationUnits(IPackageFragment pack) throws JavaModelException {
	return pack.getCompilationUnits().length > 0;
}