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.jboss.tools.ws.jaxrs.core.internal.metamodel.builder.JavaElementDeltaScanner.java

License:Open Source License

/**
 * Recursively analyse the given Java Element Delta.
 * //from  w w w .  j av a 2s.c  om
 * @param delta
 * @param eventType
 * @throws CoreException
 * @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=100267
 */
private List<JavaElementChangedEvent> scanDelta(final IJavaElementDelta delta, final int eventType)
        throws CoreException {
    final List<JavaElementChangedEvent> events = new ArrayList<JavaElementChangedEvent>();
    final IJavaElement element = delta.getElement();
    // skip as the project is closed
    if (element == null) {
        Logger.debug("** skipping this build because the delta element is null **");
        return Collections.emptyList();
    } else if (element.getElementType() == IJavaElement.JAVA_PROJECT
            && !element.getJavaProject().getProject().isOpen() && delta.getFlags() != F_OPENED) {
        Logger.debug("** skipping this build because the java project is closed. **");
        return Collections.emptyList();
    } else if ((element.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT)) {
        final IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) element;
        if (!packageFragmentRoot.isExternal()
                && (packageFragmentRoot.getResource() == null || !packageFragmentRoot.getResource().exists())) {
            return Collections.emptyList();
        }
    } else if (element.getResource() == null || !element.getResource().exists()) {
        return Collections.emptyList();
    }
    final int elementKind = element.getElementType();
    final int deltaKind = retrieveDeltaKind(delta);
    final Flags flags = new Flags(delta.getFlags());
    if (elementKind == JAVA_PROJECT) {
        final JavaElementChangedEvent event = new JavaElementChangedEvent(element, delta.getKind(), eventType,
                null, new Flags(delta.getFlags()));
        if (javaElementChangedEventFilter.apply(event)) {
            events.add(event);
            // skip anything below
            return events;
        }
    }
    final CompilationUnit compilationUnitAST = getCompilationUnitAST(delta);
    if (elementKind == COMPILATION_UNIT) {
        final ICompilationUnit compilationUnit = (ICompilationUnit) element;
        // compilationUnitAST is null when the given compilation unit'w
        // working copy is being commited (ie, Java Editor is being closed
        // for the given compilation unit, etc.)
        if (compilationUnit.exists() // see https://issues.jboss.org/browse/JBIDE-12760: compilationUnit may not exist
                && compilationUnit.isWorkingCopy() && compilationUnitAST != null) {
            // assuming possible changes in the method signatures (return type,
            // param types and param annotations). Other changes in methods
            // (renaming, adding/removing params) result in add+remove
            // events on the given method itself.
            if (requiresDiffsComputation(flags)) {
                for (IType type : compilationUnit.getAllTypes()) {
                    for (IMethod javaMethod : type.getMethods()) {
                        final JavaElementChangedEvent event = new JavaElementChangedEvent(javaMethod, CHANGED,
                                eventType, compilationUnitAST, new Flags(F_SIGNATURE));
                        if (javaElementChangedEventFilter.apply(event)) {
                            events.add(event);
                        }
                    }
                }
            }
        }
    }
    // element is part of the compilation unit
    else if (compilationUnitAST != null) {
        final JavaElementChangedEvent event = new JavaElementChangedEvent(element, deltaKind, eventType,
                compilationUnitAST, flags);
        if (javaElementChangedEventFilter.apply(event)) {
            events.add(event);
        }
    }
    // continue with children elements, both on annotations and other java
    // elements.
    for (IJavaElementDelta affectedChild : delta.getAffectedChildren()) {
        events.addAll(scanDelta(affectedChild, eventType));
    }
    for (IJavaElementDelta annotation : delta.getAnnotationDeltas()) {
        events.addAll(scanDelta(annotation, eventType));
    }
    return events;
}

From source file:org.jboss.tools.ws.jaxrs.core.internal.metamodel.search.JavaElementsSearcher.java

License:Open Source License

/**
 * @param scope the search scope/*ww w .j  ava2 s.  c o  m*/
 * @param typeName the fully qualified name of the type whose subtypes should be found
 * @param progressMonitor the progress monitor
 * @return the subtypes of the given type, in the given scope, or empty list if none was found.
 * @throws CoreException
 * @throws JavaModelException
 */
private static List<IType> findSubtypes(final IJavaElement scope, final String typeName,
        final IProgressMonitor progressMonitor) throws CoreException, JavaModelException {
    final IType superType = JdtUtils.resolveType(typeName, scope.getJavaProject(), progressMonitor);
    final List<IType> subtypes = JdtUtils.findSubtypes(scope, superType, progressMonitor);
    return subtypes;
}

From source file:org.jboss.tools.ws.jaxrs.core.jdt.JaxrsAnnotationsScanner.java

License:Open Source License

/**
 * Returns all JAX-RS Applications in the given scope (ex : javaProject), ie, types annotated with
 * <code>javax.ws.rs.ApplicationPath</code> annotation and subtypes of
 * {@link javax.ws.rs.Application} (even if type hirarchy or annotation is missing).
 * /*  w ww  .  j  a  v a  2 s.  c o  m*/
 * 
 * @param scope
 *            the search scope (project, compilation unit, type, etc.)
 * @param includeLibraries
 *            include project libraries in search scope or not
 * @param progressMonitor
 *            the progress monitor
 * @return providers the JAX-RS provider types
 * @throws CoreException
 *             in case of exception
 */
public static List<IType> findApplicationTypes(final IJavaElement scope, final IProgressMonitor progressMonitor)
        throws CoreException {
    //FIXME: need correct usage of progressmonitor/subprogress monitor

    // first, search for type annotated with <code>javax.ws.rs.ApplicationPath</code>
    IJavaSearchScope searchScope = null;
    searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { scope },
            IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS);

    final List<IType> applicationTypes = searchForAnnotatedTypes(APPLICATION_PATH.qualifiedName, searchScope,
            progressMonitor);
    // the search result also includes all subtypes of javax.ws.rs.core.Application (while avoiding duplicate results)
    final IType applicationType = JdtUtils.resolveType(APPLICATION.qualifiedName, scope.getJavaProject(),
            progressMonitor);
    if (applicationType != null) {
        final ITypeHierarchy applicationTypeHierarchy = JdtUtils.resolveTypeHierarchy(applicationType, scope,
                false, progressMonitor);
        final IType[] allSubtypes = applicationTypeHierarchy.getAllSubtypes(applicationType);
        for (IType subtype : allSubtypes) {
            if (subtype.getJavaProject().equals(scope.getJavaProject())
                    && !applicationTypes.contains(subtype)) {
                applicationTypes.add(subtype);
            }
        }
    } else {
        Logger.warn("Could not find type '" + APPLICATION.qualifiedName + "' in project's classpath.");
    }
    return applicationTypes;
}

From source file:org.jboss.tools.ws.jaxrs.core.jdt.JdtUtils.java

License:Open Source License

/**
 * Searches and returns all the subtypes of the given superType that do not
 * have themselves other subtypes/*  w  w w .  j av  a 2s. c  o m*/
 * 
 * @param scope
 * @param progressMonitor
 * @param searchScope
 * @return a list of subtypes or an empty list if none was found.
 * @throws CoreException
 * @throws JavaModelException
 */
public static List<IType> findSubtypes(final IJavaElement scope, final IType superType,
        final IProgressMonitor progressMonitor) throws CoreException, JavaModelException {
    final List<IType> types = new ArrayList<IType>();
    if (superType != null) {
        final ITypeHierarchy hierarchy = JdtUtils.resolveTypeHierarchy(superType, scope, false,
                progressMonitor);
        final IType[] allSubtypes = hierarchy.getAllSubtypes(superType);
        for (IType subtype : allSubtypes) {
            if (subtype.isStructureKnown() && subtype.getJavaProject().equals(scope.getJavaProject())
                    && hierarchy.getAllSubtypes(subtype).length == 0) {
                types.add(subtype);
            }
        }
    }
    return types;
}

From source file:org.jboss.tools.ws.jaxrs.ui.navigation.JaxrsNameBindingHyperlinkDetector.java

License:Open Source License

/**
 * @param input the current {@link IJavaElement}
 * @return the {@link JaxrsMetamodel} associated with the given element or {@code null} if none exists (or if an exception was thrown).
 *///from  w w  w. jav  a  2  s .  c o  m
private JaxrsMetamodel getMetamodel(final IJavaElement input) {
    try {
        return JaxrsMetamodelLocator.get(input.getJavaProject());
    } catch (CoreException e) {
        Logger.error("Failed to retrieve JAX-RS Metamodel for " + input.getElementName(), e);
        return null;
    }
}

From source file:org.jboss.tools.ws.jaxrs.ui.quickfix.JaxrsMarkerResolutionGenerator.java

License:Open Source License

/**
 * @param javaElement/*from w  ww.  ja va  2  s.  co  m*/
 *            the java element
 * @return the {@link IJaxrsElement} associated with the given
 *         {@link IJavaElement}, or {@code null} if none was found.
 */
private static IJaxrsElement findJaxrsElement(final IJavaElement javaElement) {
    if (javaElement != null) {
        try {
            return JaxrsMetamodelLocator.get(javaElement.getJavaProject()).findElement(javaElement);
        } catch (CoreException e) {
            Logger.error(
                    "Failed to retrieve JAX-RS Elements associated with '" + javaElement.getElementName() + "'",
                    e);
        }
    }
    return null;
}

From source file:org.jboss.tools.ws.jaxws.ui.utils.JBossWSUIUtils.java

License:Open Source License

public static IStatus validateClassName(String name, IJavaElement context) {
    IStatus status = null;//from  www .  j  a  va2  s  .  c o  m
    String[] sourceComplianceLevels = getSourceComplianceLevels(context);
    status = JavaConventions.validateClassFileName(name + CLASS, sourceComplianceLevels[0],
            sourceComplianceLevels[1]);
    if (status != null && status.getSeverity() == IStatus.ERROR) {
        return status;
    }
    File file = JBossWSCreationUtils.findFileByPath(name + JAVA,
            context.getJavaProject().getProject().getLocation().toOSString());
    if (file != null && file.exists()) {
        status = StatusUtils.warningStatus(JBossJAXWSUIMessages.Error_JBossWS_GenerateWizard_ClassName_Same);
    }
    return status;
}

From source file:org.jboss.tools.ws.jaxws.ui.utils.JBossWSUIUtils.java

License:Open Source License

public static IStatus validatePackageName(String name, IJavaElement context) {
    IStatus status = null;//from   w ww .  jav  a 2  s.c  o m
    if (context == null || !context.exists()) {
        status = JavaConventions.validatePackageName(name, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3);
        if (status != null && !status.isOK()) {
            return status;
        }
    }
    String[] sourceComplianceLevels = getSourceComplianceLevels(context);
    status = JavaConventions.validatePackageName(name, sourceComplianceLevels[0], sourceComplianceLevels[1]);
    if (status != null && status.getSeverity() == IStatus.ERROR) {
        return status;
    }

    IPackageFragmentRoot[] roots = null;
    try {
        IResource[] srcFolders = JBossWSCreationUtils.getJavaSourceRoots(context.getJavaProject());
        roots = new IPackageFragmentRoot[srcFolders.length];
        int i = 0;
        for (IResource src : srcFolders) {
            roots[i] = context.getJavaProject().getPackageFragmentRoot(src);
            i++;
        }
    } catch (JavaModelException e) {
        JBossWSUIPlugin.log(e);
    }
    for (IPackageFragmentRoot root : roots) {
        if (root != null) {
            IPackageFragment pack = root.getPackageFragment(name);
            try {
                IPath rootPath = root.getPath();
                IPath outputPath = root.getJavaProject().getOutputLocation();
                if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
                    // if the bin folder is inside of our root, don't allow
                    // to name a package
                    // like the bin folder
                    IPath packagePath = pack.getPath();
                    if (outputPath.isPrefixOf(packagePath)) {
                        status = StatusUtils.warningStatus(
                                JBossJAXWSUIMessages.Error_JBossWS_GenerateWizard_IsOutputFolder);
                        return status;
                    }
                }
                if (pack.exists()) {
                    if (pack.containsJavaResources() || !pack.hasSubpackages()) {
                        status = StatusUtils
                                .warningStatus(JBossJAXWSUIMessages.Error_JBossWS_GenerateWizard_PackageExists);
                    } else {
                        status = StatusUtils.warningStatus(
                                JBossJAXWSUIMessages.Error_JBossWS_GenerateWizard_PackageNotShown);
                    }
                    return status;
                } else {
                    if (pack.getResource() == null) {
                        continue;
                    }
                    URI location = pack.getResource().getLocationURI();
                    if (location != null) {
                        IFileStore store = EFS.getStore(location);
                        if (store.fetchInfo().exists()) {
                            status = StatusUtils.warningStatus(
                                    JBossJAXWSUIMessages.Error_JBossWS_GenerateWizard_PackageExistsDifferentCase);
                            return status;
                        }
                    }
                }
            } catch (CoreException e) {
                JBossWSUIPlugin.log(e);
            }
        }
    }
    return status;
}

From source file:org.jboss.tools.ws.jaxws.ui.utils.JBossWSUIUtils.java

License:Open Source License

public static String[] getSourceComplianceLevels(IJavaElement context) {
    if (context != null) {
        IJavaProject javaProject = context.getJavaProject();
        if (javaProject != null) {
            return new String[] { javaProject.getOption(JavaCore.COMPILER_SOURCE, true),
                    javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true) };
        }//from w ww .ja  va 2  s  .  co m
    }
    return new String[] { JavaCore.getOption(JavaCore.COMPILER_SOURCE),
            JavaCore.getOption(JavaCore.COMPILER_COMPLIANCE) };
}

From source file:org.jboss.tools.ws.ui.utils.JBossWSUIUtils.java

License:Open Source License

public static IStatus validateClassName(String name, IJavaElement context) {
    IStatus status = null;//from ww  w  .  j  a  v a2  s  .com
    String[] sourceComplianceLevels = getSourceComplianceLevels(context);
    status = JavaConventions.validateClassFileName(name + CLASS, sourceComplianceLevels[0],
            sourceComplianceLevels[1]);
    if (status != null && status.getSeverity() == IStatus.ERROR) {
        return status;
    }
    File file = JBossWSCreationUtils.findFileByPath(name + JAVA,
            context.getJavaProject().getProject().getLocation().toOSString());
    if (file != null && file.exists()) {
        status = StatusUtils.warningStatus(JBossWSUIMessages.Error_JBossWS_GenerateWizard_ClassName_Same);
    }
    return status;
}