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

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

Introduction

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

Prototype

int COMPILATION_UNIT

To view the source code for org.eclipse.jdt.core IJavaElement COMPILATION_UNIT.

Click Source Link

Document

Constant representing a Java compilation unit.

Usage

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
 *///w ww  . ja v a 2 s.  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.internal.ui.wizards.exports.AJJarPackageWizard.java

License:Open Source License

private void addResource(List selectedElements, IResource resource) {
    IJavaElement je = JavaCore.create(resource);
    if (je != null && je.exists() && je.getElementType() == IJavaElement.COMPILATION_UNIT)
        selectedElements.add(je);/*from w w w  . jav  a 2  s. co  m*/
    else
        selectedElements.add(resource);
}

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

License:Open Source License

private void addJavaElement(List selectedElements, IJavaElement je) {
    if (je.getElementType() == IJavaElement.COMPILATION_UNIT)
        selectedElements.add(je);//from ww  w. ja  v a2  s.  co m
    else if (je.getElementType() == IJavaElement.CLASS_FILE)
        selectedElements.add(je);
    else if (je.getElementType() == IJavaElement.JAVA_PROJECT)
        selectedElements.add(je);
    else if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
        if (!JavaModelUtil.getPackageFragmentRoot(je).isArchive())
            selectedElements.add(je);
    } else if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
        if (!((IPackageFragmentRoot) je).isArchive())
            selectedElements.add(je);
    } else {
        IOpenable openable = je.getOpenable();
        if (openable instanceof ICompilationUnit)
            selectedElements.add(((ICompilationUnit) openable).getPrimary());
        else if (openable instanceof IClassFile && !JavaModelUtil.getPackageFragmentRoot(je).isArchive())
            selectedElements.add(openable);
    }
}

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 w w  .  j av  a  2  s  . com*/
 * @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.buildship.ui.launch.JavaElementResolver.java

License:Open Source License

private Optional<IType> resolveType(IJavaElement javaElement) {
    // exclude elements with no parent projects
    if (javaElement.getJavaProject() == null || javaElement.getJavaProject().getProject() == null) {
        return Optional.absent();
    }//  www  .j  a  v a  2  s  .  c  o  m

    IType result = null;
    switch (javaElement.getElementType()) {
    case IJavaElement.TYPE:
        result = (IType) javaElement;
        break;
    case IJavaElement.FIELD:
        result = ((IField) javaElement).getDeclaringType();
        break;
    case IJavaElement.CLASS_FILE:
    case IJavaElement.COMPILATION_UNIT:
        result = ((ITypeRoot) javaElement).findPrimaryType();
        break;
    }

    return Optional.fromNullable(result);
}

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

License:Open Source License

private int elementType(File res, int kind, int parentType, RootInfo rootInfo) {
    Path path = new Path(res.getAbsolutePath());
    switch (parentType) {
    case IJavaElement.JAVA_MODEL:
        // case of a movedTo or movedFrom project (other cases are handled in processResourceDelta(...)
        return IJavaElement.JAVA_PROJECT;

    case NON_JAVA_RESOURCE:
    case IJavaElement.JAVA_PROJECT:
        if (rootInfo == null) {
            rootInfo = enclosingRootInfo(path, kind);
        }//w w  w .  ja  v  a  2 s  . c  om
        if (rootInfo != null && rootInfo.isRootOfProject(path)) {
            return IJavaElement.PACKAGE_FRAGMENT_ROOT;
        }
        // not yet in a package fragment root or root of another project
        // or package fragment to be included (see below)
        // $FALL-THROUGH$

    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
    case IJavaElement.PACKAGE_FRAGMENT:
        if (rootInfo == null) {
            IPath rootPath = externalPath(res);
            rootInfo = enclosingRootInfo(rootPath, kind);
        }
        if (rootInfo == null) {
            return NON_JAVA_RESOURCE;
        }
        if (Util.isExcluded(path, rootInfo.inclusionPatterns, rootInfo.exclusionPatterns, false)) {
            return NON_JAVA_RESOURCE;
        }
        if (res.isDirectory()) {
            if (parentType == NON_JAVA_RESOURCE && !Util.isExcluded(new Path(res.getParent()),
                    rootInfo.inclusionPatterns, rootInfo.exclusionPatterns, false)) {
                // parent is a non-Java resource because it doesn't have a valid package name (see https://bugs.eclipse
                // .org/bugs/show_bug.cgi?id=130982)
                return NON_JAVA_RESOURCE;
            }
            String sourceLevel = rootInfo.project == null ? null
                    : rootInfo.project.getOption(JavaCore.COMPILER_SOURCE, true);
            String complianceLevel = rootInfo.project == null ? null
                    : rootInfo.project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
            if (Util.isValidFolderNameForPackage(res.getName(), sourceLevel, complianceLevel)) {
                return IJavaElement.PACKAGE_FRAGMENT;
            }
            return NON_JAVA_RESOURCE;
        }
        String fileName = res.getName();
        String sourceLevel = rootInfo.project == null ? null
                : rootInfo.project.getOption(JavaCore.COMPILER_SOURCE, true);
        String complianceLevel = rootInfo.project == null ? null
                : rootInfo.project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
        if (Util.isValidCompilationUnitName(fileName, sourceLevel, complianceLevel)) {
            return IJavaElement.COMPILATION_UNIT;
        } else if (Util.isValidClassFileName(fileName, sourceLevel, complianceLevel)) {
            return IJavaElement.CLASS_FILE;
        } else {
            IPath rootPath = externalPath(res);
            if ((rootInfo = rootInfo(rootPath, kind)) != null
                    && rootInfo.project.getProject().getFullPath().isPrefixOf(rootPath) /*ensure root is a root of its project (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185310)
                                                                                        */) {
                // case of proj=src=bin and resource is a jar file on the classpath
                return IJavaElement.PACKAGE_FRAGMENT_ROOT;
            } else {
                return NON_JAVA_RESOURCE;
            }
        }

    default:
        return NON_JAVA_RESOURCE;
    }
}

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

License:Open Source License

private IJavaElementDelta processResourceDelta(IResourceDelta changes) {

    try {// w  w w .j a  va  2  s.  co  m
        IJavaModel model = this.manager.getJavaModel();
        if (!model.isOpen()) {
            // force opening of java model so that java element delta are reported
            try {
                model.open(null);
            } catch (JavaModelException e) {
                if (VERBOSE) {
                    e.printStackTrace();
                }
                return null;
            }
        }
        this.state.initializeRoots(false/*not initiAfterLoad*/);
        this.currentElement = null;

        // get the workspace delta, and start processing there.
        //         IResourceDelta[] deltas = (IResourceDelta[])changes.getAffectedChildren(IResourceDelta.ADDED | IResourceDelta.REMOVED |
        // IResourceDelta.CHANGED, IContainer.INCLUDE_HIDDEN);
        //         for (int i = 0; i < deltas.length; i++) {
        //            IResourceDelta delta = deltas[i];
        //            File res = delta.getFile();
        //
        //            // find out the element type
        //            RootInfo rootInfo = null;
        //            int elementType;
        //            IProject proj = (IProject)res;
        //            boolean wasJavaProject = this.state.findJavaProject(proj.getName()) != null;
        //            boolean isJavaProject = JavaProject.hasJavaNature(proj);
        //            if (!wasJavaProject && !isJavaProject) {
        //               elementType = NON_JAVA_RESOURCE;
        //            } else {
        //               IPath rootPath = externalPath(res);
        //               rootInfo = enclosingRootInfo(rootPath, delta.getKind());
        //               if (rootInfo != null && rootInfo.isRootOfProject(rootPath)) {
        //                  elementType = IJavaElement.PACKAGE_FRAGMENT_ROOT;
        //               } else {
        //                  elementType = IJavaElement.JAVA_PROJECT;
        //               }
        //            }
        //
        //            // traverse delta
        //            traverseDelta(changes, IJavaElement.JAVA_PROJECT, null, null);
        updateCurrentDeltaAndIndex(changes, IJavaElement.COMPILATION_UNIT, null);
        //
        //            if (elementType == NON_JAVA_RESOURCE
        //                  || (wasJavaProject != isJavaProject && (delta.getKind()) == IResourceDelta.CHANGED)) { // project has changed
        // nature (description or open/closed)
        //               try {
        //                  // add child as non java resource
        //                  nonJavaResourcesChanged((JavaModel)model, delta);
        //               } catch (JavaModelException e) {
        //                  // java model could not be opened
        //               }
        //            }
        //
        //         }
        resetProjectCaches();

        return this.currentDelta;
    } finally {
        this.currentDelta = null;
    }
}

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

License:Open Source License

public synchronized Object removeInfoAndChildren(JavaElement element) throws JavaModelException {
    Object info = this.cache.peekAtInfo(element);
    if (info != null) {
        boolean wasVerbose = false;
        try {//from w ww .j a va 2 s .  c  om
            if (JavaModelCache.VERBOSE) {
                String elementType;
                switch (element.getElementType()) {
                case IJavaElement.JAVA_PROJECT:
                    elementType = "project"; //$NON-NLS-1$
                    break;
                case IJavaElement.PACKAGE_FRAGMENT_ROOT:
                    elementType = "root"; //$NON-NLS-1$
                    break;
                case IJavaElement.PACKAGE_FRAGMENT:
                    elementType = "package"; //$NON-NLS-1$
                    break;
                case IJavaElement.CLASS_FILE:
                    elementType = "class file"; //$NON-NLS-1$
                    break;
                case IJavaElement.COMPILATION_UNIT:
                    elementType = "compilation unit"; //$NON-NLS-1$
                    break;
                default:
                    elementType = "element"; //$NON-NLS-1$
                }
                System.out.println(Thread.currentThread() + " CLOSING " + elementType + " "
                        + element.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
                wasVerbose = true;
                JavaModelCache.VERBOSE = false;
            }
            element.closing(info);
            if (element instanceof IParent) {
                closeChildren(info);
            }
            this.cache.removeInfo(element);
            if (wasVerbose) {
                System.out.println(this.cache.toStringFillingRation("-> ")); //$NON-NLS-1$
            }
        } finally {
            JavaModelCache.VERBOSE = wasVerbose;
        }
        return info;
    }
    return null;
}

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

License:Open Source License

/**
 * Searches for all declarations of the methods invoked in the given element.
 * The element can be a compilation unit or a source type/method/field.
 * Reports the method declarations using the given requestor.
 *
 * @see org.eclipse.jdt.core.search.SearchEngine#searchDeclarationsOfSentMessages(org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt
 * .core.search.SearchRequestor, IProgressMonitor)
 *    for detailed comment// w  ww  .j  ava  2 s . c o m
 */
public void searchDeclarationsOfSentMessages(IJavaElement enclosingElement, SearchRequestor requestor,
        IProgressMonitor monitor) throws JavaModelException {
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchDeclarationsOfSentMessages(IJavaElement, SearchRequestor, SearchPattern, IProgressMonitor)");
        //$NON-NLS-1$
    }
    // Do not accept other kind of element type than those specified in the spec
    switch (enclosingElement.getElementType()) {
    case IJavaElement.FIELD:
    case IJavaElement.METHOD:
    case IJavaElement.TYPE:
    case IJavaElement.COMPILATION_UNIT:
        // valid element type
        break;
    default:
        throw new IllegalArgumentException();
    }
    SearchPattern pattern = new DeclarationOfReferencedMethodsPattern(enclosingElement);
    searchDeclarations(enclosingElement, requestor, pattern, monitor);
}

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:/*from  www  .j  av a 2 s  . co m*/
        return getPath(element.getParent(), relativeToRoot);
    }
}