Example usage for org.eclipse.jdt.core IPackageFragment getClassFiles

List of usage examples for org.eclipse.jdt.core IPackageFragment getClassFiles

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragment getClassFiles.

Prototype

@Deprecated
IClassFile[] getClassFiles() throws JavaModelException;

Source Link

Document

Returns all of the ordinary class files in this package fragment.

Usage

From source file:com.codenvy.ide.ext.java.server.JavaNavigation.java

License:Open Source License

protected Object[] getPackageContent(IPackageFragment fragment) throws JavaModelException {

    // hierarchical package mode
    ArrayList<Object> result = new ArrayList<Object>();

    getHierarchicalPackageChildren((IPackageFragmentRoot) fragment.getParent(), fragment, result);
    IClassFile[] classFiles = fragment.getClassFiles();
    List<IClassFile> filtered = new ArrayList<>();
    //filter inner classes
    for (IClassFile classFile : classFiles) {
        if (!classFile.getElementName().contains("$")) {
            filtered.add(classFile);//from w ww . ja va 2s .  c  om
        }
    }
    Object[] nonPackages = concatenate(filtered.toArray(), fragment.getNonJavaResources());
    if (result.isEmpty())
        return nonPackages;
    Collections.addAll(result, nonPackages);
    return result.toArray();
}

From source file:com.drgarbage.controlflowgraphfactory.actions.GenerateGraphsAction.java

License:Apache License

public void run(IAction action) {
    if (selection == null || !(selection instanceof TreeSelection)) {
        return;//from   ww  w  .j av  a  2s . co  m
    }

    final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

    ExportGraphFileFolderSelectionDialog dlg = openSelectFolderdialog(targetPart.getSite().getShell(), root);
    dlg.open();
    Object ret = dlg.getFirstResult();
    if (ret == null) {
        return;
    }

    final LocalFile localFile = (LocalFile) ret;
    graphSpecification = dlg.getGraphSpecification();

    TreeSelection treeSel = (TreeSelection) selection;
    final Object o = treeSel.getFirstElement();
    IType type = null;
    if (o instanceof IType) {
        type = (IType) o;
    }

    try {
        if (type == null) {
            final IPackageFragment pack = (IPackageFragment) o;
            final ExportProgressMonitorDialog monitor0 = new ExportProgressMonitorDialog(
                    targetPart.getSite().getShell());
            monitor0.setErrorMsg("An error has occured while processing the package '" + pack.getElementName()
                    + "'." + CoreMessages.ExceptionAdditionalMessage);
            monitor0.run(false, true, new WorkspaceModifyOperation() {

                /* (non-Javadoc)
                 * @see org.eclipse.ui.actions.WorkspaceModifyOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
                 */
                @Override
                protected void execute(IProgressMonitor monitor)
                        throws CoreException, InvocationTargetException, InterruptedException {

                    List<IType> listOfTypes = new ArrayList<IType>();

                    /*
                     * It is possible that a package fragment contains only compilation units 
                     * (in other words, its kind is K_SOURCE), in which case this method returns 
                     * an empty collection.
                     */
                    IClassFile[] classFiles = pack.getClassFiles();
                    for (IClassFile f : classFiles) {
                        listOfTypes.add(f.getType());
                    }

                    ICompilationUnit[] compilationUnits = pack.getCompilationUnits();
                    for (ICompilationUnit u : compilationUnits) {
                        IType unitTypes[] = u.getTypes();
                        for (IType type : unitTypes) {
                            listOfTypes.add(type);
                        }
                    }

                    final int ticks = classFiles.length;
                    monitor.beginTask(ControlFlowFactoryMessages.ProgressDialogCreateGraphs, ticks);

                    boolean yes_To_All = false;
                    for (IType t : listOfTypes) {
                        monitor.subTask(t.getElementName());
                        Result res = createGraphsForType(t, localFile, root, false, yes_To_All, true);
                        if (res == Result.NO_TO_ALL) {
                            monitor.done();
                            return;
                        } else if (res == Result.YES_TO_ALL) {
                            yes_To_All = true;
                        } else if (res == Result.ERROR) {
                            monitor0.setErrorDuringExecution(true);
                        }

                        monitor.worked(1);
                    }

                    monitor.done();
                }
            });

        } else {
            Result res = createGraphsForType(type, localFile, root, true, false, false);
            if (res == Result.ERROR) {
                Messages.warning("An error has occured while processing the class file '"
                        + type.getElementName() + "'." + CoreMessages.ExceptionAdditionalMessage);
            }
        }

    } catch (InvocationTargetException e) {
        StringBuffer buf = new StringBuffer("InvocationTargetException: ");
        Throwable th = e.getTargetException();
        if (th != null) {
            buf.append(th.toString());
        }

        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, buf.toString(), e));
        Messages.error(buf.toString() + CoreMessages.ExceptionAdditionalMessage);
        return;
    } catch (InterruptedException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        return;
    } catch (JavaModelException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        return;
    } finally {
        dlg = null;
    }
}

From source file:com.mountainminds.eclemma.internal.core.analysis.TypeTraverser.java

License:Open Source License

private void processPackageFragment(ITypeVisitor visitor, IPackageFragment fragment, IProgressMonitor monitor)
        throws JavaModelException {
    switch (fragment.getKind()) {
    case IPackageFragmentRoot.K_SOURCE:
        final ICompilationUnit[] units = fragment.getCompilationUnits();
        monitor.beginTask("", units.length); //$NON-NLS-1$
        for (final ICompilationUnit unit : units) {
            if (monitor.isCanceled()) {
                break;
            }/*from   ww w.ja v a  2  s .co  m*/
            processCompilationUnit(visitor, unit, monitor);
            monitor.worked(1);
        }
        break;
    case IPackageFragmentRoot.K_BINARY:
        final IClassFile[] classfiles = fragment.getClassFiles();
        monitor.beginTask("", classfiles.length); //$NON-NLS-1$
        for (final IClassFile classfile : classfiles) {
            if (monitor.isCanceled()) {
                break;
            }
            processClassFile(visitor, classfile, monitor);
            monitor.worked(1);
        }
        break;
    }
    monitor.done();
}

From source file:com.redhat.ceylon.eclipse.core.model.JDTModelLoader.java

License:Open Source License

@Override
public synchronized boolean loadPackage(Module module, String packageName, boolean loadDeclarations) {
    packageName = Util.quoteJavaKeywords(packageName);
    if (loadDeclarations && !loadedPackages.add(cacheKeyByModule(module, packageName))) {
        return true;
    }/* w w  w.j  a va 2 s. c o  m*/

    if (module instanceof JDTModule) {
        JDTModule jdtModule = (JDTModule) module;
        List<IPackageFragmentRoot> roots = jdtModule.getPackageFragmentRoots();
        IPackageFragment packageFragment = null;
        for (IPackageFragmentRoot root : roots) {
            // skip packages that are not present
            if (!root.exists() || !javaProject.isOnClasspath(root))
                continue;
            try {
                IClasspathEntry entry = root.getRawClasspathEntry();

                //TODO: is the following really necessary?
                //Note that getContentKind() returns an undefined
                //value for a classpath container or variable
                if (entry.getEntryKind() != IClasspathEntry.CPE_CONTAINER
                        && entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE
                        && entry.getContentKind() == IPackageFragmentRoot.K_SOURCE
                        && !CeylonBuilder.isCeylonSourceEntry(entry)) {
                    continue;
                }

                packageFragment = root.getPackageFragment(packageName);
                if (!packageFragment.exists()) {
                    continue;
                }
            } catch (JavaModelException e) {
                if (!e.isDoesNotExist()) {
                    e.printStackTrace();
                }
                continue;
            }
            if (!loadDeclarations) {
                // we found the package
                return true;
            }

            // we have a few virtual types in java.lang that we need to load but they are not listed from class files
            if (module.getNameAsString().equals(JAVA_BASE_MODULE_NAME) && packageName.equals("java.lang")) {
                loadJavaBaseArrays();
            }

            IClassFile[] classFiles = new IClassFile[] {};
            org.eclipse.jdt.core.ICompilationUnit[] compilationUnits = new org.eclipse.jdt.core.ICompilationUnit[] {};
            try {
                classFiles = packageFragment.getClassFiles();
            } catch (JavaModelException e) {
                e.printStackTrace();
            }
            try {
                compilationUnits = packageFragment.getCompilationUnits();
            } catch (JavaModelException e) {
                e.printStackTrace();
            }

            List<IType> typesToLoad = new LinkedList<>();
            for (IClassFile classFile : classFiles) {
                IType type = classFile.getType();
                typesToLoad.add(type);
            }

            for (org.eclipse.jdt.core.ICompilationUnit compilationUnit : compilationUnits) {
                // skip removed CUs
                if (!compilationUnit.exists())
                    continue;
                try {
                    for (IType type : compilationUnit.getTypes()) {
                        typesToLoad.add(type);
                    }
                } catch (JavaModelException e) {
                    e.printStackTrace();
                }
            }

            for (IType type : typesToLoad) {
                String typeFullyQualifiedName = type.getFullyQualifiedName();
                String[] nameParts = typeFullyQualifiedName.split("\\.");
                String typeQualifiedName = nameParts[nameParts.length - 1];
                // only top-levels are added in source declarations
                if (typeQualifiedName.indexOf('$') > 0) {
                    continue;
                }

                if (type.exists()
                        && !sourceDeclarations.containsKey(getToplevelQualifiedName(
                                type.getPackageFragment().getElementName(), typeFullyQualifiedName))
                        && !isTypeHidden(module, typeFullyQualifiedName)) {
                    convertToDeclaration(module, typeFullyQualifiedName, DeclarationType.VALUE);
                }
            }
        }
    }
    return false;
}

From source file:com.redhat.ceylon.eclipse.core.model.loader.JDTModelLoader.java

License:Open Source License

@Override
public synchronized boolean loadPackage(String packageName, boolean loadDeclarations) {
    packageName = Util.quoteJavaKeywords(packageName);
    if (loadDeclarations && !loadedPackages.add(packageName)) {
        return true;
    }//w ww .ja v a 2  s.  c  o  m
    Module module = lookupModuleInternal(packageName);

    if (module instanceof JDTModule) {
        JDTModule jdtModule = (JDTModule) module;
        List<IPackageFragmentRoot> roots = jdtModule.getPackageFragmentRoots();
        IPackageFragment packageFragment = null;
        for (IPackageFragmentRoot root : roots) {
            // skip packages that are not present
            if (!root.exists())
                continue;
            try {
                IClasspathEntry entry = root.getRawClasspathEntry();

                //TODO: is the following really necessary?
                //Note that getContentKind() returns an undefined
                //value for a classpath container or variable
                if (entry.getEntryKind() != IClasspathEntry.CPE_CONTAINER
                        && entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE
                        && entry.getContentKind() == IPackageFragmentRoot.K_SOURCE
                        && !CeylonBuilder.isCeylonSourceEntry(entry)) {
                    continue;
                }

                packageFragment = root.getPackageFragment(packageName);
                if (packageFragment.exists()) {
                    if (!loadDeclarations) {
                        // we found the package
                        return true;
                    } else {
                        try {
                            for (IClassFile classFile : packageFragment.getClassFiles()) {
                                // skip removed class files
                                if (!classFile.exists())
                                    continue;
                                IType type = classFile.getType();
                                if (type.exists() && !type.isMember()
                                        && !sourceDeclarations.containsKey(
                                                getQualifiedName(type.getPackageFragment().getElementName(),
                                                        type.getTypeQualifiedName()))) {
                                    convertToDeclaration(type.getFullyQualifiedName(), DeclarationType.VALUE);
                                }
                            }
                            for (org.eclipse.jdt.core.ICompilationUnit compilationUnit : packageFragment
                                    .getCompilationUnits()) {
                                // skip removed CUs
                                if (!compilationUnit.exists())
                                    continue;
                                for (IType type : compilationUnit.getTypes()) {
                                    if (type.exists() && !type.isMember()
                                            && !sourceDeclarations.containsKey(
                                                    getQualifiedName(type.getPackageFragment().getElementName(),
                                                            type.getTypeQualifiedName()))) {
                                        convertToDeclaration(type.getFullyQualifiedName(),
                                                DeclarationType.VALUE);
                                    }
                                }
                            }
                        } catch (JavaModelException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (JavaModelException e) {
                e.printStackTrace();
            }
        }
    }
    return false;
}

From source file:com.siteview.mde.internal.ui.search.dependencies.PackageFinder.java

License:Open Source License

private static void addClassFilesFromResource(IResource res, List classFiles) {
    if (res == null)
        return;/* ww w . ja v a 2s  .c  om*/
    Stack stack = new Stack();
    if (res instanceof IContainer) {
        stack.push(res);
        while (!stack.isEmpty()) {
            try {
                IResource[] children = ((IContainer) stack.pop()).members();
                for (int i = 0; i < children.length; i++)
                    if (children[i] instanceof IFile && "class".equals(children[i].getFileExtension())) { //$NON-NLS-1$
                        classFiles.add(JavaCore.createClassFileFrom((IFile) children[i]));
                    } else if (children[i] instanceof IContainer)
                        stack.push(children[i]);
            } catch (CoreException e) {
            }
        }
    } else if (res instanceof IFile) {
        if (res.getFileExtension().equals("jar") || res.getFileExtension().equals("zip")) { //$NON-NLS-1$ //$NON-NLS-2$
            IPackageFragmentRoot root = JavaCore.create(res.getProject()).getPackageFragmentRoot(res);
            if (root == null)
                return;
            try {
                IJavaElement[] children = root.getChildren();
                for (int i = 0; i < children.length; i++) {
                    if (children[i] instanceof IPackageFragment) {
                        IPackageFragment frag = (IPackageFragment) children[i];
                        IClassFile[] files = frag.getClassFiles();
                        for (int j = 0; j < files.length; j++)
                            classFiles.add(files[j]);
                    }
                }
            } catch (JavaModelException e) {
            }
        } else if (res.getFileExtension().equals("class")) //$NON-NLS-1$
            JavaCore.createClassFileFrom((IFile) res);
    }
}

From source file:edu.buffalo.cse.green.editor.model.commands.AddJavaElementCommand.java

License:Open Source License

/**
 * Opens all the compilation units in the given
 * <code>IPackageFragment</code>.
 *//* www.  j  av  a2  s .c o  m*/
private void openPackage(RootModel model, IPackageFragment packFrag) throws JavaModelException {
    ICompilationUnit[] cus = packFrag.getCompilationUnits();
    IClassFile[] classFiles = packFrag.getClassFiles();

    for (ICompilationUnit cu : cus) {
        openCU(model, cu);
    }

    for (IClassFile classFile : classFiles) {
        openClass(model, classFile);
    }
}

From source file:eldaEditor.dialogs.TransitionPropertiesInputDialog.java

License:Open Source License

private List fillExceptionCombo(Combo exceptionComnbo) {
    List exceptionList = new ArrayList<String>();
    // creo il javaProject
    IJavaProject jProject = JavaCore.create(project);
    try {//  w w  w .j a va  2  s.co  m
        // recupero il jar di actiware
        IPackageFragmentRoot jar = jProject.findPackageFragmentRoot(JavaCore.getResolvedVariablePath(
                JavaCore.newVariableEntry(CodeGenerator.frameworkPath, null, null).getPath()));

        for (int i = 1; i < jar.getChildren().length; i++) {
            IPackageFragment jarFragment = (IPackageFragment) JavaCore
                    .create(jar.getChildren()[i].getHandleIdentifier());
            if (jarFragment.getElementName().startsWith("eldaframework.eldaevent.exception")) {
                IClassFile[] classArray = jarFragment.getClassFiles();
                for (int j = 0; j < classArray.length; j++) {
                    String name = classArray[j].getElementName().replaceAll(".class", "");
                    exceptionComnbo.add(name);
                    exceptionList.add(name);
                }
            }
        }
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return exceptionList;
}

From source file:fede.workspace.eclipse.java.fields.MethodField.java

License:Apache License

/**
 * Choose method./*from  w w w.  ja  v  a 2 s .  c  om*/
 * 
 * @return the i method
 */
private IMethod chooseMethod() {
    IJavaElement[] packages = getPackageFragment();

    if (packages == null) {
        packages = new IJavaElement[0];
    }

    StandardJavaElementContentProvider standardJavaElementContentProvider = new StandardJavaElementContentProvider(
            true) {
        @Override
        public Object[] getChildren(Object element) {
            if (element instanceof IJavaElement[]) {
                return (Object[]) element;
            }
            if (element instanceof IPackageFragment) {
                try {
                    return mygetPackageContents((IPackageFragment) element);
                } catch (JavaModelException e) {
                    return new Object[0];
                }
            }

            return super.getChildren(element);
        }

        private Object[] mygetPackageContents(IPackageFragment fragment) throws JavaModelException {
            List<IType> types = new ArrayList<IType>();
            if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
                ICompilationUnit[] cu = fragment.getCompilationUnits();
                for (ICompilationUnit oneCu : cu) {
                    types.addAll(Arrays.asList(oneCu.getTypes()));
                }
                return types.toArray();
                // concatenate(fragment.getCompilationUnits(),
                // fragment.getNonJavaResources());
            }
            IClassFile[] cfs = fragment.getClassFiles();
            for (IClassFile cf : cfs) {
                types.add(cf.getType());
            }
            return types.toArray();
            // return concatenate(fragment.getClassFiles(),
            // fragment.getNonJavaResources());
        }

        @Override
        public boolean hasChildren(Object element) {
            if (element instanceof IJavaElement[]) {
                return true;
            }
            return super.hasChildren(element);
        }
    };
    ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(packageTable.getShell(),
            JAVA_ELEMENT_LABEL_PROVIDER, standardJavaElementContentProvider);
    // dialog.setIgnoreCase(false);
    dialog.setTitle(NewWizardMessages.NewTypeWizardPage_ChoosePackageDialog_title);
    dialog.setMessage(NewWizardMessages.NewTypeWizardPage_ChoosePackageDialog_description);
    dialog.setEmptyListMessage(NewWizardMessages.NewTypeWizardPage_ChoosePackageDialog_empty);
    dialog.setAllowMultiple(false);
    dialog.setDoubleClickSelects(false);
    dialog.setValidator(new ISelectionStatusValidator() {
        public IStatus validate(Object[] selection) {
            if (selection != null && selection.length == 1 && selection[0] instanceof IMethod) {
                return Status.OK_STATUS;
            }
            return new Status(IStatus.ERROR, WSPlugin.PLUGIN_ID, 0, "Select a method", null);
        }
    });

    dialog.setInput(packages);

    if (methodSelected != null) {
        dialog.setInitialSelections(new Object[] { methodSelected });
    }

    if (dialog.open() == Window.OK) {
        return (IMethod) dialog.getFirstResult();
    }
    return null;
}

From source file:fr.obeo.ariadne.ide.connector.java.internal.explorer.JavaExplorer.java

License:Open Source License

/**
 * Explores the given package located in the given classpath entry of the currently analyzed Java project
 * in order to extract Ariadne concept.//w w w  .  j a  v  a  2  s  .co m
 * 
 * @param classpathEntry
 *            The classpath entry
 * @param iPackageFragment
 *            The package
 * @param monitor
 *            The progress monitor
 */
private void explorePackage(ClasspathEntry classpathEntry, IPackageFragment iPackageFragment,
        IProgressMonitor monitor) {
    try {
        // Find or create matching types container
        TypesContainer typesContainer = null;
        List<TypesContainer> typesContainers = classpathEntry.getTypesContainers();
        for (TypesContainer aTypesContainer : typesContainers) {
            if (aTypesContainer.getName().equals(iPackageFragment.getElementName())) {
                typesContainer = aTypesContainer;
                break;
            }
        }

        if (typesContainer == null) {
            typesContainer = CodeFactory.eINSTANCE.createTypesContainer();
            typesContainer.setName(iPackageFragment.getElementName());
            classpathEntry.getTypesContainers().add(typesContainer);
        }

        String attachedJavadoc = iPackageFragment.getAttachedJavadoc(monitor);
        typesContainer.setDescription(attachedJavadoc);

        if (iPackageFragment.getKind() == IPackageFragmentRoot.K_BINARY) {
            IClassFile[] classFiles = iPackageFragment.getClassFiles();
            for (IClassFile iClassFile : classFiles) {
                this.exploreType(iClassFile.getType(), typesContainer, monitor);
            }
        } else if (iPackageFragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
            ICompilationUnit[] compilationUnits = iPackageFragment.getCompilationUnits();
            for (ICompilationUnit iCompilationUnit : compilationUnits) {
                IType[] allTypes = iCompilationUnit.getAllTypes();
                for (IType iType : allTypes) {
                    Type type = this.exploreType(iType, typesContainer, monitor);

                    IResource resource = iType.getResource();
                    IProject project = resource.getProject();

                    if (RepositoryProvider.isShared(project)) {
                        RepositoryProvider provider = RepositoryProvider.getProvider(project);
                        IFileHistoryProvider fileHistoryProvider = provider.getFileHistoryProvider();
                        IFileHistory fileHistory = fileHistoryProvider.getFileHistoryFor(resource,
                                IFileHistoryProvider.NONE, monitor);
                        IFileRevision[] fileRevisions = fileHistory.getFileRevisions();
                        for (IFileRevision iFileRevision : fileRevisions) {
                            String identifier = iFileRevision.getContentIdentifier();

                            List<Repository> repositories = this.ariadneProject.getRepositories();
                            for (Repository repository : repositories) {
                                List<Commit> commits = repository.getCommits();
                                for (Commit commit : commits) {
                                    if (commit.getId().equals(identifier)) {
                                        // Link the commit to the type created
                                        List<ResourceChange> resourceChanges = commit.getResourceChanges();
                                        for (ResourceChange resourceChange : resourceChanges) {
                                            if (resourceChange.getPath()
                                                    .equals(iFileRevision.getURI().toString())
                                                    || resourceChange.getPath()
                                                            .endsWith(resource.getFullPath().toString())) {
                                                resourceChange.setVersionedElement(type);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
}