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

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#exists() . 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: FilteringCompositeChange.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected Change createUndoChange(Change[] childUndos) {
	List<Change> filteredUndos = newArrayList();
	for (Change childUndo : childUndos) {
		try {
			Object modifiedElement = childUndo.getModifiedElement();
			if (modifiedElement instanceof ICompilationUnit) {
				ICompilationUnit cu = (ICompilationUnit) modifiedElement;
				if (cu.exists()) {
					IResource resource = cu.getUnderlyingResource();
					if (!resource.isDerived()) {
						filteredUndos.add(childUndo);
					}
				}
			} else {
				filteredUndos.add(childUndo);
			}
		} catch (JavaModelException e) {
			LOG.error("Error filtering refactoring undo changes", e);
		}
	}
	return super.createUndoChange(toArray(filteredUndos, Change.class));
}
 
Example 2
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 3
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Evaluates a 'java' template in the context of a compilation unit
 *
 * @param template the template to be evaluated
 * @param compilationUnit the compilation unit in which to evaluate the template
 * @param position the position inside the compilation unit for which to evaluate the template
 * @return the evaluated template
 * @throws CoreException in case the template is of an unknown context type
 * @throws BadLocationException in case the position is invalid in the compilation unit
 * @throws TemplateException in case the evaluation fails
 */
public static String evaluateTemplate(Template template, ICompilationUnit compilationUnit, int position) throws CoreException, BadLocationException, TemplateException {

	TemplateContextType contextType= JavaPlugin.getDefault().getTemplateContextRegistry().getContextType(template.getContextTypeId());
	if (!(contextType instanceof CompilationUnitContextType))
		throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, JavaTemplateMessages.JavaContext_error_message, null));

	IDocument document= new Document();
	if (compilationUnit != null && compilationUnit.exists())
		document.set(compilationUnit.getSource());

	CompilationUnitContext context= ((CompilationUnitContextType) contextType).createContext(document, position, 0, compilationUnit);
	context.setForceEvaluation(true);

	TemplateBuffer buffer= context.evaluate(template);
	if (buffer == null)
		return null;
	return buffer.getString();
}
 
Example 4
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isInferTypeArgumentsAvailable(final IStructuredSelection selection) throws JavaModelException {
	if (selection.isEmpty())
		return false;

	for (Iterator<?> iter= selection.iterator(); iter.hasNext();) {
		Object element= iter.next();
		if (!(element instanceof IJavaElement))
			return false;
		if (element instanceof ICompilationUnit) {
			ICompilationUnit unit= (ICompilationUnit) element;
			if (!unit.exists() || unit.isReadOnly())
				return false;

			return true;
		}
		if (!isInferTypeArgumentsAvailable((IJavaElement) element))
			return false;
	}
	return true;
}
 
Example 5
Source File: ExternalizeWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void open(final ICompilationUnit unit, final Shell shell) {
	if (unit == null || !unit.exists()) {
		return;
	}
	Display display= shell != null ? shell.getDisplay() : Display.getCurrent();
	BusyIndicator.showWhile(display, new Runnable() {
		public void run() {
			NLSRefactoring refactoring= null;
			try {
				refactoring= NLSRefactoring.create(unit);
			} catch (IllegalArgumentException e) {
				// Loading a properties file can throw an IAE due to malformed Unicode escape sequence, see Properties#load for details.
				IStatus status= new Status(IStatus.ERROR, JavaPlugin.getPluginId(), e.getLocalizedMessage());
				ExceptionHandler.handle(status,
						NLSUIMessages.ExternalizeWizard_name,
						NLSUIMessages.ExternalizeWizard_error_message);
			}
			if (refactoring != null)
				new RefactoringStarter().activate(new ExternalizeWizard(refactoring), shell, ActionMessages.ExternalizeStringsAction_dialog_title, RefactoringSaveHelper.SAVE_REFACTORING);
		}
	});
}
 
Example 6
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 7
Source File: DeltaConverter.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.3
 * @deprecated This method is not used anymore.
 */
@Deprecated
protected IType getPrimaryTypeFrom(ICompilationUnit cu) {
	try {
		if (cu.exists()) {
			IType primaryType = cu.findPrimaryType();
			if (primaryType != null)
				return primaryType;

			// if no exact match is found, return the first public type in CU (if any)
			for (IType type : cu.getTypes()) {
				if (Flags.isPublic(type.getFlags()))
					return type;
			}
		}
	} catch (JavaModelException e) {
		if (LOGGER.isDebugEnabled())
			LOGGER.debug(e, e);
	}
	return null;
}
 
Example 8
Source File: ReorgCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void getWrongPackageDeclNameProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) throws CoreException {
	ICompilationUnit cu= context.getCompilationUnit();

	// correct package declaration
	int relevance= cu.getPackageDeclarations().length == 0 ? IProposalRelevance.MISSING_PACKAGE_DECLARATION : IProposalRelevance.CORRECT_PACKAGE_DECLARATION; // bug 38357
	proposals.add(new CorrectPackageDeclarationProposal(cu, problem, relevance));

	// move to package
	IPackageDeclaration[] packDecls= cu.getPackageDeclarations();
	String newPackName= packDecls.length > 0 ? packDecls[0].getElementName() : ""; //$NON-NLS-1$

	IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(cu);
	IPackageFragment newPack= root.getPackageFragment(newPackName);

	ICompilationUnit newCU= newPack.getCompilationUnit(cu.getElementName());
	boolean isLinked= cu.getResource().isLinked();
	if (!newCU.exists() && !isLinked) {
		String label;
		if (newPack.isDefaultPackage()) {
			label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_movecu_default_description, BasicElementLabels.getFileName(cu));
		} else {
			String packageLabel= JavaElementLabels.getElementLabel(newPack, JavaElementLabels.ALL_DEFAULT);
			label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_movecu_description, new Object[] { BasicElementLabels.getFileName(cu), packageLabel });
		}

		proposals.add(new ChangeCorrectionProposal(label, CodeActionKind.QuickFix, new MoveCompilationUnitChange(cu, newPack), IProposalRelevance.MOVE_CU_TO_PACKAGE));
	}
}
 
Example 9
Source File: WorkspaceEventsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public void didChangeWatchedFiles(DidChangeWatchedFilesParams param) {
	List<FileEvent> changes = param.getChanges().stream().distinct().collect(Collectors.toList());
	for (FileEvent fileEvent : changes) {
		CHANGE_TYPE changeType = toChangeType(fileEvent.getType());
		if (changeType == CHANGE_TYPE.DELETED) {
			cleanUpDiagnostics(fileEvent.getUri());
			handler.didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(fileEvent.getUri())));
			discardWorkingCopies(fileEvent.getUri());
		}
		ICompilationUnit unit = JDTUtils.resolveCompilationUnit(fileEvent.getUri());
		if (unit != null && changeType == CHANGE_TYPE.CREATED && !unit.exists()) {
			final ICompilationUnit[] units = new ICompilationUnit[1];
			units[0] = unit;
			try {
				ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
					@Override
					public void run(IProgressMonitor monitor) throws CoreException {
						units[0] = createCompilationUnit(units[0]);
					}
				}, new NullProgressMonitor());
			} catch (CoreException e) {
				JavaLanguageServerPlugin.logException(e.getMessage(), e);
			}
			unit = units[0];
		}
		if (unit != null) {
			if (unit.isWorkingCopy()) {
				continue;
			}
			if (changeType == CHANGE_TYPE.DELETED || changeType == CHANGE_TYPE.CHANGED) {
				if (unit.equals(CoreASTProvider.getInstance().getActiveJavaElement())) {
					CoreASTProvider.getInstance().disposeAST();
				}
			}
		}
		pm.fileChanged(fileEvent.getUri(), changeType);
	}
}
 
Example 10
Source File: AbstractQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private String evaluateChanges(String uri, List<TextEdit> edits) throws BadLocationException, JavaModelException {
	assertFalse("No edits generated: " + edits, edits == null || edits.isEmpty());
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
	assertNotNull("CU not found: " + uri, cu);
	Document doc = new Document();
	if (cu.exists()) {
		doc.set(cu.getSource());
	}
	return TextEditUtil.apply(doc, edits);
}
 
Example 11
Source File: CompilationUnitResourceDependencyIndex.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private void loadCuDependencies(IMemento cuNode) {
  String cuHandle = cuNode.getString(ATTR_COMPILATION_UNIT);
  if (cuHandle == null) {
    CorePluginLog.logError("Loading index {0}: Missing attribute {1}",
        indexName, ATTR_COMPILATION_UNIT);
    return;
  }

  ICompilationUnit cu = (ICompilationUnit) JavaCore.create(cuHandle);
  // Verify the compilation unit still exists
  if (cu == null || !cu.exists()) {
    CorePluginLog.logError(
        "Loading index {0}: compilation unit no longer exists ({1})",
        indexName, cuHandle);
    return;
  }

  Set<IPath> resourcePaths = new HashSet<IPath>();
  for (IMemento resNode : cuNode.getChildren(TAG_RESOURCE)) {
    IPath resourcePath = getResourcePath(resNode);
    if (resourcePath == null) {
      CorePluginLog.logError("Loading index {0}: missing attribute {1}",
          indexName, ATTR_RESOURCE_PATH);
      continue;
    }

    resourcePaths.add(resourcePath);
  }

  // Now add these dependencies to the index
  index.putLeftToManyRights(cu, resourcePaths);
}
 
Example 12
Source File: JavaCompilationParticipant.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Re-validates the types which are current/former owner classes, and which
 * may need another validation pass (since they might not have been recognized
 * as owner classes on the first pass).
 *
 * @param preBuildOwnerIndex the pre-build owner types
 * @param validatedCompilationUnits units already validated
 */
private void revalidateOwnerTypes(
    UiBinderSubtypeToOwnerIndex preBuildOwnerIndex,
    Set<ICompilationUnit> validatedCompilationUnits) {
  UiBinderSubtypeToOwnerIndex postBuildOwnerIndex = UiBinderReferenceManager.INSTANCE.getSubtypeToOwnerIndex();

  // Compute the union of all current and former UiBinder+Owner pairs
  Set<UiBinderSubtypeAndOwner> subtypesAndOwners = new HashSet<UiBinderSubtypeAndOwner>(
      postBuildOwnerIndex.getAllUiBinderTypesAndOwners());
  subtypesAndOwners.addAll(preBuildOwnerIndex.getAllUiBinderTypesAndOwners());

  // Compute the set of owner type compilation units we need to re-validate
  Set<ICompilationUnit> cusToTouch = new HashSet<ICompilationUnit>();
  for (UiBinderSubtypeAndOwner entry : subtypesAndOwners) {
    // Only re-validate owner types for UiBinder subtypes we just validated
    if (validatedCompilationUnits.contains(entry.getUiBinderType().getCompilationUnit())) {
      IType ownerType = entry.findOwnerType();
      /*
       * Optimization: Don't need to re-validate owner classes which live in
       * the same source file as the UiBinder subtype, since we know we
       * recognized them on the original validation pass.
       */
      if (ownerType != null && !entry.hasCommonCompilationUnit()) {
        ICompilationUnit compilationUnit = ownerType.getCompilationUnit();
        // Binary types will have null compilation units
        if (compilationUnit != null && compilationUnit.exists()) {
          cusToTouch.add(compilationUnit);
        }
      }
    }
  }

  if (!cusToTouch.isEmpty()) {
    BuilderUtilities.revalidateCompilationUnits(cusToTouch,
        "Revalidating UiBinder owner classes");
  }
}
 
Example 13
Source File: NLSRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean willCreateAccessorClass() throws JavaModelException {

		ICompilationUnit compilationUnit= getAccessorCu();
		if (compilationUnit.exists()) {
			return false;
		}

		if (typeNameExistsInPackage(fAccessorClassPackage, fAccessorClassName)) {
			return false;
		}

		return (!Checks.resourceExists(getAccessorCUPath()));
	}
 
Example 14
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 15
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isExternalizeStringsAvailable(final IStructuredSelection selection) throws JavaModelException {
	for (Iterator<?> iter= selection.iterator(); iter.hasNext();) {
		Object element= iter.next();
		if (element instanceof IJavaElement) {
			IJavaElement javaElement= (IJavaElement)element;
			if (javaElement.exists() && !javaElement.isReadOnly()) {
				int elementType= javaElement.getElementType();
				if (elementType == IJavaElement.PACKAGE_FRAGMENT) {
					return true;
				} else if (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
					IPackageFragmentRoot root= (IPackageFragmentRoot)javaElement;
					if (!root.isExternal() && !ReorgUtils.isClassFolder(root))
						return true;
				} else if (elementType == IJavaElement.JAVA_PROJECT) {
					return true;
				} else if (elementType == IJavaElement.COMPILATION_UNIT) {
					ICompilationUnit cu= (ICompilationUnit)javaElement;
					if (cu.exists())
						return true;
				} else if (elementType == IJavaElement.TYPE) {
					IJavaElement parent= ((IType) element).getParent();
					if (parent instanceof ICompilationUnit && parent.exists())
						return true;
				}
			}
		} else if (element instanceof IWorkingSet) {
			IWorkingSet workingSet= (IWorkingSet) element;
			return IWorkingSetIDs.JAVA.equals(workingSet.getId());
		}
	}
	return false;
}
 
Example 16
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isExtractInterfaceAvailable(final IStructuredSelection selection) throws JavaModelException {
	if (selection.size() == 1) {
		Object first= selection.getFirstElement();
		if (first instanceof IType) {
			return isExtractInterfaceAvailable((IType) first);
		} else if (first instanceof ICompilationUnit) {
			ICompilationUnit unit= (ICompilationUnit) first;
			if (!unit.exists() || unit.isReadOnly())
				return false;

			return true;
		}
	}
	return false;
}
 
Example 17
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isUseSuperTypeAvailable(final IStructuredSelection selection) throws JavaModelException {
	if (selection.size() == 1) {
		final Object first= selection.getFirstElement();
		if (first instanceof IType) {
			return isUseSuperTypeAvailable((IType) first);
		} else if (first instanceof ICompilationUnit) {
			ICompilationUnit unit= (ICompilationUnit) first;
			if (!unit.exists() || unit.isReadOnly())
				return false;

			return true;
		}
	}
	return false;
}
 
Example 18
Source File: ReorgCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	boolean isLinked = cu.getResource().isLinked();

	IJavaProject javaProject= cu.getJavaProject();
	String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String compliance= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);

	CompilationUnit root= context.getASTRoot();

	ASTNode coveredNode= problem.getCoveredNode(root);
	if (!(coveredNode instanceof SimpleName)) {
		return;
	}

	ASTNode parentType= coveredNode.getParent();
	if (!(parentType instanceof AbstractTypeDeclaration)) {
		return;
	}

	String currTypeName= ((SimpleName) coveredNode).getIdentifier();
	String newTypeName= JavaCore.removeJavaLikeExtension(cu.getElementName());


	boolean hasOtherPublicTypeBefore = false;

	boolean found = false;
	List<AbstractTypeDeclaration> types= root.types();
	for (int i= 0; i < types.size(); i++) {
		AbstractTypeDeclaration curr= types.get(i);
		if (parentType != curr) {
			if (newTypeName.equals(curr.getName().getIdentifier())) {
				return;
			}
			if (!found && Modifier.isPublic(curr.getModifiers())) {
				hasOtherPublicTypeBefore = true;
			}
		} else {
			found = true;
		}
	}

	if (!JavaConventions.validateJavaTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
		proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, IProposalRelevance.RENAME_TYPE));
	}

	if (!hasOtherPublicTypeBefore && JavaLanguageServerPlugin.getPreferencesManager().getClientPreferences().isResourceOperationSupported()) {
		String newCUName = JavaModelUtil.getRenamedCUName(cu, currTypeName);
		ICompilationUnit newCU = ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
		if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
			RenameCompilationUnitChange change = new RenameCompilationUnitChange(cu, newCUName);

			// rename CU
			String label = Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, BasicElementLabels.getResourceName(newCUName));
			proposals.add(new ChangeCorrectionProposal(label, CodeActionKind.QuickFix, change, IProposalRelevance.RENAME_CU));
		}
	}

}
 
Example 19
Source File: ReorgCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	boolean isLinked= cu.getResource().isLinked();

	IJavaProject javaProject= cu.getJavaProject();
	String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String compliance= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);

	CompilationUnit root= context.getASTRoot();

	ASTNode coveredNode= problem.getCoveredNode(root);
	if (!(coveredNode instanceof SimpleName))
		return;

	ASTNode parentType= coveredNode.getParent();
	if (!(parentType instanceof AbstractTypeDeclaration))
		return;

	String currTypeName= ((SimpleName) coveredNode).getIdentifier();
	String newTypeName= JavaCore.removeJavaLikeExtension(cu.getElementName());

	boolean hasOtherPublicTypeBefore= false;

	boolean found= false;
	List<AbstractTypeDeclaration> types= root.types();
	for (int i= 0; i < types.size(); i++) {
		AbstractTypeDeclaration curr= types.get(i);
		if (parentType != curr) {
			if (newTypeName.equals(curr.getName().getIdentifier())) {
				return;
			}
			if (!found && Modifier.isPublic(curr.getModifiers())) {
				hasOtherPublicTypeBefore= true;
			}
		} else {
			found= true;
		}
	}
	if (!JavaConventions.validateJavaTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
		proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, IProposalRelevance.RENAME_TYPE));
	}

	if (!hasOtherPublicTypeBefore) {
		String newCUName= JavaModelUtil.getRenamedCUName(cu, currTypeName);
		ICompilationUnit newCU= ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
		if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
			RenameCompilationUnitChange change= new RenameCompilationUnitChange(cu, newCUName);

			// rename CU
			String label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, BasicElementLabels.getResourceName(newCUName));
			proposals.add(new ChangeCorrectionProposal(label, change, IProposalRelevance.RENAME_CU, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME)));
		}
	}
}
 
Example 20
Source File: PackageBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public IAnnotationBinding[] getAnnotations() {
	try {
		INameEnvironment nameEnvironment = this.binding.environment.nameEnvironment;
		if (!(nameEnvironment instanceof SearchableEnvironment))
			return AnnotationBinding.NoAnnotations;
		NameLookup nameLookup = ((SearchableEnvironment) nameEnvironment).nameLookup;
		if (nameLookup == null)
			return AnnotationBinding.NoAnnotations;
		final String pkgName = getName();
		IPackageFragment[] pkgs = nameLookup.findPackageFragments(pkgName, false/*exact match*/);
		if (pkgs == null)
			return AnnotationBinding.NoAnnotations;

		for (int i = 0, len = pkgs.length; i < len; i++) {
			int fragType = pkgs[i].getKind();
			switch(fragType) {
				case IPackageFragmentRoot.K_SOURCE:
					String unitName = "package-info.java"; //$NON-NLS-1$
					ICompilationUnit unit = pkgs[i].getCompilationUnit(unitName);
					if (unit != null && unit.exists()) {
						ASTParser p = ASTParser.newParser(AST.JLS3_INTERNAL);
						p.setSource(unit);
						p.setResolveBindings(true);
						p.setUnitName(unitName);
						p.setFocalPosition(0);
						p.setKind(ASTParser.K_COMPILATION_UNIT);
						CompilationUnit domUnit = (CompilationUnit) p.createAST(null);
						PackageDeclaration pkgDecl = domUnit.getPackage();
						if (pkgDecl != null) {
							List annos = pkgDecl.annotations();
							if (annos == null || annos.isEmpty())
								return AnnotationBinding.NoAnnotations;
							IAnnotationBinding[] result = new IAnnotationBinding[annos.size()];
							int index=0;
	 						for (Iterator it = annos.iterator(); it.hasNext(); index++) {
								result[index] = ((Annotation) it.next()).resolveAnnotationBinding();
								// not resolving bindings
								if (result[index] == null)
									return AnnotationBinding.NoAnnotations;
							}
							return result;
						}
					}
					break;
				case IPackageFragmentRoot.K_BINARY:
					NameEnvironmentAnswer answer =
						nameEnvironment.findType(TypeConstants.PACKAGE_INFO_NAME, this.binding.compoundName);
					if (answer != null && answer.isBinaryType()) {
						IBinaryType type = answer.getBinaryType();
						char[][][] missingTypeNames = type.getMissingTypeNames();
						IBinaryAnnotation[] binaryAnnotations = type.getAnnotations();
						org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding[] binaryInstances =
							BinaryTypeBinding.createAnnotations(binaryAnnotations, this.binding.environment, missingTypeNames);
						org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding[] allInstances =
							org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding.addStandardAnnotations(binaryInstances, type.getTagBits(), this.binding.environment);
						int total = allInstances.length;
						IAnnotationBinding[] domInstances = new AnnotationBinding[total];
						for (int a = 0; a < total; a++) {
							final IAnnotationBinding annotationInstance = this.resolver.getAnnotationInstance(allInstances[a]);
							if (annotationInstance == null) {// not resolving binding
								return AnnotationBinding.NoAnnotations;
							}
							domInstances[a] = annotationInstance;
						}
						return domInstances;
					}
			}
		}
	} catch(JavaModelException e) {
		return AnnotationBinding.NoAnnotations;
	}
	return AnnotationBinding.NoAnnotations;
}