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

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#getTypes() . 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: FindBrokenNLSKeysAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static IStorage getResourceBundle(ICompilationUnit compilationUnit) throws JavaModelException {
	if (compilationUnit == null)
		return null;

	if (!ActionUtil.isOnBuildPath(compilationUnit))
		return null;

	IType[] types= compilationUnit.getTypes();
	if (types.length != 1)
		return null;

	if (!isPotentialNLSAccessor(compilationUnit))
		return null;

	return NLSHintHelper.getResourceBundle(compilationUnit);
}
 
Example 2
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 3
Source File: MoveModifications.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public void move(ICompilationUnit unit, MoveArguments args) throws CoreException {
	add(unit, args, null);
	IType[] types= unit.getTypes();
	for (int tt= 0; tt < types.length; tt++) {
		add(types[tt], args, null);
	}
	IResource resourceDestination= getResourceDestination(args);
	if (resourceDestination != null && unit.getResource() != null) {
		IResource parent= resourceDestination;
		while (!parent.exists()) {
			getResourceModifications().addCreate(parent);
			parent= parent.getParent();
		}

		getResourceModifications().addMove(unit.getResource(), new MoveArguments(resourceDestination, args.getUpdateReferences()));
	}
}
 
Example 4
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 5
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void computeQualifiedNameMatches(IProgressMonitor pm) throws JavaModelException {
	if (!fUpdateQualifiedNames) {
		return;
	}
	IPackageFragment destination= getDestinationAsPackageFragment();
	if (destination != null) {
		ICompilationUnit[] cus= getCus();
		pm.beginTask("", cus.length); //$NON-NLS-1$
		pm.subTask(RefactoringCoreMessages.MoveRefactoring_scanning_qualified_names);
		for (int i= 0; i < cus.length; i++) {
			ICompilationUnit cu= cus[i];
			IType[] types= cu.getTypes();
			IProgressMonitor typesMonitor= new SubProgressMonitor(pm, 1);
			typesMonitor.beginTask("", types.length); //$NON-NLS-1$
			for (int j= 0; j < types.length; j++) {
				handleType(types[j], destination, new SubProgressMonitor(typesMonitor, 1));
				if (typesMonitor.isCanceled()) {
					throw new OperationCanceledException();
				}
			}
			typesMonitor.done();
		}
	}
	pm.done();
}
 
Example 6
Source File: NLSAccessorFieldRenameParticipant.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean isPotentialNLSAccessor(ICompilationUnit unit) throws JavaModelException {
	IType type= unit.getTypes()[0];
	if (!type.exists())
		return false;

	IField bundleNameField= getBundleNameField(type.getFields());
	if (bundleNameField == null)
		return false;

	if (!importsOSGIUtil(unit))
		return false;

	IInitializer[] initializers= type.getInitializers();
	for (int i= 0; i < initializers.length; i++) {
		if (Modifier.isStatic(initializers[0].getFlags()))
			return true;
	}

	return false;
}
 
Example 7
Source File: AddResourcesToClientBundleAction.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private static IType findFirstTopLevelClientBundleType(IFile file) {
  try {
    IJavaElement element = JavaCore.create(file);
    if (element instanceof ICompilationUnit) {
      ICompilationUnit cu = (ICompilationUnit) element;
      if (cu.exists()) {
        for (IType type : cu.getTypes()) {
          if (ClientBundleUtilities.isClientBundle(cu.getJavaProject(), type)) {
            return type;
          }
        }
      }
    }
  } catch (JavaModelException e) {
    GWTPluginLog.logError(e);
  }
  return null;
}
 
Example 8
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IJavaElement[] getActualJavaElementsToReorg() throws JavaModelException {
	List<IJavaElement> result= new ArrayList<IJavaElement>();
	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 9
Source File: JavaBrowsingPart.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected IType getTypeForCU(ICompilationUnit cu) {
	// Use primary type if possible
	IType primaryType= cu.findPrimaryType();
	if (primaryType != null)
		return primaryType;

	// Use first top-level type
	try {
		IType[] types= cu.getTypes();
		if (types.length > 0)
			return types[0];
		else
			return null;
	} catch (JavaModelException ex) {
		return null;
	}
}
 
Example 10
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Collection<String> getTopLevelTypeNames(ICompilationUnit iCompilationUnit) throws CoreException {
	IType[] types= iCompilationUnit.getTypes();
	List<String> result= new ArrayList<String>(types.length);
	for (int i= 0; i < types.length; i++) {
		result.add(types[i].getElementName());
	}
	return result;
}
 
Example 11
Source File: SortMembersAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(IStructuredSelection selection) {
	Shell shell= getShell();
	try {
		ICompilationUnit cu= getSelectedCompilationUnit(selection);
		if (cu == null) {
			return;
		}
		IType[] types= cu.getTypes();
		if (!hasMembersToSort(types)) {
			return;
		}
		if (!ActionUtil.isEditable(getShell(), cu)) {
			return;
		}

		SortMembersMessageDialog dialog= new SortMembersMessageDialog(getShell());
		if (dialog.open() != Window.OK) {
			return;
		}

		if (!ElementValidator.check(cu, getShell(), getDialogTitle(), false)) {
			return;
		}

		// open an editor and work on a working copy
		IEditorPart editor= JavaUI.openInEditor(cu);
		if (editor != null) {
			run(shell, cu, editor, dialog.isNotSortingFieldsEnabled());
		}
	} catch (CoreException e) {
		ExceptionHandler.handle(e, shell, getDialogTitle(), null);
	}
}
 
Example 12
Source File: JavaElementUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IType getMainType(ICompilationUnit cu) throws JavaModelException{
	IType[] types= cu.getTypes();
	for (int i = 0; i < types.length; i++) {
		if (isMainType(types[i]))
			return types[i];
	}
	return null;
}
 
Example 13
Source File: FindBrokenNLSKeysAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private SearchPatternData tryIfPropertyCuSelected(ICompilationUnit compilationUnit) throws JavaModelException {
	IStorage bundle= getResourceBundle(compilationUnit);
	if (!(bundle instanceof IFile))
		return null;

	return new SearchPatternData(compilationUnit.getTypes()[0], (IFile) bundle);
}
 
Example 14
Source File: PackageExplorerPart.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * A compilation unit or class was expanded, expand
 * the main type.
 * @param element the element
 */
void expandMainType(Object element) {
	try {
		IType type= null;
		if (element instanceof ICompilationUnit) {
			ICompilationUnit cu= (ICompilationUnit)element;
			IType[] types= cu.getTypes();
			if (types.length > 0)
				type= types[0];
		}
		else if (element instanceof IClassFile) {
			IClassFile cf= (IClassFile)element;
			type= cf.getType();
		}
		if (type != null) {
			final IType type2= type;
			Control ctrl= fViewer.getControl();
			if (ctrl != null && !ctrl.isDisposed()) {
				ctrl.getDisplay().asyncExec(new Runnable() {
					public void run() {
						Control ctrl2= fViewer.getControl();
						if (ctrl2 != null && !ctrl2.isDisposed())
							fViewer.expandToLevel(type2, 1);
					}
				});
			}
		}
	} catch(JavaModelException e) {
		// no reveal
	}
}
 
Example 15
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkTypeNameConflicts(ICompilationUnit iCompilationUnit, Set<String> topLevelTypeNames) throws CoreException {
	RefactoringStatus result= new RefactoringStatus();
	IType[] types= iCompilationUnit.getTypes();

	for (int i= 0; i < types.length; i++) {
		String name= types[i].getElementName();
		if (topLevelTypeNames.contains(name)){
			String[] keys= {getElementLabel(iCompilationUnit.getParent()), getElementLabel(types[i])};
			String msg= Messages.format(RefactoringCoreMessages.RenamePackageRefactoring_contains_type, keys);
			RefactoringStatusContext context= JavaStatusContext.create(types[i]);
			result.addError(msg, context);
		}
	}
	return result;
}
 
Example 16
Source File: WorkItem.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Add secondary types patterns (not nested in the type itself but contained
 * in the java file)
 *
 * @param fileName
 *            java file name (not path!) without .java suffix
 * @param classNamePattern
 *            non null pattern for all matching .class file names
 * @return modified classNamePattern, if there are more then one type
 *         defined in the java file
 */
private static String addSecondaryTypesToPattern(IFile file, String fileName, String classNamePattern) {
    ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
    if (cu == null) {
        FindbugsPlugin.getDefault().logError(
                "NULL compilation unit for " + file + ", FB analysis might  be incomplete for included types");
        return classNamePattern;
    }
    try {
        IType[] types = cu.getTypes();
        if (types.length > 1) {
            StringBuilder sb = new StringBuilder(classNamePattern);
            for (IType type : types) {
                if (fileName.equals(type.getElementName())) {
                    // "usual" type with the same name: we have it already
                    continue;
                }
                sb.append("|").append(type.getElementName());
                sb.append("\\.class|").append(type.getElementName());
                sb.append("\\$.*\\.class");
            }
            classNamePattern = sb.toString();
        }
    } catch (JavaModelException e) {
        FindbugsPlugin.getDefault().logException(e, "Cannot get types from compilation unit: " + cu);
    }
    return classNamePattern;
}
 
Example 17
Source File: TopLevelTypeProblemsLabelDecorator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
	protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException {
//		XXX: Work in progress for problem decorator being a workbench decorator
//		IDecoratorManager decoratorMgr= PlatformUI.getWorkbench().getDecoratorManager();
//		if (!decoratorMgr.getEnabled("org.eclipse.jdt.ui.problem.decorator")) //$NON-NLS-1$
//			return false;

		if (!(sourceElement instanceof IType) || ((IType)sourceElement).getDeclaringType() != null)
			return false;

		ICompilationUnit cu= ((IType)sourceElement).getCompilationUnit();
		if (cu == null)
			return false;
		IType[] types= cu.getTypes();
		if (types.length < 1)
			return false;

		int firstTypeStartOffset= -1;
		ISourceRange range= types[0].getSourceRange();
		if (range != null)
			firstTypeStartOffset= range.getOffset();

		int lastTypeEndOffset= -1;
		range= types[types.length-1].getSourceRange();
		if (range != null)
			lastTypeEndOffset= range.getOffset() + range.getLength() - 1;

		return pos < firstTypeStartOffset || pos > lastTypeEndOffset || isInside(pos, sourceElement.getSourceRange());
	}
 
Example 18
Source File: JavaElementUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static IType getMainType(ICompilationUnit cu) throws JavaModelException{
	IType[] types= cu.getTypes();
	for (int i = 0; i < types.length; i++) {
		if (isMainType(types[i])) {
			return types[i];
		}
	}
	return null;
}
 
Example 19
Source File: OpenTypeHierarchyUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Converts the input to a possible input candidates
 * @param input input
 * @return the possible candidates
 */
public static IJavaElement[] getCandidates(Object input) {
	if (!(input instanceof IJavaElement)) {
		return null;
	}
	try {
		IJavaElement elem= (IJavaElement) input;
		switch (elem.getElementType()) {
			case IJavaElement.INITIALIZER:
			case IJavaElement.METHOD:
			case IJavaElement.FIELD:
			case IJavaElement.TYPE:
			case IJavaElement.PACKAGE_FRAGMENT_ROOT:
			case IJavaElement.JAVA_PROJECT:
				return new IJavaElement[] { elem };
			case IJavaElement.PACKAGE_FRAGMENT:
				if (((IPackageFragment)elem).containsJavaResources())
					return new IJavaElement[] {elem};
				break;
			case IJavaElement.PACKAGE_DECLARATION:
				return new IJavaElement[] { elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT) };
			case IJavaElement.IMPORT_DECLARATION:
				IImportDeclaration decl= (IImportDeclaration) elem;
				if (decl.isOnDemand()) {
					elem= JavaModelUtil.findTypeContainer(elem.getJavaProject(), Signature.getQualifier(elem.getElementName()));
				} else {
					elem= elem.getJavaProject().findType(elem.getElementName());
				}
				if (elem == null)
					return null;
				return new IJavaElement[] {elem};

			case IJavaElement.CLASS_FILE:
				return new IJavaElement[] { ((IClassFile)input).getType() };
			case IJavaElement.COMPILATION_UNIT: {
				ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
				if (cu != null) {
					IType[] types= cu.getTypes();
					if (types.length > 0) {
						return types;
					}
				}
				break;
			}
			default:
		}
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
	}
	return null;
}
 
Example 20
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;
		
	}