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.xtext.common.types.ui.refactoring.participant.JdtRenameParticipant.java

License:Open Source License

@Override
protected List<? extends IRenameElementContext> createRenameElementContexts(Object element) {
    if (element instanceof IJavaElement) {
        IJavaElement javaElement = (IJavaElement) element;
        EClass expectedJvmType = getExpectedJvmType(javaElement);
        if (expectedJvmType != null) {
            IJavaProject javaProject = javaElement.getJavaProject();
            IProject project = javaProject.getProject();
            ResourceSet resourceSet = resourceSetProvider.get(project);
            EObject directJvmElement = jvmElementFinder.getCorrespondingJvmElement(javaElement, resourceSet);
            if (directJvmElement != null && expectedJvmType.isSuperTypeOf(directJvmElement.eClass())) {
                ResourceSet resourceSet2 = resourceSetProvider.get(project);
                EObject indexedJvmElement = jvmElementFinder.findJvmElementDeclarationInIndex(directJvmElement,
                        project, resourceSet2);
                if (indexedJvmElement != null)
                    // jvmElement is indexed, thus contained in an XtextResurce and likely inferred from some Xtext-based elements
                    return getContextFactory(indexedJvmElement).createJdtParticipantXtextSourceContexts(this,
                            indexedJvmElement);
                else if (directJvmElement instanceof JvmMember)
                    // jvmElement could only be cross referenced by Xtext-based elements
                    return createJdtRenameParticipantContext((JvmMember) directJvmElement, javaElement);
            }/*from  w  w w. j a  v  a  2  s  .c  om*/
        }
    }
    return null;
}

From source file:org.eclipse.xtext.ui.containers.JavaProjectsStateHelper.java

License:Open Source License

public List<String> initVisibleHandles(String handle) {
    IJavaElement javaElement = JavaCore.create(handle);
    if (javaElement != null) {
        IJavaProject project = javaElement.getJavaProject();
        if (isAccessibleXtextProject(project.getProject())) {
            List<String> rootHandles = getPackageFragmentRootHandles(project);
            return rootHandles;
        }/*  ww w .j  ava  2  s.c o  m*/
        return Collections.emptyList();
    }
    return Collections.emptyList();
}

From source file:org.eclipse.xtext.xbase.ui.validation.XbaseUIValidator.java

License:Open Source License

protected void checkRestrictedType(final EObject context, final EStructuralFeature feature,
        final JvmDeclaredType typeToCheck) {
    @SuppressWarnings("unchecked")
    Map<JvmDeclaredType, RestrictionKind> validationContext = (Map<JvmDeclaredType, RestrictionKind>) getContext()
            .get(RestrictionKind.class);
    if (validationContext == null) {
        validationContext = Maps.newHashMap();
        getContext().put(RestrictionKind.class, validationContext);
    }/*from  ww  w  .  java  2 s  . c om*/
    RestrictionKind restriction = validationContext.get(typeToCheck);
    IJavaProject javaProject = null;
    if (restriction == null) {
        final IJavaElement javaElement = javaElementFinder.findElementFor(typeToCheck);
        if (javaElement == null || !(javaElement instanceof IType)) {
            validationContext.put(typeToCheck, RestrictionKind.VALID);
            return;
        }
        javaProject = javaElement.getJavaProject();
        restriction = computeRestriction(projectProvider.getJavaProject(context.eResource().getResourceSet()),
                (IType) javaElement);
        validationContext.put(typeToCheck, restriction);
    }

    if (restriction == RestrictionKind.FORBIDDEN) {
        if (javaProject == null)
            javaProject = projectProvider.getJavaProject(context.eResource().getResourceSet());

        addIssue("Access restriction: The type " + typeToCheck.getSimpleName()
                + " is not accessible due to restriction on required project " + javaProject.getElementName(),
                context, feature, IssueCodes.FORBIDDEN_REFERENCE);
    } else if (restriction == RestrictionKind.DISCOURAGED) {
        if (javaProject == null)
            javaProject = projectProvider.getJavaProject(context.eResource().getResourceSet());
        addIssue("Discouraged access: The type " + typeToCheck.getSimpleName()
                + " is not accessible due to restriction on required project " + javaProject.getElementName(),
                context, feature, IssueCodes.DISCOURAGED_REFERENCE);
    }
}

From source file:org.eclipse.zest.dot.internal.ZestProjectWizard.java

License:Open Source License

private void setupProjectClasspath(final IJavaElement javaElement, final IWorkspaceRoot root,
        final IResource newProject) {
    try {/*w w w  . j a  v  a 2  s.  co  m*/
        IClasspathEntry[] classpath = javaElement.getJavaProject().getRawClasspath();
        /*
         * We will add two items to the classpath: a src-gen source folder and the Zest plugin
         * dependencies (to get the required SWT and Zest dependencies into the newly created
         * project).
         */
        IClasspathEntry[] newClasspath = new IClasspathEntry[classpath.length + 2];
        IProject project = (IProject) newProject;
        IFolder sourceGenFolder = project.getFolder(SRC_GEN);
        sourceGenFolder.create(true, true, null);
        createPackage(project, sourceGenFolder);
        /* Copy over the existing classpath entries: */
        for (int i = 0; i < classpath.length; i++) {
            newClasspath[i] = classpath[i];
        }
        newClasspath[newClasspath.length - 2] = JavaCore.newSourceEntry(sourceGenFolder.getFullPath());
        newClasspath[newClasspath.length - 1] = JavaCore
                .newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"));
        /* Set the updated classpath: */
        javaElement.getJavaProject().setRawClasspath(newClasspath, null);
        /* Activate the Zest project nature: */
        ToggleNatureAction.toggleNature(project);
    } catch (JavaModelException e) {
        e.printStackTrace();
    } catch (CoreException e) {
        e.printStackTrace();
    }
}

From source file:org.evolizer.changedistiller.job.ChangeDistiller.java

License:Apache License

private IStatus processElement(IJavaElement element, IProgressMonitor group, int tick) {
    Job changeDistillerJob = null;/*w w  w  .j  av  a 2 s.com*/
    try {
        // ICompilationUnit
        if (element.getElementType() == IJavaElement.COMPILATION_UNIT) {
            changeDistillerJob = new SourceDistiller("Process class " + element.getElementName());
            SourceDistiller job = (SourceDistiller) changeDistillerJob;
            List<Revision> revisions = ChangeDistillerPlugin.getPersistencyProvider()
                    .query("from Revision as r where r.file.path like '%/" + element.getElementName()
                            + "' and r.number not like '1.%.%'" + " order by r.report.creationTime asc",
                            Revision.class);
            job.setProject(element.getJavaProject().getProject());
            job.setRevisionsToDistill(revisions);

            // IPackageFragment; but only process source fragments (exclude binary Jars)
        } else if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
            IPackageFragment fragment = (IPackageFragment) element;

            if ((fragment.getKind() == IPackageFragmentRoot.K_SOURCE) && fragment.containsJavaResources()) {
                changeDistillerJob = new PackageFragmentDistiller(
                        "Process Package " + fragment.getElementName());
                ((PackageFragmentDistiller) changeDistillerJob).setPackageFragment(fragment);
            }

            // IJavaProject
        } else if (element.getElementType() == IJavaElement.JAVA_PROJECT) {

            changeDistillerJob = new ProjectDistiller("Process project " + element.getElementName());
            ((ProjectDistiller) changeDistillerJob).setJavaProject((IJavaProject) element);

        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    if (changeDistillerJob != null) {
        changeDistillerJob.setProgressGroup(group, tick);
        changeDistillerJob.setPriority(Job.LONG);
        changeDistillerJob.schedule();

        try {
            // wait until ChangeDistiller finished selected element
            changeDistillerJob.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return changeDistillerJob.getResult();
    }
    return Status.OK_STATUS;
}

From source file:org.evolizer.core.util.selectionhandling.JavaSelectionHelper.java

License:Apache License

/**
 * Return the project object from a given Java element.
 * //from  w w  w.ja  v  a 2  s. co m
 * @param javaElement   The Java element
 * @return  The project object.
 */
public static IJavaProject getProject(IJavaElement javaElement) {
    IJavaProject project;
    if (javaElement instanceof IJavaProject) {
        project = (IJavaProject) javaElement;
    } else {
        project = javaElement.getJavaProject();
    }

    return project;
}

From source file:org.fusesource.ide.branding.wizards.NewCamelTestWizardPageOne.java

License:Open Source License

/**
 * Initialized the page with the current selection
 * //from w w w.  java2 s  .  com
 * @param selection
 *            The selection
 */
public void init(IStructuredSelection selection) {
    IJavaElement elem = getInitialJavaElement(selection);
    IJavaProject jproject = elem.getJavaProject();
    IPackageFragmentRoot testRoot = null;

    if (selection != null && !selection.isEmpty()) {
        Object selectedElement = selection.getFirstElement();
        IFile ifile = null;

        if (selectedElement instanceof IFile) {
            ifile = (IFile) selectedElement;
        } else if (selectedElement instanceof IAdaptable) {
            IAdaptable adaptable = (IAdaptable) selectedElement;
            ifile = (IFile) adaptable.getAdapter(IFile.class);
        }

        if (ifile != null) {
            setXmlFileUnderTest(ifile);
        }

        // now we determine the container for the test classes
        if (jproject != null && jproject.exists()) {
            try {
                IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
                for (int i = 0; i < roots.length; i++) {
                    if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                        if (roots[i].getPath().toFile().getPath()
                                .contains(String.format("src%stest%sjava", File.separator, File.separator))) {
                            testRoot = roots[i];
                            break;
                        } else if (roots[i].getPath().toFile().getPath()
                                .contains(String.format("src%stest%sscala", File.separator, File.separator))) {
                            testRoot = roots[i];
                            // we will prefer the src/test/java folder, so we don't break here and search for it
                        }
                    }
                }
            } catch (Exception ex) {
                Activator.getLogger().error(ex);
            }
        }
    }

    if (elem != null) {
        initContainerPage(elem);

        // if we found a suitable test class container then we set it here
        if (testRoot != null) {
            // set the container correctly
            setPackageFragmentRoot(testRoot, true);
        }

        IJavaProject project = elem.getJavaProject();
        resourceContainer = project.getProject();

        // evaluate the enclosing type
        IPackageFragment pack = (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
        if (pack != null) {
            setPackageFragment(pack, true);
        } else {
            File testFolderFile = project.getProject().getParent().getRawLocation()
                    .append(getPackageFragmentRoot().getPath().makeRelative()).toFile();
            File f = getBasePackage(testFolderFile);
            if (f != null && testRoot != null) {
                IPath p = new Path(f.getPath());
                p = p.makeRelativeTo(project.getProject().getParent().getRawLocation()
                        .append(getPackageFragmentRoot().getPath().makeRelative()));
                String name = "";
                StringTokenizer strTok = new StringTokenizer(p.toOSString(), File.separator);
                while (strTok.hasMoreTokens()) {
                    String tok = strTok.nextToken();
                    if (name.trim().length() > 0) {
                        name += ".";
                    }
                    name += tok;
                }
                try {
                    IPackageFragment pf = testRoot.createPackageFragment(name, true, new NullProgressMonitor());
                    setPackageFragment(pf, true);
                } catch (Exception ex) {
                    Activator.getLogger().error(ex);
                }
            }
        }

        if (fXmlFileUnderTest == null) {
            try {
                // if we have no file selected yet, lets see if there's a
                // single one available
                List<IFile> files = ResourceModelUtils.filter(resourceContainer,
                        new org.fusesource.ide.foundation.core.util.Filter<IFile>() {
                            @Override
                            public boolean matches(IFile file) {
                                if (Objects.equal(file.getFileExtension(), "xml")) {
                                    return camelXmlMatcher.matches(file);
                                }
                                return false;
                            }
                        });
                if (files.size() == 1) {
                    setXmlFileUnderTest(files.get(0));
                }
            } catch (Exception e) {
                Activator.getLogger().error("Failed to search for Camel XML files: " + e, e);
            }
        }
    }
    setJUnit4(true, true);
    updateStatus(getStatusList());
}

From source file:org.grails.ide.eclipse.core.junit.Grails20AwareTestFinder.java

License:Open Source License

/**
 * This method determines whether grails aware functionality applies to a given element. If it
 * returns false, then methods should just delegate to the original JUnit test finder.
 *///from  w  w w .  j av  a 2s  . c o  m
private boolean enableFor(IJavaElement el) {
    //      debug("enableFor? "+el.getElementName());
    IJavaProject javaProject = el.getJavaProject();
    if (javaProject != null) {
        //         debug("enableFor? "+javaProject.getElementName());
        IProject project = javaProject.getProject();
        if (GrailsNature.isGrailsProject(project)) {
            GrailsVersion version = GrailsVersion.getEclipseGrailsVersion(project);
            //            debug("enableFor? version = "+version);
            boolean result = GrailsVersion.V_2_0_0.compareTo(version) <= 0;
            //            debug("enableFor? => "+result);
            return result;
        } else {
            //            debug("enableFor? not a Grails project");
        }
    }
    //      debug("enableFor? => false");
    return false;
}

From source file:org.grails.ide.eclipse.editor.groovy.elements.GrailsWorkspaceCore.java

License:Open Source License

/**
 * Creates the {@link GrailsProject} associated with a particular
 * {@link IJavaElement}.  Will return null if the element 
 * is not in a Grails project./*from   w  w  w.j a v  a  2 s . co  m*/
 * @param elt
 * @return
 */
public GrailsProject getGrailsProjectFor(IJavaElement elt) {
    return create(elt.getJavaProject());
}

From source file:org.grails.ide.eclipse.test.util.AbstractGrailsJUnitIntegrationsTest.java

License:Open Source License

/**
 * COPIED from JUnitLaunchShortcut... create a JUnit lauch config just like the one the JUnit UI would.
 *///from  ww w  . j  a  va2  s . co m
public static ILaunchConfigurationWorkingCopy createLaunchConfiguration(IJavaElement element)
        throws CoreException {
    final String testName;
    final String mainTypeQualifiedName;
    final String containerHandleId;

    switch (element.getElementType()) {
    case IJavaElement.JAVA_PROJECT:
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
    case IJavaElement.PACKAGE_FRAGMENT: {
        String name = element.getElementName();
        containerHandleId = element.getHandleIdentifier();
        mainTypeQualifiedName = "";
        testName = name.substring(name.lastIndexOf(IPath.SEPARATOR) + 1);
    }
        break;
    case IJavaElement.TYPE: {
        containerHandleId = "";
        mainTypeQualifiedName = ((IType) element).getFullyQualifiedName('.'); // don't replace, fix for binary inner types
        testName = element.getElementName();
    }
        break;
    case IJavaElement.METHOD: {
        IMethod method = (IMethod) element;
        containerHandleId = "";
        mainTypeQualifiedName = method.getDeclaringType().getFullyQualifiedName('.');
        testName = method.getDeclaringType().getElementName() + '.' + method.getElementName();
    }
        break;
    default:
        throw new IllegalArgumentException(
                "Invalid element type to create a launch configuration: " + element.getClass().getName()); //$NON-NLS-1$
    }

    String testKindId = TestKindRegistry.getContainerTestKindId(element);

    ILaunchConfigurationType configType = getLaunchManager()
            .getLaunchConfigurationType(JUnitLaunchConfigurationConstants.ID_JUNIT_APPLICATION);
    ILaunchConfigurationWorkingCopy wc = configType.newInstance(null,
            getLaunchManager().generateLaunchConfigurationName(testName));

    wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, mainTypeQualifiedName);
    wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
            element.getJavaProject().getElementName());
    wc.setAttribute(JUnitLaunchConfigurationConstants.ATTR_KEEPRUNNING, false);
    wc.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_CONTAINER, containerHandleId);
    wc.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_RUNNER_KIND, testKindId);
    JUnitMigrationDelegate.mapResources(wc);
    //AssertionVMArg.setArgDefault(wc);
    if (element instanceof IMethod) {
        wc.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_METHOD_NAME, element.getElementName()); // only set for methods
    }
    return wc;
}