Example usage for org.eclipse.jdt.core IJavaElement getElementName

List of usage examples for org.eclipse.jdt.core IJavaElement getElementName

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement getElementName.

Prototype

String getElementName();

Source Link

Document

Returns the name of this element.

Usage

From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.AJSerialVersionHashOperation.java

License:Open Source License

/**
 * The original version of this method used the JDT state
 * object to find the class file of the type, but in 
 * AspectJ projects, there is no State object.
 * //w  ww .j a v  a2s  . co  m
 * Instead use the IOutputLocationManager for the project
 * 
 * Note that this will not work when the type is anonymous or it is
 * a named type inside a method declaration
 */
private static IFile getClassfile(ITypeBinding typeBinding) throws CoreException {
    IType type = (IType) typeBinding.getJavaElement();

    // get the output location manager
    IProject project = typeBinding.getJavaElement().getJavaProject().getProject();
    AjCompiler compiler = AspectJPlugin.getDefault().getCompilerFactory().getCompilerForProject(project);
    IOutputLocationManager manager = compiler.getCompilerConfiguration().getOutputLocationManager();
    if (!(manager instanceof CoreOutputLocationManager)) {
        return null;
    }
    CoreOutputLocationManager coreManager = (CoreOutputLocationManager) manager;

    // get the binary folder
    ICompilationUnit cu = type.getCompilationUnit();
    File file = new File(cu.getResource().getLocation().toOSString());
    File outLocation = coreManager.getOutputLocationForResource(file);

    // convert to IFolder
    IPath outPath = new Path(outLocation.getPath());
    IPath projPath = project.getLocation();
    if (projPath.isPrefixOf(outPath)) {
        outPath = outPath.removeFirstSegments(projPath.segmentCount());
    }
    IFolder outFolder = project.getFolder(outPath);
    if (!outFolder.exists()) {
        return null;
    }

    // get the package path
    IPackageFragment frag = type.getPackageFragment();
    String packageName = frag.getElementName();
    IPath packagePath = new Path(packageName.replace('.', '/'));
    IFolder packageFolder = outFolder.getFolder(packagePath);
    if (!packageFolder.exists()) {
        return null;
    }

    // determine the binary name of this type
    StringBuffer binaryName = new StringBuffer();
    IJavaElement enclosing = type.getParent();
    while (enclosing != null && !(enclosing instanceof ICompilationUnit)) {
        binaryName.append(enclosing.getElementName() + "$");
        enclosing = enclosing.getParent();
    }
    binaryName.append(type.getElementName() + ".class");
    IFile classFile = packageFolder.getFile(new Path(binaryName.toString()));
    if (classFile.exists()) {
        return classFile;
    } else {
        return null;
    }
}

From source file:org.eclipse.ajdt.internal.ui.markers.UpdateAJMarkers.java

License:Open Source License

private void addMarkersForFiles(IProgressMonitor monitor) {
    SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, sourceFiles.length);
    for (int i = 0; i < sourceFiles.length; i++) {
        IJavaElement unit = JavaCore.create(sourceFiles[i]);
        if (unit != null && unit.exists() && unit instanceof ICompilationUnit) {
            subMonitor.subTask("Add markers for " + unit.getElementName());
            addMarkersForFile((ICompilationUnit) unit, sourceFiles[i]);
            fileCount++;//  www .  j  a v a 2 s  . co  m
        }
        if (subMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        subMonitor.worked(1);
    }
}

From source file:org.eclipse.ajdt.internal.ui.visualiser.AJDTMarkupProvider.java

License:Open Source License

private void updateModel() {
    if (ProviderManager.getContentProvider() instanceof AJDTContentProvider) {
        IJavaProject jp = ((AJDTContentProvider) ProviderManager.getContentProvider()).getCurrentProject();
        if (jp != null) {
            AJProjectModelFacade model = AJProjectModelFactory.getInstance()
                    .getModelForProject(jp.getProject());

            Collection<IRelationship> allRelationships = model
                    .getRelationshipsForProject(new AJRelationshipType[] { AJRelationshipManager.ADVISED_BY,
                            AJRelationshipManager.ANNOTATED_BY, AJRelationshipManager.ASPECT_DECLARATIONS,
                            AJRelationshipManager.MATCHES_DECLARE });
            if (allRelationships != null) {
                for (IRelationship relationship : allRelationships) {
                    List<IMarkupKind> kinds = new ArrayList<IMarkupKind>();
                    IProgramElement sourceIpe = model.getProgramElement(relationship.getSourceHandle());
                    if (sourceIpe != null) {
                        List<String> targets = relationship.getTargets();
                        for (String targetStr : targets) {
                            IJavaElement target = model.programElementToJavaElement(targetStr);
                            String simpleName;
                            String qualifiedName;

                            if (!(target instanceof IAJCodeElement)) {
                                IJavaElement enclosingType = target.getAncestor(IJavaElement.TYPE);
                                if (enclosingType == null) {
                                    // Bug 324706  I don't know why the sloc is null.  Log the bug and
                                    // continue on.
                                    VisualiserPlugin.log(IStatus.WARNING,
                                            "Bug 324706: null containing type found for "
                                                    + target.getElementName() + "\nHandle identifier is: "
                                                    + target.getHandleIdentifier());
                                    // avoid an npe
                                    continue;
                                }/*from  w  w  w . j  a  v  a2  s. c  o  m*/

                                simpleName = enclosingType.getElementName();
                                qualifiedName = ((IType) enclosingType).getFullyQualifiedName('.');

                            } else { // It's an injar aspect so we wno't be able to find the parents
                                qualifiedName = target.getElementName();
                                String[] parts = qualifiedName.split(" "); //$NON-NLS-1$
                                String aNameWithExtension = parts[parts.length - 1];
                                if (aNameWithExtension.indexOf('.') != -1) { // $NON-NLS-1$
                                    simpleName = aNameWithExtension.substring(0,
                                            aNameWithExtension.lastIndexOf('.')); // $NON-NLS-1$
                                } else {
                                    simpleName = aNameWithExtension;
                                }
                            }

                            if (sourceIpe.getSourceLocation() == null) {
                                // Bug 324706  I don't know why the sloc is null.  Log the bug and
                                // continue on.
                                VisualiserPlugin.log(IStatus.WARNING,
                                        "Bug 324706: Warning, null source location found in "
                                                + sourceIpe.getName() + "\nHandle identifier is: "
                                                + sourceIpe.getHandleIdentifier());
                                // avoid an npe
                                continue;
                            }

                            int lineNum = sourceIpe.getSourceLocation().getLine();
                            IJavaElement sourceJe = model
                                    .programElementToJavaElement(relationship.getSourceHandle());
                            if (sourceJe != null) {
                                IJavaElement compilationUnitAncestor = sourceJe
                                        .getAncestor(IJavaElement.COMPILATION_UNIT);
                                if (compilationUnitAncestor != null) {
                                    String memberName = compilationUnitAncestor.getElementName();
                                    memberName = memberName.substring(0, memberName.lastIndexOf(".")); //$NON-NLS-1$
                                    String packageName = sourceJe.getAncestor(IJavaElement.PACKAGE_FRAGMENT)
                                            .getElementName();
                                    if (!(packageName.equals(""))) { //$NON-NLS-1$
                                        memberName = packageName + "." + memberName; //$NON-NLS-1$
                                    }
                                    IMarkupKind markupKind = null;
                                    if (kindMap == null) {
                                        kindMap = new HashMap<String, IMarkupKind>();
                                    }
                                    if (relationship.getName()
                                            .equals(AJRelationshipManager.MATCHES_DECLARE.getDisplayName())) {
                                        String sourceName = target.getElementName();
                                        boolean errorKind = sourceName.startsWith(aspectJErrorKind);
                                        if (kindMap.get(
                                                sourceName + ":::" + qualifiedName) instanceof IMarkupKind) { //$NON-NLS-1$
                                            markupKind = kindMap.get(sourceName + ":::" + qualifiedName); //$NON-NLS-1$
                                        } else {
                                            markupKind = new ErrorOrWarningMarkupKind(
                                                    sourceName + ":::" + simpleName, errorKind); //$NON-NLS-1$
                                            kindMap.put(sourceName + ":::" + qualifiedName, markupKind); //$NON-NLS-1$
                                        }
                                    } else {
                                        if (kindMap.get(qualifiedName) instanceof IMarkupKind) {
                                            markupKind = kindMap.get(qualifiedName);
                                        } else {
                                            markupKind = new SimpleMarkupKind(simpleName, qualifiedName);
                                            kindMap.put(qualifiedName, markupKind);
                                        }
                                    }
                                    kinds.add(markupKind);
                                    Stripe stripe = new Stripe(kinds, lineNum, 1);
                                    addMarkup(memberName, stripe);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    processMarkups();
}

From source file:org.eclipse.ajdt.internal.ui.wizards.exports.AJJarFileExportOperation.java

License:Open Source License

/**
 * Exports the passed resource to the JAR file
 *
 * @param element the resource or JavaElement to export
 *//*from  w ww  .ja  v  a 2s .co  m*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
    // AspectJ Change Begin
    if (!AspectJPlugin.USING_CU_PROVIDER) {
        // Don't export AJCompilationUnits because they are duplicates of files that we also export.
        if (element instanceof AJCompilationUnit) {
            return;
        }
    }
    // AspectJ Change End
    int leadSegmentsToRemove = 1;
    IPackageFragmentRoot pkgRoot = null;
    boolean isInJavaProject = false;
    IResource resource = null;
    IJavaProject jProject = null;
    if (element instanceof IJavaElement) {
        isInJavaProject = true;
        IJavaElement je = (IJavaElement) element;
        int type = je.getElementType();
        if (type != IJavaElement.CLASS_FILE && type != IJavaElement.COMPILATION_UNIT) {
            exportJavaElement(progressMonitor, je);
            return;
        }
        try {
            resource = je.getUnderlyingResource();
        } catch (JavaModelException ex) {
            addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_resourceNotFound,
                    je.getElementName()), ex);
            return;
        }
        jProject = je.getJavaProject();
        pkgRoot = JavaModelUtil.getPackageFragmentRoot(je);
    } else
        resource = (IResource) element;

    if (!resource.isAccessible()) {
        addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_resourceNotFound,
                resource.getFullPath()), null);
        return;
    }

    if (resource.getType() == IResource.FILE) {
        if (!isInJavaProject) {
            // check if it's a Java resource
            try {
                isInJavaProject = resource.getProject().hasNature(JavaCore.NATURE_ID);
            } catch (CoreException ex) {
                addWarning(
                        Messages.format(JarPackagerMessages.JarFileExportOperation_projectNatureNotDeterminable,
                                resource.getFullPath()),
                        ex);
                return;
            }
            if (isInJavaProject) {
                jProject = JavaCore.create(resource.getProject());
                try {
                    IPackageFragment pkgFragment = jProject
                            .findPackageFragment(resource.getFullPath().removeLastSegments(1));
                    if (pkgFragment != null)
                        pkgRoot = JavaModelUtil.getPackageFragmentRoot(pkgFragment);
                    else
                        pkgRoot = findPackageFragmentRoot(jProject,
                                resource.getFullPath().removeLastSegments(1));
                } catch (JavaModelException ex) {
                    addWarning(Messages.format(
                            JarPackagerMessages.JarFileExportOperation_javaPackageNotDeterminable,
                            resource.getFullPath()), ex);
                    return;
                }
            }
        }

        if (pkgRoot != null && jProject != null) {
            leadSegmentsToRemove = pkgRoot.getPath().segmentCount();
            boolean isOnBuildPath;
            isOnBuildPath = jProject.isOnClasspath(resource);
            if (!isOnBuildPath || (mustUseSourceFolderHierarchy()
                    && !pkgRoot.getElementName().equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)))
                leadSegmentsToRemove--;
        }

        IPath destinationPath = resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);

        boolean isInOutputFolder = false;
        if (isInJavaProject && jProject != null) {
            try {
                isInOutputFolder = jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
            } catch (JavaModelException ex) {
                isInOutputFolder = false;
            }
        }

        exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
        exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);

        progressMonitor.worked(1);
        ModalContext.checkCanceled(progressMonitor);

    } else
        exportContainer(progressMonitor, (IContainer) resource);
}

From source file:org.eclipse.ajdt.ui.tests.xref.XReferenceViewContentsTest.java

License:Open Source License

/**
 * Test for bug 111189 - the xrefs not being added to the
 * tree if there is advice on methods inside inner classes.
 *//*from   ww  w . j  a  v  a  2  s  .  c o m*/
public void testBug111189() throws CoreException {
    IProject project = createPredefinedProject("bug111189"); //$NON-NLS-1$
    waitForJobsToComplete();

    XReferenceContentProvider viewContentProvider = new XReferenceContentProvider();

    AJProjectModelFacade model = AJProjectModelFactory.getInstance().getModelForProject(project);
    waitForJobsToComplete();

    AJRelationshipType[] rels = new AJRelationshipType[] { AJRelationshipManager.MATCHES_DECLARE,
            AJRelationshipManager.MATCHED_BY };

    List/*IRelationship*/ listOfRels = model.getRelationshipsForProject(rels);
    assertTrue("there should be some relationships", !listOfRels.isEmpty()); //$NON-NLS-1$

    IJavaProject jProject = JavaCore.create(project);
    IJavaElement source = jProject.findType("pack.Test");

    XReferenceAdapter xra = new XReferenceAdapter(source);
    viewContentProvider.inputChanged(null, null, xra);
    Object[] elements = viewContentProvider.getElements(xra);
    assertEquals("There should be one source of xref", 1, elements.length); //$NON-NLS-1$
    assertEquals(source, ((TreeParent) elements[0]).getData());

    TreeParent testMethod = null;
    TreeParent innerClassC1 = null;

    Object[] children = viewContentProvider.getChildren(elements[0]);
    // if there aren't two children here then the recursion is 
    // wrong in the XReferenceContentProvider.addChildren(..) method
    // and this is a regression of bug 111189
    assertEquals("There should be two children", 2, children.length); //$NON-NLS-1$
    for (int i = 0; i < children.length; i++) {
        TreeParent t = (TreeParent) children[i];
        IJavaElement x = (IJavaElement) t.getData();
        if (x.getElementName().equals("testMethod")) { //$NON-NLS-1$
            testMethod = t;
        } else {
            innerClassC1 = t;
        }
    }

    // Check that all the children have been added to the testMethod node
    Object[] c1 = viewContentProvider.getChildren(testMethod);
    assertEquals("testMethod should have 1 child", 1, c1.length); //$NON-NLS-1$
    assertTrue("matches declare child should exist", ((IJavaElement) ((TreeObject) c1[0]).getData()).exists());
    Object[] c2 = viewContentProvider.getChildren(c1[0]);
    assertEquals("named innerclass C should have 1 child", 1, c2.length); //$NON-NLS-1$
    assertTrue("matches declare child should exist", ((IJavaElement) ((TreeObject) c2[0]).getData()).exists());
    Object[] c3 = viewContentProvider.getChildren(c2[0]);
    assertEquals("method m() of named innerclass C should have 1 child", 1, c3.length); //$NON-NLS-1$
    assertTrue("matches declare child should exist",
            ((String) ((TreeObject) c3[0]).getName()).equals("matches declare"));
    Object[] c4 = viewContentProvider.getChildren(c3[0]);
    assertEquals("matches declare should have 1 child", 1, c4.length); //$NON-NLS-1$
    assertTrue("matches declare child should exist",
            ((AJNode) ((TreeObject) c4[0]).getData()).getJavaElement().exists());

    // Check that all the children have been added to the innerclass node
    Object[] d1 = viewContentProvider.getChildren(innerClassC1);
    assertEquals("inner class should have 1 child", 1, d1.length); //$NON-NLS-1$
    assertTrue("matches declare child should exist", ((IJavaElement) ((TreeObject) d1[0]).getData()).exists());
    Object[] d2 = viewContentProvider.getChildren(d1[0]);
    // if there aren't two children then this is a regression of bug 111189
    //  - the recursion in XReferenceContentProvider.addChildren(..) method
    assertEquals("method m() of inner class should have 2 children", 2, d2.length); //$NON-NLS-1$
    assertTrue("matches declare child should exist",
            ((String) ((TreeObject) d2[0]).getName()).equals("matches declare"));
    assertTrue("matches declare child should exist", ((IJavaElement) ((TreeObject) d2[1]).getData()).exists());
    // there are two children of m(): 'matches declare' and 
    // 'method-call(.....)'
    TreeParent matchesDeclare = null;
    TreeParent methodCall = null;
    for (int i = 0; i < d2.length; i++) {
        TreeParent t = (TreeParent) d2[i];
        if (t.getData() == null) {
            matchesDeclare = t;
        } else {
            methodCall = t;
        }
    }
    Object[] d3 = viewContentProvider.getChildren(matchesDeclare);
    assertEquals("matches declare should have one child", 1, d3.length); //$NON-NLS-1$
    assertTrue("matches declare child should exist",
            ((AJNode) ((TreeObject) d3[0]).getData()).getJavaElement().exists());
    Object[] d4 = viewContentProvider.getChildren(methodCall);
    assertEquals("method-call should have one child", 1, d4.length); //$NON-NLS-1$
    assertTrue("matches declare child should exist",
            ((String) ((TreeObject) d4[0]).getName()).equals("matches declare"));
    Object[] d5 = viewContentProvider.getChildren(d4[0]);
    assertEquals("matches declare should have one child", 1, d5.length); //$NON-NLS-1$
    assertTrue("matches declare child should exist",
            ((AJNode) ((TreeObject) d5[0]).getData()).getJavaElement().exists());
}

From source file:org.eclipse.andmore.wizards.buildingblocks.NewBuildingBlocksWizardPage.java

License:Apache License

/**
 * Checks for cross package/class collision among source folders
 * /*from   w  ww .  j a  v a  2 s .c o  m*/
 * @return true if there is any collision or false otherwise
 */
private boolean packageAndClassExist() {
    boolean exists = false;

    try {
        if ((getJavaProject() != null) && getJavaProject().isOpen()) {
            IPackageFragmentRoot[] roots = getJavaProject().getPackageFragmentRoots();

            if (roots != null) {
                for (IPackageFragmentRoot root : roots) {
                    if ((root.getKind() & IPackageFragmentRoot.K_SOURCE) == IPackageFragmentRoot.K_SOURCE) {
                        IPackageFragment pack = root.getPackageFragment(getPackageText());

                        if ((pack != null) && pack.exists()) {
                            IJavaElement classes[] = pack.getChildren();

                            if (classes != null) {
                                for (IJavaElement clazz : classes) {
                                    if (clazz.getElementName().equals(getTypeName() + JAVA_EXTENSION)) {
                                        exists = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if (exists) {
                        break;
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        // Do nothing
        AndmoreLogger.error(NewBuildingBlocksWizardPage.class, e.getLocalizedMessage(), e);
    }

    return exists;
}

From source file:org.eclipse.capra.handler.jdt.JavaElementHandler.java

License:Open Source License

@Override
public String getName(Object selection) {
    if (selection instanceof IJavaElement) {
        IJavaElement cu = (IJavaElement) selection;
        return cu.getElementName();
    } else if (selection instanceof WorkingSet) {
        WorkingSet ws = (WorkingSet) selection;
        return ws.getName();
    }//from  w  w w  . j av a 2s  . c  om

    return "";
}

From source file:org.eclipse.che.jdt.internal.core.search.JavaSearchScope.java

License:Open Source License

private IPath getPath(IJavaElement element, boolean relativeToRoot) {
    switch (element.getElementType()) {
    case IJavaElement.JAVA_MODEL:
        return Path.EMPTY;
    case IJavaElement.JAVA_PROJECT:
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        if (relativeToRoot)
            return Path.EMPTY;
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT:
        String relativePath = org.eclipse.jdt.internal.core.util.Util
                .concatWith(((PackageFragment) element).names, '/');
        return getPath(element.getParent(), relativeToRoot).append(new Path(relativePath));
    case IJavaElement.COMPILATION_UNIT:
    case IJavaElement.CLASS_FILE:
        return getPath(element.getParent(), relativeToRoot).append(new Path(element.getElementName()));
    default:/*  ww w  . j  ava 2 s  . com*/
        return getPath(element.getParent(), relativeToRoot);
    }
}

From source file:org.eclipse.che.jdt.JavaTypeHierarchy.java

License:Open Source License

/**
 * Get all implementations of selected Java Element.
 *
 * @param project// ww  w. j  a v a 2 s  . c  o  m
 *         opened project
 * @param fqn
 *         fully qualified name of the class file
 * @param offset
 *         cursor position
 * @return descriptor of the implementations
 * @throws JavaModelException
 *         when JavaModel has a failure
 */
public ImplementationsDescriptorDTO getImplementations(IJavaProject project, String fqn, int offset)
        throws JavaModelException {
    ImplementationsDescriptorDTO implementationDescriptor = DtoFactory
            .newDto(ImplementationsDescriptorDTO.class);

    IJavaElement element = getJavaElement(project, fqn, offset);
    if (element == null) {
        return implementationDescriptor.withImplementations(emptyList());
    }

    List<Type> implementations = new ArrayList<>();

    implementationDescriptor.setImplementations(implementations);

    switch (element.getElementType()) {
    case 7: //type
        findSubTypes(element, implementations);
        implementationDescriptor.setMemberName(element.getElementName());
        break;
    case 9: //method
        findTypesWithSubMethods(element, implementations);
        implementationDescriptor.setMemberName(element.getElementName());
        break;
    default:
        break;
    }

    return implementationDescriptor;
}

From source file:org.eclipse.che.jdt.ParametersHints.java

License:Open Source License

private void findHints(IJavaElement method, IJavaElement parent, List<MethodParameters> result)
        throws JavaModelException {
    String methodName = method.getElementName();

    for (IMethod iMethod : ((IType) parent).getMethods()) {
        int methodFlag = iMethod.getFlags();
        if (Flags.isPrivate(methodFlag) || !methodName.equals(iMethod.getElementName())) {
            continue;
        }//from  ww w  . j av  a2 s .  c o m

        MethodParameters methodParameters = DtoFactory.newDto(MethodParameters.class);

        String parameters = getMethodParametersAsString(iMethod);

        methodParameters.setMethodName(methodName);
        methodParameters.setParameters(parameters);

        if (!result.contains(methodParameters)) {
            result.add(methodParameters);
        }
    }
}