Example usage for org.eclipse.jdt.internal.core PackageFragment getCompilationUnit

List of usage examples for org.eclipse.jdt.internal.core PackageFragment getCompilationUnit

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core PackageFragment getCompilationUnit.

Prototype

@Override
public ICompilationUnit getCompilationUnit(String cuName) 

Source Link

Usage

From source file:org.eclipse.ajdt.core.AspectJCore.java

License:Open Source License

public static IJavaElement create(String handleIdentifier, WorkingCopyOwner owner) {

    if (handleIdentifier == null) {
        return null;
    }//from www .j a v  a2s.co  m
    Map aspectsInJavaFiles = new HashMap();

    boolean isCodeElement = false;
    String codeElementHandle = ""; //$NON-NLS-1$

    int codeElementDelimPos = indexOfIgnoringEscapes(handleIdentifier, AspectElement.JEM_CODEELEMENT);
    if (codeElementDelimPos != -1) {
        isCodeElement = true;
        codeElementHandle = handleIdentifier.substring(codeElementDelimPos + 1);
        handleIdentifier = handleIdentifier.substring(0, codeElementDelimPos);
    }

    AJMementoTokenizer memento = new AJMementoTokenizer(handleIdentifier);
    while (memento.hasMoreTokens()) {
        String token = memento.nextToken();
        if ((token.charAt(0) == AspectElement.JEM_ASPECT_CU)
                || (token.charAt(0) == JavaElement.JEM_COMPILATIONUNIT)
                || (token.charAt(0) == JavaElement.JEM_CLASSFILE)) {

            int index;
            if (token.charAt(0) == AspectElement.JEM_ASPECT_CU) {
                index = handleIdentifier.indexOf(AspectElement.JEM_ASPECT_CU);
            } else if (token.charAt(0) == JavaElement.JEM_COMPILATIONUNIT) {
                index = handleIdentifier.indexOf(JavaElement.JEM_COMPILATIONUNIT);
            } else { // JEM_CLASSFILE 
                index = handleIdentifier.indexOf(JavaElement.JEM_CLASSFILE);
            }

            if (index != -1) {
                IJavaElement je = JavaCore.create(handleIdentifier.substring(0, index));
                if (je instanceof PackageFragment) {
                    PackageFragment pf = (PackageFragment) je;
                    String cuName = handleIdentifier.substring(index + 1);
                    int ind1 = cuName.indexOf(JavaElement.JEM_TYPE);
                    if (ind1 != -1) {
                        cuName = cuName.substring(0, ind1);
                    }
                    int ind2 = cuName.indexOf(AspectElement.JEM_ASPECT_TYPE);
                    if (ind2 != -1) {
                        cuName = cuName.substring(0, ind2);
                    }
                    int ind3 = cuName.indexOf(AspectElement.JEM_ITD_METHOD);
                    if (ind3 != -1) {
                        cuName = cuName.substring(0, ind3);
                    }
                    ind3 = cuName.indexOf(AspectElement.JEM_ITD_FIELD);
                    if (ind3 != -1) {
                        cuName = cuName.substring(0, ind3);
                    }
                    int ind4 = cuName.indexOf(AspectElement.JEM_DECLARE);
                    if (ind4 != -1) {
                        cuName = cuName.substring(0, ind4);
                    }
                    int ind5 = cuName.indexOf(AspectElement.JEM_IMPORTDECLARATION);
                    if (ind5 != -1) {
                        cuName = cuName.substring(0, ind5);
                    }
                    int ind6 = cuName.indexOf(AspectElement.JEM_PACKAGEDECLARATION);
                    if (ind6 != -1) {
                        cuName = cuName.substring(0, ind6);
                    }
                    if (CoreUtils.ASPECTJ_SOURCE_ONLY_FILTER.accept(cuName)) {
                        // no need to use a cuprovider because we know this
                        // is an AJCompilationUnit
                        JavaElement cu = new AJCompilationUnit(pf, cuName, owner);
                        token = memento.nextToken();
                        if (!memento.hasMoreTokens()) {
                            return cu;
                        }
                        IJavaElement restEl = cu.getHandleFromMemento(memento.nextToken(), memento, owner);
                        if (restEl != null) {
                            if (isCodeElement) {
                                // there was an AJCodeElement at the end of
                                // the handle
                                IJavaElement codeEl = getCodeElement(codeElementHandle, (JavaElement) restEl);
                                if (codeEl != null) {
                                    return codeEl;
                                }
                            }
                            return restEl;
                        }
                    } else {
                        // Use the default working copy owner for Java elements
                        IJavaElement restEl = pf.getHandleFromMemento(token, memento,
                                DefaultWorkingCopyOwner.PRIMARY);
                        if (restEl != null) {
                            if (isCodeElement) {
                                // there was an AJCodeElement at the end of
                                // the handle
                                IJavaElement codeEl = getCodeElement(codeElementHandle, (JavaElement) restEl);
                                if (codeEl != null) {
                                    return codeEl;
                                }
                            }
                            return restEl;
                        } else if (ind2 != -1) { // An aspect in a .java file...
                            int index3 = handleIdentifier.indexOf(AspectElement.JEM_ASPECT_TYPE);
                            String aspectName = handleIdentifier.substring(index3 + 1);
                            boolean identifierIsAspect = true;
                            int ind7 = aspectName.indexOf(AspectElement.JEM_DECLARE);
                            if (ind7 != -1) {
                                aspectName = aspectName.substring(0, ind7);
                                identifierIsAspect = false;
                            }
                            int ind8 = aspectName.indexOf(AspectElement.JEM_ADVICE);
                            if (ind8 != -1) {
                                aspectName = aspectName.substring(0, ind8);
                                identifierIsAspect = false;
                            }
                            int ind9 = aspectName.indexOf(AspectElement.JEM_ITD_METHOD);
                            if (ind9 != -1) {
                                aspectName = aspectName.substring(0, ind9);
                                identifierIsAspect = false;
                            }
                            ind9 = aspectName.indexOf(AspectElement.JEM_ITD_FIELD);
                            if (ind9 != -1) {
                                aspectName = aspectName.substring(0, ind9);
                                identifierIsAspect = false;
                            }
                            int ind10 = aspectName.indexOf(AspectElement.JEM_ASPECT_TYPE);
                            if (ind10 != -1) {
                                aspectName = aspectName.substring(0, ind10);
                                identifierIsAspect = false;
                            }
                            int ind11 = aspectName.indexOf(AspectElement.JEM_TYPE);
                            if (ind11 != -1) {
                                aspectName = aspectName.substring(0, ind11);
                                identifierIsAspect = false;
                            }
                            int ind12 = aspectName.indexOf(AspectElement.JEM_FIELD);
                            if (ind12 != -1) {
                                aspectName = aspectName.substring(0, ind12);
                                identifierIsAspect = false;
                            }
                            int ind13 = aspectName.indexOf(AspectElement.JEM_METHOD);
                            if (ind13 != -1) {
                                aspectName = aspectName.substring(0, ind13);
                                identifierIsAspect = false;
                            }
                            int ind14 = aspectName.indexOf(AspectElement.JEM_POINTCUT);
                            if (ind14 != -1) {
                                aspectName = aspectName.substring(0, ind14);
                                identifierIsAspect = false;
                            }
                            IOpenable openable;
                            if (cuName.endsWith(".class")) {
                                openable = pf.getClassFile(cuName);
                            } else {
                                openable = pf.getCompilationUnit(cuName);
                            }
                            List l;
                            if (aspectsInJavaFiles.get(openable) instanceof List) {
                                l = (List) aspectsInJavaFiles.get(openable);
                            } else {
                                l = new ArrayList();
                                aspectsInJavaFiles.put(openable, l);
                            }
                            JavaElement aspectEl = null;
                            for (Iterator iter = l.iterator(); iter.hasNext();) {
                                AspectElement element = (AspectElement) iter.next();
                                if (element.getElementName().equals(aspectName)) {
                                    aspectEl = element;
                                }
                            }
                            if (aspectEl == null) {
                                if (openable instanceof ClassFile) {
                                    ClassFile cOpenable = (ClassFile) openable;
                                    aspectEl = new BinaryAspectElement((JavaElement) cOpenable, aspectName);
                                } else {
                                    aspectEl = new AspectElement((JavaElement) openable, aspectName);
                                }
                                l.add(aspectEl);
                            }
                            int afterAspectIndex = index3 + aspectName.length() + 1;

                            if (identifierIsAspect) {
                                return aspectEl;
                            } else {
                                memento.setIndexTo(afterAspectIndex);
                                return aspectEl.getHandleFromMemento(memento.nextToken(), memento, owner);
                            }
                        }
                    }
                }
            }
        }
    }
    // XXX can we get here???
    if (isCodeElement) {
        // an injar aspect with no parent
        return new AJInjarElement(codeElementHandle);
    }
    return JavaCore.create(handleIdentifier);
}

From source file:org.eclipse.jdt.internal.core.CopyResourceElementsOperation.java

License:Open Source License

/**
 * Copies/moves a package fragment with the name <code>newName</code>
 * to the destination package.<br>
 *
 * @exception JavaModelException if the operation is unable to
 * complete//from   w  w w  .  ja va2s. co  m
 */
private void processPackageFragmentResource(PackageFragment source, PackageFragmentRoot root, String newName)
        throws JavaModelException {
    try {
        String[] newFragName = (newName == null) ? source.names : Util.getTrimmedSimpleNames(newName);
        PackageFragment newFrag = root.getPackageFragment(newFragName);
        IResource[] resources = collectResourcesOfInterest(source);

        // if isMove() can we move the folder itself ? (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=22458)
        boolean shouldMoveFolder = isMove() && !newFrag.resource().exists(); // if new pkg fragment exists, it is an override
        IFolder srcFolder = (IFolder) source.resource();
        IPath destPath = newFrag.getPath();
        if (shouldMoveFolder) {
            // check if destination is not included in source
            if (srcFolder.getFullPath().isPrefixOf(destPath)) {
                shouldMoveFolder = false;
            } else {
                // check if there are no sub-packages
                IResource[] members = srcFolder.members();
                for (int i = 0; i < members.length; i++) {
                    if (members[i] instanceof IFolder) {
                        shouldMoveFolder = false;
                        break;
                    }
                }
            }
        }
        boolean containsReadOnlySubPackageFragments = createNeededPackageFragments(
                (IContainer) source.parent.resource(), root, newFragName, shouldMoveFolder);
        boolean sourceIsReadOnly = Util.isReadOnly(srcFolder);

        // Process resources
        if (shouldMoveFolder) {
            // move underlying resource
            // TODO Revisit once bug 43044 is fixed
            if (sourceIsReadOnly) {
                Util.setReadOnly(srcFolder, false);
            }
            srcFolder.move(destPath, this.force, true /* keep history */, getSubProgressMonitor(1));
            if (sourceIsReadOnly) {
                Util.setReadOnly(srcFolder, true);
            }
            setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
        } else {
            // process the leaf resources
            if (resources.length > 0) {
                if (isRename()) {
                    if (!destPath.equals(source.getPath())) {
                        moveResources(resources, destPath);
                    }
                } else if (isMove()) {
                    // we need to delete this resource if this operation wants to override existing resources
                    for (int i = 0, max = resources.length; i < max; i++) {
                        IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot()
                                .findMember(destPath.append(resources[i].getName()));
                        if (destinationResource != null) {
                            if (this.force) {
                                deleteResource(destinationResource, IResource.KEEP_HISTORY);
                            } else {
                                throw new JavaModelException(
                                        new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION,
                                                Messages.bind(Messages.status_nameCollision,
                                                        destinationResource.getFullPath().toString())));
                            }
                        }
                    }
                    moveResources(resources, destPath);
                } else {
                    // we need to delete this resource if this operation wants to override existing resources
                    for (int i = 0, max = resources.length; i < max; i++) {
                        IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot()
                                .findMember(destPath.append(resources[i].getName()));
                        if (destinationResource != null) {
                            if (this.force) {
                                // we need to delete this resource if this operation wants to override existing resources
                                deleteResource(destinationResource, IResource.KEEP_HISTORY);
                            } else {
                                throw new JavaModelException(
                                        new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION,
                                                Messages.bind(Messages.status_nameCollision,
                                                        destinationResource.getFullPath().toString())));
                            }
                        }
                    }
                    copyResources(resources, destPath);
                }
            }
        }

        // Update package statement in compilation unit if needed
        if (!Util.equalArraysOrNull(newFragName, source.names)) { // if package has been renamed, update the compilation units
            char[][] inclusionPatterns = root.fullInclusionPatternChars();
            char[][] exclusionPatterns = root.fullExclusionPatternChars();
            for (int i = 0; i < resources.length; i++) {
                String resourceName = resources[i].getName();
                if (Util.isJavaLikeFileName(resourceName)) {
                    // we only consider potential compilation units
                    ICompilationUnit cu = newFrag.getCompilationUnit(resourceName);
                    if (Util.isExcluded(cu.getPath(), inclusionPatterns, exclusionPatterns,
                            false/*not a folder*/))
                        continue;
                    this.parser.setSource(cu);
                    CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
                    AST ast = astCU.getAST();
                    ASTRewrite rewrite = ASTRewrite.create(ast);
                    updatePackageStatement(astCU, newFragName, rewrite, cu);
                    TextEdit edits = rewrite.rewriteAST();
                    applyTextEdit(cu, edits);
                    cu.save(null, false);
                }
            }
        }

        // Discard empty old package (if still empty after the rename)
        boolean isEmpty = true;
        if (isMove()) {
            // delete remaining files in this package (.class file in the case where Proj=src=bin)
            // in case of a copy
            updateReadOnlyPackageFragmentsForMove((IContainer) source.parent.resource(), root, newFragName,
                    sourceIsReadOnly);
            if (srcFolder.exists()) {
                IResource[] remaining = srcFolder.members();
                for (int i = 0, length = remaining.length; i < length; i++) {
                    IResource file = remaining[i];
                    if (file instanceof IFile) {
                        if (Util.isReadOnly(file)) {
                            Util.setReadOnly(file, false);
                        }
                        deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY);
                    } else {
                        isEmpty = false;
                    }
                }
            }
            if (isEmpty) {
                IResource rootResource;
                // check if source is included in destination
                if (destPath.isPrefixOf(srcFolder.getFullPath())) {
                    rootResource = newFrag.resource();
                } else {
                    rootResource = source.parent.resource();
                }

                // delete recursively empty folders
                deleteEmptyPackageFragment(source, false, rootResource);
            }
        } else if (containsReadOnlySubPackageFragments) {
            // in case of a copy
            updateReadOnlyPackageFragmentsForCopy((IContainer) source.parent.resource(), root, newFragName);
        }
        // workaround for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=24505
        if (isEmpty && isMove() && !(Util.isExcluded(source) || Util.isExcluded(newFrag))) {
            IJavaProject sourceProject = source.getJavaProject();
            getDeltaFor(sourceProject).movedFrom(source, newFrag);
            IJavaProject destProject = newFrag.getJavaProject();
            getDeltaFor(destProject).movedTo(newFrag, source);
        }
    } catch (JavaModelException e) {
        throw e;
    } catch (CoreException ce) {
        throw new JavaModelException(ce);
    }
}

From source file:org.eclipse.jdt.internal.core.CopyResourceElementsOperation.java

License:Open Source License

private void saveContent(PackageFragment dest, String destName, TextEdit edits, String sourceEncoding,
        IFile destFile) throws JavaModelException {
    try {//  ww w .  j ava2s. c  o  m
        // TODO (frederic) remove when bug 67606 will be fixed (bug 67823)
        // fix bug 66898
        if (sourceEncoding != null)
            destFile.setCharset(sourceEncoding, this.progressMonitor);
        // end todo
    } catch (CoreException ce) {
        // use no encoding
    }
    // when the file was copied, its read-only flag was preserved -> temporary set it to false
    // note this doesn't interfere with repository providers as this is a new resource that cannot be under
    // version control yet
    Util.setReadOnly(destFile, false);
    ICompilationUnit destCU = dest.getCompilationUnit(destName);
    applyTextEdit(destCU, edits);
    destCU.save(getSubProgressMonitor(1), this.force);
}

From source file:org.jboss.tools.hibernate.jpt.ui.internal.persistence.details.HibernatePersistenceUnitClassesComposite.java

License:Open Source License

protected IFilter createPackageFilter() {
    return new IFilter() {

        public boolean select(Object element) {
            if (element instanceof PackageFragment) {
                PackageFragment pf = (PackageFragment) element;
                return pf.getCompilationUnit(Hibernate.PACKAGE_INFO_JAVA).exists();

            }/*from  w  w  w  .  j a  va 2 s .  co  m*/
            return false;
        }
    };
}