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

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

Introduction

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

Prototype

IJavaProject getJavaProject();

Source Link

Document

Returns the Java project this element is contained in, or null if this element is not contained in any Java project (for instance, the IJavaModel is not contained in any Java project).

Usage

From source file:org.eclipse.ajdt.internal.buildpath.ConfigureAJBuildPathAction.java

License:Open Source License

private IProject getProjectFromSelectedElement(Object firstElement) {
    if (firstElement instanceof IJavaElement) {
        IJavaElement element = (IJavaElement) firstElement;
        IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(element);
        if (root != null && root != element && root.isArchive()) {
            return null;
        }/*from   w w w. ja  va  2  s .  c o m*/
        IJavaProject project = element.getJavaProject();
        if (project != null) {
            return project.getProject();
        }
        return null;
    } else if (firstElement instanceof ClassPathContainer) {
        return ((ClassPathContainer) firstElement).getJavaProject().getProject();
    } else if (firstElement instanceof IAdaptable) {
        IResource res = (IResource) ((IAdaptable) firstElement).getAdapter(IResource.class);
        if (res != null) {
            return res.getProject();
        }
    }
    return null;
}

From source file:org.eclipse.ajdt.internal.ui.ajdocexport.AJdocOptionsManager.java

License:Open Source License

private IJavaElement getSelectableJavaElement(Object obj) throws JavaModelException {
    IJavaElement je = null;
    if (obj instanceof IAdaptable) {
        je = (IJavaElement) ((IAdaptable) obj).getAdapter(IJavaElement.class);
    }//from  w w w  .ja v  a2s .c o m

    if (je != null) {
        switch (je.getElementType()) {
        case IJavaElement.JAVA_MODEL:
        case IJavaElement.JAVA_PROJECT:
        case IJavaElement.CLASS_FILE:
            break;
        case IJavaElement.PACKAGE_FRAGMENT_ROOT:
            if (containsCompilationUnits((IPackageFragmentRoot) je)) {
                return je;
            }
            break;
        case IJavaElement.PACKAGE_FRAGMENT:
            if (containsCompilationUnits((IPackageFragment) je)) {
                return je;
            }
            break;
        default:
            ICompilationUnit cu = (ICompilationUnit) je.getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null) {
                return cu;
            }
        }
        IJavaProject project = je.getJavaProject();
        if (isValidProject(project))
            return project;
    }

    return null;
}

From source file:org.eclipse.ajdt.internal.ui.lazystart.AdviceImageDecorator.java

License:Open Source License

public void decorate(Object element, IDecoration decoration) {
    // add the orange triangle to the icon if this method, 
    // class or aspect is advised
    if ((element instanceof IMethod || element instanceof SourceType)) {
        IJavaElement je = (IJavaElement) element;
        IJavaProject jp = je.getJavaProject();
        // only query the model if the element is in an AJ project
        if ((jp != null) && Utils.isAJProject(jp.getProject()) && !(je instanceof AspectJMemberElement)) {
            if (AJProjectModelFactory.getInstance().getModelForJavaElement(je).isAdvised(je)) {
                ensureAdviceListenerIsRegistered();
                // causes bundle activation
                AspectJUIPlugin.getDefault();
                decoration.addOverlay(AspectJImages.ADVICE_OVERLAY.getImageDescriptor(), IDecoration.TOP_LEFT);
            }//w w w .ja v a  2s .c  o m
        }
    }
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.PushInRefactoring.java

License:Open Source License

private AJProjectModelFacade getModel(IJavaElement elt) {
    IProject project = elt.getJavaProject().getProject();
    AJProjectModelFacade model = allModels.get(project);
    if (model == null) {
        model = AJProjectModelFactory.getInstance().getModelForProject(project);
        allModels.put(project, model);//from   w  w w.j  a  v a 2 s .  c om
    }
    return model;
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.PushInRefactoring.java

License:Open Source License

private NameLookup getLookup(IJavaElement elt) throws JavaModelException {
    IJavaProject javaProject = elt.getJavaProject();
    NameLookup nameLookup = allLookups.get(javaProject);
    if (nameLookup == null) {
        nameLookup = ((JavaProject) javaProject).newNameLookup(DefaultWorkingCopyOwner.PRIMARY);
        allLookups.put(javaProject, nameLookup);
    }//from   ww  w . ja  va 2  s .  co m
    return nameLookup;
}

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

License:Open Source License

/**
 * Keeps the currentJavaElement and currentProject information up to date in
 * this class, as this method is called whenever a user changes their
 * selection in the workspace./*from www.ja va2s.  c o m*/
 */
public void selectionChanged(IWorkbenchPart workbenchPart, ISelection selection) {

    /*
     * What is the significance of this check?
     * 
     * 'If we are not the current content provider, we don't need to bother
     * updating to reflect the new selection'?
     * 
     * Yes, but what does it meant to be the current content provider? It's
     * not analagous to being the curerntly selected perspective.
     * 
     * Also, this code still gets called, even when the Visualiser
     * perspective has been closed. Guess it's still loaded.
     * 
     * -spyoung
     */

    if (!(ProviderManager.getContentProvider().equals(this))) {
        return;
    }

    boolean updateRequired = false;
    if (selection instanceof IStructuredSelection) {
        IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        Object firstElement = structuredSelection.getFirstElement();

        if (firstElement != null) {
            if (firstElement instanceof IJavaElement) {
                IJavaElement javaElement = (IJavaElement) firstElement;
                if (currentlySelectedJE == javaElement) {
                    return;
                }
                currentlySelectedJE = javaElement;
                updateRequired = true;
                if (javaElement.getJavaProject() != null) {
                    setCurrentProject(javaElement.getJavaProject());
                }
            }
        }
    }

    if (updateRequired) {
        reset();
        VisualiserPlugin.refresh();
    }
}

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  w  w  .j  a  va2  s. c  o  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.internal.ui.wizards.exports.AJJarPackageWizardPage.java

License:Open Source License

protected void setupBasedOnInitialSelections() {
    Iterator iterator = fInitialSelection.iterator();
    while (iterator.hasNext()) {
        Object selectedElement = iterator.next();

        if (selectedElement instanceof IResource && !((IResource) selectedElement).isAccessible())
            continue;

        if (selectedElement instanceof IJavaElement && !((IJavaElement) selectedElement).exists())
            continue;

        if (selectedElement instanceof ICompilationUnit || selectedElement instanceof IClassFile
                || selectedElement instanceof IFile)
            fInputGroup.initialCheckListItem(selectedElement);
        else {/*from  w ww  . j  a  v a2  s  .com*/
            if (selectedElement instanceof IFolder) {
                // Convert resource to Java element if possible
                IJavaElement je = JavaCore.create((IResource) selectedElement);
                if (je != null && je.exists() && je.getJavaProject().isOnClasspath((IResource) selectedElement))
                    selectedElement = je;
            }
            fInputGroup.initialCheckTreeItem(selectedElement);
        }
    }

    TreeItem[] items = fInputGroup.getTree().getItems();
    int i = 0;
    while (i < items.length && !items[i].getChecked())
        i++;
    if (i < items.length) {
        fInputGroup.getTree().setSelection(new TreeItem[] { items[i] });
        fInputGroup.getTree().showSelection();
        fInputGroup.populateListViewer(items[i].getData());
    }
}

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

License:Open Source License

/**
 * Initializes all fields provided by the page with a given selection.
 * // w  ww .  j a  v  a  2 s  . co m
 * @param elem the selection used to initialize this page or <code>
 * null</code> if no selection was available
 */
protected void initTypePage(IJavaElement elem) {
    String initSuperclass = "java.lang.Object"; //$NON-NLS-1$
    ArrayList initSuperinterfaces = new ArrayList(5);

    IJavaProject project = null;
    IPackageFragment pack = null;
    IType enclosingType = null;

    if (elem != null) {
        // evaluate the enclosing type
        project = elem.getJavaProject();
        pack = (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
        IType typeInCU = (IType) elem.getAncestor(IJavaElement.TYPE);
        if (typeInCU != null) {
            if (typeInCU.getCompilationUnit() != null) {
                enclosingType = typeInCU;
            }
        } else {
            ICompilationUnit cu = (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null) {
                enclosingType = cu.findPrimaryType();
            }
        }

        try {
            IType type = null;
            if (elem.getElementType() == IJavaElement.TYPE) {
                type = (IType) elem;
                if (type.exists()) {
                    String superName = SuperInterfaceSelectionDialog.getNameWithTypeParameters(type);
                    if (type.isInterface()) {
                        initSuperinterfaces.add(superName);
                    } else {
                        initSuperclass = superName;
                    }
                }
            }
        } catch (JavaModelException e) {
            JavaPlugin.log(e);
            // ignore this exception now
        }
    }

    String typeName = ""; //$NON-NLS-1$

    ITextSelection selection = getCurrentTextSelection();
    if (selection != null) {
        String text = selection.getText();
        if (text != null && validateJavaTypeName(text, project).isOK()) {
            typeName = text;
        }
    }

    setPackageFragment(pack, true);
    setEnclosingType(enclosingType, true);
    setEnclosingTypeSelection(false, true);

    setTypeName(typeName, true);
    setSuperClass(initSuperclass, true);
    setSuperInterfaces(initSuperinterfaces, true);

    setAddComments(StubUtility.doAddComments(project), true); // from project or workspace
}

From source file:org.eclipse.birt.report.designer.internal.ui.ide.util.ClassFinder.java

License:Open Source License

private List findCLasses(IJavaElement element, IProgressMonitor pm) throws JavaModelException {
    List found = new ArrayList();
    IJavaProject javaProject = element.getJavaProject();

    IType testCaseType = classType(javaProject);
    if (testCaseType == null)
        return found;

    IType[] subtypes = javaProject.newTypeHierarchy(testCaseType, getRegion(element), pm)
            .getAllSubtypes(testCaseType);

    if (subtypes == null)
        throw new JavaModelException(new CoreException(new Status(IStatus.ERROR, ID,
                IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE, ERROR_MESSAGE, null)));

    for (int i = 0; i < subtypes.length; i++) {
        try {//from  w  w w.jav  a  2 s.c om
            if (hasValidModifiers(subtypes[i]))
                found.add(subtypes[i]);
        } catch (JavaModelException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
        }
    }
    return found;
}