Java 类org.eclipse.jdt.core.IJavaElement 实例源码

项目:ContentAssist    文件:ResourceMacro.java   
/**
 * Returns the target of this resource change.
 * @param elem the changed element
 * @return the target of the change, or an empty string if the target is not either a project, package, or file
 */
private String getTarget(IJavaElement elem) {
    if (elem == null) {
        return "";
    }

    int type = elem.getElementType();
    if (type == IJavaElement.JAVA_PROJECT) {
        return "Project";

    } else if (type == IJavaElement.PACKAGE_DECLARATION) {
        return "Package";

    } else if (type == IJavaElement.COMPILATION_UNIT) {
        return "File";
    }

    return elem.getElementName() + "@" + elem.getElementType();
}
项目:ContentAssist    文件:ResourceMacro.java   
/**
 * Obtains the name of the specified element.
 * @param elem the element
 * @param type the type of the element
 * @return the name string
 */
public static String getName(IJavaElement elem) {
    int type = elem.getElementType();
    if (type == IJavaElement.JAVA_PROJECT) {
        return elem.getResource().getName();

    } else if (type == IJavaElement.PACKAGE_DECLARATION) {
        IPackageFragment jpackage = (IPackageFragment)elem;
        return jpackage.getElementName();

    } else if (type == IJavaElement.COMPILATION_UNIT) {
        return elem.getResource().getName();
    }

    return "";
}
项目:ContentAssist    文件:ResourceChangedManager.java   
/**
 * Creates a macro corresponding to the removed delta of the change.
 * @param time the time when the change occurred
 * @param delta the removed delta of the change
 * @return the created resource macro
 */
private ResourceMacro createResourceRemovedMacro(long time, IJavaElementDelta delta) {
    IJavaElement elem = delta.getElement();
    String path = elem.getPath().toString();
    if (path == null) {
        return null;
    }

    String type = "Removed";
    if ((delta.getFlags() & IJavaElementDelta.F_MOVED_TO) != 0) {
        if (isRenamed(delta.getElement(), delta.getMovedToElement())) {
            type = "RenamedTo";
        } else {
            type = "MovedTo";
        }
    }

    return new ResourceMacro(time, type, path, elem);
}
项目:ContentAssist    文件:ResourceChangedManager.java   
/**
 * Creates a macro corresponding to the added delta of the change.
 * @param time the time when the change occurred
 * @param delta the added delta of the change
 * @return the created resource macro
 */
private ResourceMacro createResourceAddedMacro(long time, IJavaElementDelta delta) {
    IJavaElement elem = delta.getElement();
    String path = elem.getPath().toString();
    if (path == null) {
        return null;
    }

    String type = "Added";
    if ((delta.getFlags() & IJavaElementDelta.F_MOVED_FROM) != 0) {
        if (isRenamed(delta.getElement(), delta.getMovedFromElement())) {
            type = "RenamedFrom";
        } else {
            type = "MovedFrom";
        }
    }

    return new ResourceMacro(time, type, path, elem);
}
项目:codelens-eclipse    文件:JDTUtils.java   
public static boolean isHiddenGeneratedElement(IJavaElement element) {
    // generated elements are tagged with javax.annotation.Generated and
    // they need to be filtered out
    if (element instanceof IAnnotatable) {
        try {
            IAnnotation[] annotations = ((IAnnotatable) element).getAnnotations();
            if (annotations.length != 0) {
                for (IAnnotation annotation : annotations) {
                    if (isSilencedGeneratedAnnotation(annotation)) {
                        return true;
                    }
                }
            }
        } catch (JavaModelException e) {
            // ignore
        }
    }
    return false;
}
项目:Equella    文件:NewPluginWizard.java   
@Override
public boolean performFinish()
{
    boolean res = super.performFinish();
    if( res )
    {
        final IJavaElement newElement = getCreatedElement();

        IWorkingSet[] workingSets = fFirstPage.getWorkingSets();
        if( workingSets.length > 0 )
        {
            PlatformUI.getWorkbench().getWorkingSetManager().addToWorkingSets(newElement, workingSets);
        }
        BasicNewResourceWizard.selectAndReveal(fSecondPage.getJavaProject().getProject(), getWorkbench()
            .getActiveWorkbenchWindow());
    }
    return res;
}
项目:Equella    文件:NewRegistryWizard.java   
@Override
public boolean performFinish()
{
    boolean res = super.performFinish();
    if( res )
    {
        final IJavaElement newElement = getCreatedElement();

        IWorkingSet[] workingSets = fFirstPage.getWorkingSets();
        if( workingSets.length > 0 )
        {
            PlatformUI.getWorkbench().getWorkingSetManager().addToWorkingSets(newElement, workingSets);
        }
        BasicNewResourceWizard.selectAndReveal(fSecondPage.getJavaProject().getProject(), getWorkbench()
            .getActiveWorkbenchWindow());
    }
    return res;
}
项目:Hydrograph    文件:ClassDetails.java   
public ClassDetails(IClassFile classFile, String jarFileName, String packageName, boolean isUserDefined) {
    LOGGER.debug("Extracting methods from "+classFile.getElementName());

    try {
        this.javaDoc=getJavaDoc(classFile); 
        intialize(classFile,jarFileName,packageName, isUserDefined);
        for (IJavaElement iJavaElement : classFile.getChildren()) {
            if (iJavaElement instanceof IType) {
                IType iType = (IType) iJavaElement;
                for (IMethod iMethod : iType.getMethods()) {
                    addMethodsToClass(iMethod);
                }
            }
        }
    } catch (JavaModelException e) {
        LOGGER.error("Error occurred while fetching methods from class"+cName);
    }
}
项目:Hydrograph    文件:ClassDetails.java   
public ClassDetails(SourceType javaClassFile, String jarFileName, String packageName, boolean isUserDefined) {
    Logger LOGGER = LogFactory.INSTANCE.getLogger(ClassDetails.class);
    LOGGER.debug("Extracting methods from " + cName);

    try {
        this.javaDoc=getJavaDoc(javaClassFile);         
        intialize(javaClassFile, jarFileName, packageName, isUserDefined);
        for (IJavaElement iJavaElement : javaClassFile.getChildren()) {
            if (iJavaElement instanceof SourceMethod) {
                addMethodsToClass((IMethod) iJavaElement);
            }
        }
    } catch (JavaModelException e) {
        LOGGER.error("Error occurred while fetching methods from class" + cName);
    }
}
项目:java-debug    文件:JdtSourceLookUpProvider.java   
private static IClassFile resolveClassFile(String uriString) {
    if (uriString == null || uriString.isEmpty()) {
        return null;
    }
    try {
        URI uri = new URI(uriString);
        if (uri != null && JDT_SCHEME.equals(uri.getScheme()) && "contents".equals(uri.getAuthority())) {
            String handleId = uri.getQuery();
            IJavaElement element = JavaCore.create(handleId);
            IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
            return cf;
        }
    } catch (URISyntaxException e) {
        // ignore
    }
    return null;
}
项目:java-debug    文件:JavaHotCodeReplaceProvider.java   
/**
 * Returns the source file associated with the given type, or <code>null</code>
 * if no source file could be found.
 *
 * @param project
 *            the java project containing the classfile
 * @param qualifiedName
 *            fully qualified name of the type, slash delimited
 * @param sourceAttribute
 *            debug source attribute, or <code>null</code> if none
 */
private IResource getSourceFile(IJavaProject project, String qualifiedName, String sourceAttribute) {
    String name = null;
    IJavaElement element = null;
    try {
        if (sourceAttribute == null) {
            element = findElement(qualifiedName, project);
        } else {
            int i = qualifiedName.lastIndexOf('/');
            if (i > 0) {
                name = qualifiedName.substring(0, i + 1);
                name = name + sourceAttribute;
            } else {
                name = sourceAttribute;
            }
            element = project.findElement(new Path(name));
        }
        if (element instanceof ICompilationUnit) {
            ICompilationUnit cu = (ICompilationUnit) element;
            return cu.getCorrespondingResource();
        }
    } catch (CoreException e) {
        logger.log(Level.INFO, "Failed to get source file with exception" + e.getMessage(), e);
    }
    return null;
}
项目:java-debug    文件:JavaHotCodeReplaceProvider.java   
/**
 * Returns the class file or compilation unit containing the given fully
 * qualified name in the specified project. All registered java like file
 * extensions are considered.
 *
 * @param qualifiedTypeName
 *            fully qualified type name
 * @param project
 *            project to search in
 * @return class file or compilation unit or <code>null</code>
 * @throws CoreException
 *             if an exception occurs
 */
public static IJavaElement findElement(String qualifiedTypeName, IJavaProject project) throws CoreException {
    String path = qualifiedTypeName;

    final String[] javaLikeExtensions = JavaCore.getJavaLikeExtensions();
    int pos = path.indexOf('$');
    if (pos != -1) {
        path = path.substring(0, pos);
    }
    path = path.replace('.', IPath.SEPARATOR);
    path += "."; //$NON-NLS-1$
    for (String ext : javaLikeExtensions) {
        IJavaElement element = project.findElement(new Path(path + ext));
        if (element != null) {
            return element;
        }
    }
    return null;
}
项目:eclipse.jdt.ls    文件:RefactoringASTParser.java   
/**
 * Returns the compiler options used for creating the refactoring AST.
 * <p>
 * Turns all errors, warnings and infos into ignore and disables task tags.
 * The customizable set of compiler options only contains additional Eclipse
 * options. The standard JDK compiler options can't be changed anyway.
 *
 * @param element
 *            an element (not the Java model)
 * @return compiler options
 */
public static Map<String, String> getCompilerOptions(IJavaElement element) {
    IJavaProject project = element.getJavaProject();
    Map<String, String> options = project.getOptions(true);
    for (Iterator<String> iter = options.keySet().iterator(); iter.hasNext();) {
        String key = iter.next();
        String value = options.get(key);
        if (JavaCore.ERROR.equals(value) || JavaCore.WARNING.equals(value) || JavaCore.INFO.equals(value)) {
            // System.out.println("Ignoring - " + key);
            options.put(key, JavaCore.IGNORE);
        }
    }
    options.put(JavaCore.COMPILER_PB_MAX_PER_UNIT, "0"); //$NON-NLS-1$
    options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
    return options;
}
项目:eclipse.jdt.ls    文件:NavigateToDefinitionHandler.java   
private Location computeDefinitionNavigation(ITypeRoot unit, int line, int column, IProgressMonitor monitor) {
    try {
        IJavaElement element = JDTUtils.findElementAtSelection(unit, line, column, this.preferenceManager, monitor);
        if (element == null) {
            return null;
        }
        ICompilationUnit compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
        IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
        if (compilationUnit != null || (cf != null && cf.getSourceRange() != null)  ) {
            return JDTUtils.toLocation(element);
        }
        if (element instanceof IMember && ((IMember) element).getClassFile() != null) {
            return JDTUtils.toLocation(((IMember) element).getClassFile());
        }
    } catch (JavaModelException e) {
        JavaLanguageServerPlugin.logException("Problem computing definition for" +  unit.getElementName(), e);
    }
    return null;
}
项目:eclipse.jdt.ls    文件:JavadocContentAccess.java   
/**
 * Gets a reader for an package fragment's Javadoc comment content from the source attachment.
 * The content does contain only the text from the comment without the Javadoc leading star characters.
 * Returns <code>null</code> if the package fragment does not contain a Javadoc comment or if no source is available.
 * @param fragment The package fragment to get the Javadoc of.
 * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member
 * does not contain a Javadoc comment or if no source is available
 * @throws JavaModelException is thrown when the package fragment's javadoc can not be accessed
 * @since 3.4
 */
private static Reader internalGetContentReader(IPackageFragment fragment) throws JavaModelException {
    IPackageFragmentRoot root= (IPackageFragmentRoot) fragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

    //1==> Handle the case when the documentation is present in package-info.java or package-info.class file
    boolean isBinary= root.getKind() == IPackageFragmentRoot.K_BINARY;
    ITypeRoot packageInfo;
    if (isBinary) {
        packageInfo= fragment.getClassFile(PACKAGE_INFO_CLASS);
    } else {
        packageInfo= fragment.getCompilationUnit(PACKAGE_INFO_JAVA);
    }
    if (packageInfo != null && packageInfo.exists()) {
        String source = packageInfo.getSource();
        //the source can be null for some of the class files
        if (source != null) {
            Javadoc javadocNode = getPackageJavadocNode(fragment, source);
            if (javadocNode != null) {
                int start = javadocNode.getStartPosition();
                int length = javadocNode.getLength();
                return new JavaDocCommentReader(source, start, start + length - 1);
            }
        }
    }
    return null;
}
项目:code    文件:OpenTypeAction.java   
@Override
    public void run() {
        ITypeBinding typeBinding = Crystal.getInstance().getTypeBindingFromName(fullyQualifiedName);
        if(typeBinding!=null){
            //get all types & names of fields & methods & class/interface
            IJavaElement javaElement = typeBinding.getJavaElement();
            if (javaElement != null && ASTUtils.isFromSource(typeBinding)) {
                try {
//                  EditorUtility.openInEditor(javaElement, true);
                    /*
                     * code above causes a bug that if several classes are in
                     * the same java file, always open the first one no matter
                     * which one the user chooses
                     */
                    JavaUI.openInEditor(javaElement);
//                  IEditorPart javaEditor = JavaUI.openInEditor(javaElement);
//                  JavaUI.revealInEditor(javaEditor, javaElement);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        super.run();
    }
项目:code    文件:TraceUtility.java   
public static void highlightInEditor(ASTNode enclosingDeclaration , ASTNode expressionNode){
    if(TraceToCodeUIAction.highlightCode){
        IJavaElement javaElement = getIJavaElement(enclosingDeclaration);
        if (javaElement != null) {
            try {

                EditorUtility.openInEditor(javaElement);
                IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
                if (part instanceof ITextEditor) {
                    ((ITextEditor) part).selectAndReveal(expressionNode.getStartPosition(), expressionNode.getLength());

                }
            } catch (PartInitException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
项目:libraries    文件:ListRunner.java   
public ListRunner(
  final ICanceler canceler,
  final ILogger logger,
  final IJavaElement[] selection,
  final IDependenciesModel dependenciesModel,
  final IObjectModel<IItem> selectedItemModel,
  final IObjectListModel<IItem> selectedItemsModel,
  final Label label,
  final IJavaModel model,
  final WritableList<IDependencyRelation> relations,
  final INameHitMaps nameHitMaps) {
  this.logger = logger;
  this.selection = selection;
  this.dependenciesModel = dependenciesModel;
  this.canceler = canceler;
  this.selectedItemModel = selectedItemModel;
  this.selectedItemsModel = selectedItemsModel;
  this.label = label;
  this.model = model;
  this.relations = relations;
  this.nameHitMaps = nameHitMaps;
}
项目:eclipse.jdt.ls    文件:GetterSetterCorrectionSubProcessor.java   
private static boolean isAvailable(IJavaElement javaElement) throws JavaModelException {
    if (javaElement == null) {
        return false;
    }
    if (!javaElement.exists()) {
        return false;
    }
    if (javaElement.isReadOnly()) {
        return false;
    }
    // work around for https://bugs.eclipse.org/bugs/show_bug.cgi?id=48422
    // the Java project is now cheating regarding its children so we shouldn't
    // call isStructureKnown if the project isn't open.
    // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=52474
    if (!(javaElement instanceof IJavaProject) && !(javaElement instanceof ILocalVariable) && !javaElement.isStructureKnown()) {
        return false;
    }
    if (javaElement instanceof IMember && ((IMember) javaElement).isBinary()) {
        return false;
    }
    return true;
}
项目:pde.source.lookup    文件:DownloadSourcesActionDelegate.java   
@Override
public void setActiveEditor(IAction action, IEditorPart part) {
  if (part != null && part.getEditorInput() instanceof IClassFileEditorInput) {
    Set<IPackageFragmentRoot> queue = new LinkedHashSet<>();
    try {
      IClassFileEditorInput input = (IClassFileEditorInput) part.getEditorInput();
      IJavaElement element = input.getClassFile();
      while (element.getParent() != null) {
        element = element.getParent();
        if (element instanceof IPackageFragmentRoot) {
          IPackageFragmentRoot fragment = (IPackageFragmentRoot) element;
          if (canProcess(fragment)) {
            queue.add(fragment);
          }
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    findSources(queue);
  }
}
项目:code    文件:TraceUtility.java   
public static IJavaElement getIJavaElement(ASTNode node){
    IJavaElement javaElement = null;
    // Find IJavaElement corresponding to the ASTNode
    if (node instanceof MethodDeclaration) {
        javaElement = ((MethodDeclaration) node).resolveBinding()
                .getJavaElement();
    } else if (node instanceof VariableDeclaration) {
        javaElement = ((VariableDeclaration) node).resolveBinding()
                .getJavaElement();
    }else if(node instanceof TypeDeclaration){
        javaElement = ((TypeDeclaration)node).resolveBinding()
                .getJavaElement();
    }else if(node instanceof ClassInstanceCreation){
        javaElement = ((ClassInstanceCreation)node).resolveConstructorBinding().getJavaElement();
    }

    return javaElement;
}
项目:eclemma    文件:TypeTraverser.java   
private void processType(ITypeVisitor visitor, BinaryTypeName btn,
    IType type, IProgressMonitor monitor) throws JavaModelException {
  final String binaryname = btn.toString();
  monitor.subTask(binaryname);
  visitor.visit(type, binaryname);
  for (final IJavaElement child : type.getChildren()) {
    if (monitor.isCanceled()) {
      break;
    }
    switch (child.getElementType()) {
    case IJavaElement.TYPE:
      IType nestedtype = (IType) child;
      processType(visitor, btn.nest(nestedtype), nestedtype, monitor);
      break;
    case IJavaElement.METHOD:
    case IJavaElement.INITIALIZER:
    case IJavaElement.FIELD:
      processAnonymousInnerTypes(visitor, btn, (IMember) child, monitor);
      break;
    }
  }
}
项目:eclemma    文件:JavaElementCoverageAdapterFactory.java   
public Object getAdapter(Object object,
    @SuppressWarnings("rawtypes") Class adapterType) {
  // if the object is a IResource find the corresponding IJavaElement
  if (object instanceof IResource) {
    object = ((IResource) object).getAdapter(IJavaElement.class);
    if (object == null) {
      return null;
    }
  }
  // then find the coverage information from the current session
  IJavaModelCoverage mc = CoverageTools.getJavaModelCoverage();
  if (mc == null) {
    return null;
  } else {
    ICoverageNode coverage = mc.getCoverageFor((IJavaElement) object);
    if (adapterType.isInstance(coverage)) {
      return coverage;
    } else {
      return null;
    }
  }
}
项目:google-cloud-eclipse    文件:ClasspathPipelineOptionsHierarchyFactory.java   
@Override
public PipelineOptionsHierarchy forProject(
    IProject project, MajorVersion version, IProgressMonitor monitor)
    throws PipelineOptionsRetrievalException {
  IJavaElement javaElement = project.getAdapter(IJavaElement.class);
  checkNotNull(
      javaElement,
      "%s cannot be created for a non-java project: %s",
      JavaProjectPipelineOptionsHierarchy.class.getSimpleName(),
      project);
  try {
    IJavaProject javaProject = javaElement.getJavaProject();
    IType rootType = javaProject.findType(PipelineOptionsNamespaces.rootType(version));
    if (rootType == null || !rootType.exists()) {
      return global(monitor);
    }
    return new JavaProjectPipelineOptionsHierarchy(javaProject, version, monitor);
  } catch (JavaModelException e) {
    DataflowCorePlugin.logError(e,
        "Error while constructing Pipeline Options Hierarchy for project %s", project.getName());
    throw new PipelineOptionsRetrievalException(e);
  }
}
项目:o3smeasures-tool    文件:NumberOfChildrenJavaModel.java   
/**
 * @see IJavaModel#calculateValue
 */
@Override
public void calculateValue(ICompilationUnit unit) {

    try {
        int length = 0;

        IType[] types = unit.getAllTypes();
        for (IType type : types) {
            ITypeHierarchy th= type.newTypeHierarchy((IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT), null);

            if (th != null) subtypesList = th.getAllSubtypes(type);

            if (subtypesList != null) length = subtypesList.length;

            Double value = new BigDecimal(length, new MathContext(2, RoundingMode.UP)).doubleValue();
            setNocValue(value);
        }

    }catch (JavaModelException exception1) {
        logger.error(exception1);
    }catch (NullPointerException exception2){
        logger.error(exception2);
    }
}
项目:wildfly-hive    文件:ClasspathChangeListener.java   
private void visit(IJavaElementDelta delta) {
    IJavaElement el = delta.getElement();
    switch (el.getElementType()) {
    case IJavaElement.JAVA_MODEL:
        for (IJavaElementDelta c : delta.getAffectedChildren()) {
            visit(c);
        }
        break;
    case IJavaElement.JAVA_PROJECT:
        IJavaProject javaProject = (IJavaProject) el;
        if (isClasspathChanged(delta)) {
            detectionJob.analyze(javaProject);
        }
        break;
    default:
        break;
    }
}
项目:Sparrow    文件:OutCodeVisitor.java   
@Override
public boolean visit(SimpleName node) {
    if (currentMethod == null)
        return false;
    IBinding binding = node.resolveBinding();
    if (binding == null)
        return false;
    if (node.isDeclaration())
        return true;
    if (node.resolveBinding() instanceof IVariableBinding) {
        IVariableBinding iVariableBinding = (IVariableBinding) node.resolveBinding();
        if (iVariableBinding.isField()) {
            IVariableBinding variableDeclarationBinding = iVariableBinding.getVariableDeclaration();
            if (variableDeclarationBinding.getDeclaringClass() != null) {
                IJavaElement accessedField = variableDeclarationBinding.getJavaElement();
                if (accessedField instanceof IField) {
                    if (!((IField) accessedField).isReadOnly())
                        methodDetails.addAccess((IField) accessedField);
                }
            }
        }
    }
    return true;
}
项目:code    文件:ASTUtils.java   
public static MethodDeclaration getMethodDeclaration(String methodName) {
    IJavaElement javaElem = EditorUtility.getActiveEditorJavaInput();
    if (javaElem.getElementType() == IJavaElement.COMPILATION_UNIT) {
        ICompilationUnit iCompUnit = (ICompilationUnit) javaElem;
        ASTNode astNode = Crystal.getInstance()
                .getASTNodeFromCompilationUnit(iCompUnit);
        if (astNode != null
                && astNode.getNodeType() == ASTNode.COMPILATION_UNIT) {
            CompilationUnit compUnit = (CompilationUnit) astNode;
            for (Object declaration : compUnit.types()) {
                if (declaration instanceof TypeDeclaration) {
                    for (MethodDeclaration method : ((TypeDeclaration) declaration)
                            .getMethods()) {
                        if (methodName.contentEquals(method.getName()
                                .getFullyQualifiedName())) {
                            return method;
                        }
                    }
                }
            }
        }
    }
    return null;
}
项目:eclipse.jdt.ls    文件:JDTUtils.java   
/**
 * Given the uri returns a {@link ICompilationUnit}.
 * May return null if it can not associate the uri with a Java
 * file.
 *
 * @param uriString
 * @return compilation unit
 */
public static ICompilationUnit resolveCompilationUnit(URI uri) {
    if (uri == null || JDT_SCHEME.equals(uri.getScheme()) || !uri.isAbsolute()){
        return null;
    }

    IFile resource = (IFile) findResource(uri, ResourcesPlugin.getWorkspace().getRoot()::findFilesForLocationURI);
    if(resource != null){
        if(!ProjectUtils.isJavaProject(resource.getProject())){
            return null;
        }
        IJavaElement element = JavaCore.create(resource);
        if (element instanceof ICompilationUnit) {
            return (ICompilationUnit)element;
        }
    }
    if (resource == null) {
        return getFakeCompilationUnit(uri, new NullProgressMonitor());
    }
    //the resource is not null but no compilation unit could be created (eg. project not ready yet)
    return null;
}
项目:eclipse.jdt.ls    文件:JDTUtils.java   
/**
 * Given the uri returns a {@link IPackageFragment}. May return null if it can
 * not associate the uri with a package fragment.
 *
 * @param uriString
 * @return package fragment
 */
public static IPackageFragment resolvePackage(URI uri) {
    if (uri == null || JDT_SCHEME.equals(uri.getScheme()) || !uri.isAbsolute()) {
        return null;
    }

    IFolder resource = (IFolder) findResource(uri, ResourcesPlugin.getWorkspace().getRoot()::findContainersForLocationURI);
    if (resource != null) {
        if (!ProjectUtils.isJavaProject(resource.getProject())) {
            return null;
        }
        IJavaElement element = JavaCore.create(resource);
        if (element instanceof IPackageFragment) {
            return (IPackageFragment) element;
        }
    }
    return null;
}
项目:eclipse.jdt.ls    文件:JDTUtils.java   
private static ISourceRange getNameRange(IJavaElement element) throws JavaModelException {
    ISourceRange nameRange = null;
    if (element instanceof IMember) {
        IMember member = (IMember) element;
        nameRange = member.getNameRange();
        if ( (!SourceRange.isAvailable(nameRange))) {
            nameRange = member.getSourceRange();
        }
    } else if (element instanceof ITypeParameter || element instanceof ILocalVariable) {
        nameRange = ((ISourceReference) element).getNameRange();
    } else if (element instanceof ISourceReference) {
        nameRange = ((ISourceReference) element).getSourceRange();
    }
    if (!SourceRange.isAvailable(nameRange) && element.getParent() != null) {
        nameRange = getNameRange(element.getParent());
    }
    return nameRange;
}
项目:eclipse.jdt.ls    文件:JDTUtils.java   
public static boolean isHiddenGeneratedElement(IJavaElement element) {
    // generated elements are tagged with javax.annotation.Generated and
    // they need to be filtered out
    if (element instanceof IAnnotatable) {
        try {
            IAnnotation[] annotations = ((IAnnotatable) element).getAnnotations();
            if (annotations.length != 0) {
                for (IAnnotation annotation : annotations) {
                    if (isSilencedGeneratedAnnotation(annotation)) {
                        return true;
                    }
                }
            }
        } catch (JavaModelException e) {
            //ignore
        }
    }
    return false;
}
项目:Sparrow    文件:OutCodeVisitor.java   
@Override
public boolean visit(MethodDeclaration methodDeclaration) {
    IBinding binding = methodDeclaration.resolveBinding();
    if (binding == null)
        return false;
    currentMethod = (IMethod) binding.getJavaElement();
    if (currentMethod != null) {
        methodDetails = new MethodDetails();
        String handleIdentifier = currentMethod.getHandleIdentifier();
        allDetails.put(handleIdentifier, methodDetails);
        methodDetails.setModifiers(methodDeclaration.getModifiers());
        methodDetails.setParameters(getParameters(methodDeclaration.parameters()));
        Type returnType2 = methodDeclaration.getReturnType2();
        if (returnType2 != null) {
            ITypeBinding typeBinding = returnType2.resolveBinding();
            IJavaElement returnType = typeBinding.getJavaElement();
            if (returnType instanceof IType) {
                methodDetails.setReturnType((IType) returnType);
            }
        }
    }
    return true;
}
项目:eclipse.jdt.ls    文件:RedundantNullnessTypeAnnotationsFilter.java   
public static /* @Nullable */ RedundantNullnessTypeAnnotationsFilter createIfConfigured(/* @Nullable */ ASTNode node) {
    if (node == null) {
        return null;
    }
    final ASTNode root= node.getRoot();
    if (root instanceof CompilationUnit) {
        CompilationUnit compilationUnit= (CompilationUnit) root;
        IJavaElement javaElement= compilationUnit.getJavaElement();
        IJavaProject javaProject= javaElement == null ? null : javaElement.getJavaProject();
        if (javaProject != null) {
            if (JavaCore.ENABLED.equals(javaProject.getOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, true))) {
                String nonNullAnnotationName= javaProject.getOption(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, true);
                String nullableAnnotationName= javaProject.getOption(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, true);
                String nonNullByDefaultName= javaProject.getOption(JavaCore.COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME, true);
                if (nonNullAnnotationName == null || nullableAnnotationName == null || nonNullByDefaultName == null) {
                    return null;
                }
                EnumSet<TypeLocation> nonNullByDefaultLocations= determineNonNullByDefaultLocations(node, nonNullByDefaultName);
                return new RedundantNullnessTypeAnnotationsFilter(nonNullAnnotationName, nullableAnnotationName, nonNullByDefaultLocations);
            }
        }
    }
    return null;
}
项目:eclipse.jdt.ls    文件:StubUtility2.java   
/**
 * Evaluates the insertion position of a new node.
 *
 * @param listRewrite The list rewriter to which the new node will be added
 * @param sibling The Java element before which the new element should be added.
 * @return the AST node of the list to insert before or null to insert as last.
 * @throws JavaModelException thrown if accessing the Java element failed
 */

public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElement sibling) throws JavaModelException {
    if (sibling instanceof IMember) {
        ISourceRange sourceRange= ((IMember) sibling).getSourceRange();
        if (sourceRange == null) {
            return null;
        }
        int insertPos= sourceRange.getOffset();

        List<? extends ASTNode> members= listRewrite.getOriginalList();
        for (int i= 0; i < members.size(); i++) {
            ASTNode curr= members.get(i);
            if (curr.getStartPosition() >= insertPos) {
                return curr;
            }
        }
    }
    return null;
}
项目:eclipse.jdt.ls    文件:StubUtility.java   
private static String[] getParameterTypeNamesForSeeTag(IMethod overridden) {
    try {
        ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
        parser.setProject(overridden.getJavaProject());
        IBinding[] bindings = parser.createBindings(new IJavaElement[] { overridden }, null);
        if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) {
            return getParameterTypeNamesForSeeTag((IMethodBinding) bindings[0]);
        }
    } catch (IllegalStateException e) {
        // method does not exist
    }
    // fall back code. Not good for generic methods!
    String[] paramTypes = overridden.getParameterTypes();
    String[] paramTypeNames = new String[paramTypes.length];
    for (int i = 0; i < paramTypes.length; i++) {
        paramTypeNames[i] = Signature.toString(Signature.getTypeErasure(paramTypes[i]));
    }
    return paramTypeNames;
}
项目:eclipse.jdt.ls    文件:RenameProcessor.java   
protected SearchPattern createOccurrenceSearchPattern(IJavaElement[] elements) throws CoreException {
    if (elements == null || elements.length == 0) {
        return null;
    }
    Set<IJavaElement> set = new HashSet<>(Arrays.asList(elements));
    Iterator<IJavaElement> iter = set.iterator();
    IJavaElement first = iter.next();
    SearchPattern pattern = SearchPattern.createPattern(first, IJavaSearchConstants.ALL_OCCURRENCES);
    if (pattern == null) {
        throw new CoreException(Status.CANCEL_STATUS);
    }
    while (iter.hasNext()) {
        IJavaElement each = iter.next();
        SearchPattern nextPattern = SearchPattern.createPattern(each, IJavaSearchConstants.ALL_OCCURRENCES);
        if (nextPattern == null) {
            throw new CoreException(Status.CANCEL_STATUS);
        }
        pattern = SearchPattern.createOrPattern(pattern, nextPattern);
    }
    return pattern;
}
项目:ContentAssist    文件:ResourceMacro.java   
/**
 * Creates an object storing information on an resource change macro.
 * @param time the time when the macro started
 * @param type the type of the change
 * @param path the path of the changed resource
 * @param elem the changed resource
 */
public ResourceMacro(long time, String type, String path, IJavaElement elem) {
    super(time, time, type, path);
    this.target = getTarget(elem);
    this.identicalPath = getIdenticalPath(elem);
    this.code = getCode(elem);
    this.encoding = getEncoding(elem);
}
项目:ContentAssist    文件:ResourceMacro.java   
/**
 * 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 "";
}
项目:ContentAssist    文件:ResourceMacro.java   
/**
 * Returns the encoding of the changed source code.
 * @param elem the changed resource
 * @return the encoding of the source code, or <code>null</code>
 */
private String getEncoding(IJavaElement elem) {
    if (elem instanceof ICompilationUnit) {
        ICompilationUnit cu = (ICompilationUnit)elem;

        try {
            IFile file = (IFile)cu.getCorrespondingResource();
            return file.getCharset();
        } catch (CoreException e) {
        }
    }
    return null;
}