Example usage for org.eclipse.jdt.core ICompilationUnit getImports

List of usage examples for org.eclipse.jdt.core ICompilationUnit getImports

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ICompilationUnit getImports.

Prototype

IImportDeclaration[] getImports() throws JavaModelException;

Source Link

Document

Returns the import declarations in this compilation unit in the order in which they appear in the source.

Usage

From source file:ar.com.fluxit.jqa.utils.JdtUtils.java

License:Open Source License

private static Collection<CommonDescriptor> collectCommonTypes(ICompilationUnit compilationUnit) {
    try {//from  w  ww. j a va2s  . co  m
        Collection<CommonDescriptor> result = new ArrayList<CommonDescriptor>();
        for (IImportDeclaration importDeclaration : compilationUnit.getImports()) {
            result.add(new CommonDescriptor(getCommonTypeName(importDeclaration)));
        }
        return result;
    } catch (JavaModelException e) {
        throw new IllegalStateException("Error while processing common types", e);
    }
}

From source file:com.curlap.orb.plugin.common.JavaElementSearcher.java

License:Open Source License

protected Set<String> createPackageNameMask(ICompilationUnit target) throws JavaModelException {
    Set<String> mask = new HashSet<String>();
    //TODO: move to constants.
    String prefix = "java";

    IImportDeclaration[] impDecs = target.getImports();
    for (IImportDeclaration impDec : impDecs)
        if (!impDec.getElementName().startsWith(prefix))
            mask.add(impDec.getElementName());

    return mask;//from   ww w.ja  va2 s  .co  m
}

From source file:com.idega.eclipse.ejbwizards.BeanCreator.java

License:Open Source License

private void fillImportMap(ICompilationUnit iUnit) {
    if (this.importMap == null) {
        this.importMap = new HashMap();
    }//from   ww w  .j  av  a  2  s.  c  o  m

    try {
        IImportDeclaration[] imports = iUnit.getImports();
        for (int i = 0; i < imports.length; i++) {
            IImportDeclaration declaration = imports[i];
            String importName = declaration.getElementName();
            this.importMap.put(importName.substring(importName.lastIndexOf(".") + 1), importName);
        }
    } catch (JavaModelException jme) {
        jme.printStackTrace();
    }
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockProject.java

License:Open Source License

private void outputImports(IvyXmlWriter xw, IPackageFragment ipf) {
    try {/*from   w w w .  java2  s .  c om*/
        for (ICompilationUnit icu : ipf.getCompilationUnits()) {
            for (IImportDeclaration imp : icu.getImports()) {
                xw.begin("IMPORT");
                if (imp.isOnDemand())
                    xw.field("DEMAND", true);
                if (Modifier.isStatic(imp.getFlags()))
                    xw.field("STATIC", true);
                xw.text(imp.getElementName());
                xw.end("IMPORT");
            }
        }
    } catch (JavaModelException e) {
    }
}

From source file:es.bsc.servicess.ide.editors.CommonFormPage.java

License:Apache License

/** Get the fully qualified domain name of a compilation unit
 * @param cu Compilation unit/*from w w w. j  a v a2s. co m*/
 * @param signature Class signature
 * @param project Service implementation project
 * @return Fully qualified domain name
 * @throws JavaModelException
 */
private static String getFQType(ICompilationUnit cu, String signature, IJavaProject project)
        throws JavaModelException {
    if (signature.equals(Signature.SIG_BOOLEAN) || signature.equals(Signature.SIG_BYTE)
            || signature.equals(Signature.SIG_CHAR) || signature.equals(Signature.SIG_DOUBLE)
            || signature.equals(Signature.SIG_FLOAT) || signature.equals(Signature.SIG_INT)
            || signature.equals(Signature.SIG_LONG) || signature.equals(Signature.SIG_SHORT)
            || signature.equals(Signature.SIG_VOID)) {
        return Signature.toString(signature);
    } else {
        String qualifier = Signature.getQualifier(signature);
        if (qualifier != null && qualifier.length() > 0) {
            return Signature.toString(signature);
        } else {
            String classname = Signature.getSignatureSimpleName(signature);
            IImportDeclaration[] imports = cu.getImports();
            for (IImportDeclaration imp : imports) {
                String name = imp.getElementName();
                if (name.endsWith(".*")) {
                    String fqclass = searchClassInPackages(project, name.substring(0, name.indexOf(".*")),
                            classname);
                    if (fqclass != null)
                        return fqclass;
                } else if (name.endsWith(classname)) {
                    return name;
                }
            }
            return "java.lang." + classname;
        }
    }
}

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

License:Open Source License

/**
 * Explores the Java type representing an annotation and create the matching Ariadne annotation in the
 * given Ariadne types container./*from   w w  w.  j  a v  a2 s  . com*/
 * 
 * @param iType
 *            The Java annotation
 * @param typesContainer
 *            The Ariadne types container
 * @param monitor
 *            The progress monitor
 * @return The Ariadne annotation created
 */
private Annotation exploreAnnotation(IType iType, TypesContainer typesContainer, IProgressMonitor monitor) {
    Annotation annotation = null;
    try {
        List<Type> types = typesContainer.getTypes();
        for (Type aType : types) {
            if (aType instanceof Annotation
                    && aType.getQualifiedName().equals(iType.getFullyQualifiedParameterizedName())) {
                annotation = (Annotation) aType;
            }
        }

        if (annotation == null) {
            annotation = CodeFactory.eINSTANCE.createAnnotation();
            annotation.setQualifiedName(iType.getFullyQualifiedParameterizedName());
        }

        if (annotation != null) {
            typesContainer.getTypes().add(annotation);

            String javadoc = this.getJavadoc(iType, monitor);
            annotation.setDescription(javadoc);
            annotation.setVersion(this.getVersionFromJavadoc(javadoc));

            int flags = iType.getFlags();

            if (Flags.isDeprecated(flags)) {
                // Add the property "Deprecated"
                this.addDeprecatedProperty(annotation);
            }
            annotation.setVisibility(this.getVisibility(iType, false));

            // Explore the fields
            IField[] fields = iType.getFields();
            for (IField iField : fields) {
                this.exploreField(iField, annotation, monitor);
            }

            // Set up the annotations dependencies
            IAnnotation[] annotations = iType.getAnnotations();
            for (IAnnotation iAnnotation : annotations) {
                Annotation ariadneAnnotation = this.getOrCreateAnnotation(iAnnotation);
                if (ariadneAnnotation != null) {
                    annotation.getAnnotations().add(ariadneAnnotation);
                }
            }

            // Set up the reference dependencies (import)
            ICompilationUnit compilationUnit = iType.getCompilationUnit();
            if (compilationUnit != null) {
                IImportDeclaration[] imports = compilationUnit.getImports();
                for (IImportDeclaration iImportDeclaration : imports) {
                    if (!iImportDeclaration.getElementName().endsWith("*")) { //$NON-NLS-1$
                        Classifier classifier = this.getOrCreateClassifier(iImportDeclaration.getElementName());
                        if (classifier != null) {
                            VersionedDependency versionedDependency = CoreFactory.eINSTANCE
                                    .createVersionedDependency();
                            versionedDependency.setVersionedElement(classifier);
                            annotation.getVersionedDependencies().add(versionedDependency);
                        }
                    } else {
                        // TODO Support "*" import
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return annotation;
}

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

License:Open Source License

/**
 * Explores the Java type representing a classifier (enumeration, interface, class) and create the
 * matching Ariadne classifier in the given types container.
 * /*  w w  w  .j  a  v a  2  s .  c om*/
 * @param iType
 *            The Java class, enumeration or interface
 * @param typesContainer
 *            The Ariadne types container
 * @param monitor
 *            The progress monitor
 * @return The Ariadne classifier created
 */
private Classifier exploreClassifier(IType iType, TypesContainer typesContainer, IProgressMonitor monitor) {
    Classifier classifier = null;
    try {
        List<Type> types = typesContainer.getTypes();
        for (Type aType : types) {
            if (aType instanceof Classifier
                    && aType.getQualifiedName().equals(iType.getFullyQualifiedParameterizedName())) {
                classifier = (Classifier) aType;
            }
        }

        if (classifier == null) {
            classifier = CodeFactory.eINSTANCE.createClassifier();
            classifier.setName(iType.getElementName());
            classifier.setQualifiedName(iType.getFullyQualifiedParameterizedName());
        }

        if (classifier != null) {
            typesContainer.getTypes().add(classifier);

            String javadoc = this.getJavadoc(iType, monitor);
            classifier.setDescription(javadoc);
            classifier.setVersion(this.getVersionFromJavadoc(javadoc));

            int flags = iType.getFlags();
            if (Flags.isInterface(flags)) {
                classifier.setKind(ClassifierKind.INTERFACE);
            } else if (Flags.isEnum(flags)) {
                classifier.setKind(ClassifierKind.ENUMERATION);
            } else {
                classifier.setKind(ClassifierKind.CLASS);
            }

            if (Flags.isDeprecated(flags)) {
                // Add the property "Deprecated"
                this.addDeprecatedProperty(classifier);
            }
            classifier.setFinal(Flags.isFinal(flags));
            classifier.setStatic(Flags.isStatic(flags));
            classifier.setVisibility(this.getVisibility(iType, false));

            // Explore the methods
            IMethod[] methods = iType.getMethods();
            for (IMethod iMethod : methods) {
                if (iMethod.isConstructor()) {
                    this.exploreConstructor(iMethod, classifier, Flags.isInterface(flags), monitor);
                } else {
                    this.exploreOperation(iMethod, classifier, Flags.isInterface(flags), monitor);
                }

            }

            // Explore the fields
            IField[] fields = iType.getFields();
            for (IField iField : fields) {
                this.exploreField(iField, classifier, Flags.isInterface(flags), monitor);
            }

            // Set up the annotations dependencies
            IAnnotation[] annotations = iType.getAnnotations();
            for (IAnnotation iAnnotation : annotations) {
                Annotation ariadneAnnotation = this.getOrCreateAnnotation(iAnnotation);
                if (ariadneAnnotation != null) {
                    classifier.getAnnotations().add(ariadneAnnotation);
                }
            }

            // Set up the reference dependencies (import)
            ICompilationUnit compilationUnit = iType.getCompilationUnit();
            if (compilationUnit != null) {
                IImportDeclaration[] imports = compilationUnit.getImports();
                for (IImportDeclaration iImportDeclaration : imports) {
                    if (!iImportDeclaration.getElementName().endsWith("*")) { //$NON-NLS-1$
                        Classifier ariadneClassifier = this
                                .getOrCreateClassifier(iImportDeclaration.getElementName());
                        if (ariadneClassifier != null) {
                            VersionedDependency versionedDependency = CoreFactory.eINSTANCE
                                    .createVersionedDependency();
                            versionedDependency.setVersionedElement(ariadneClassifier);
                            classifier.getVersionedDependencies().add(versionedDependency);
                        }
                    } else {
                        // TODO Support "*" import
                    }
                }
            }

            // Set up the inhenritance dependencies
            String superclassName = iType.getSuperclassName();
            Classifier ariadneClassifier = this.getOrCreateClassifier(superclassName);
            if (ariadneClassifier != null) {
                classifier.getSuperTypes().add(ariadneClassifier);
            }

            String[] superInterfaceNames = iType.getSuperInterfaceNames();
            for (String superInterfaceName : superInterfaceNames) {
                ariadneClassifier = this.getOrCreateClassifier(superInterfaceName);
                if (ariadneClassifier != null) {
                    classifier.getSuperTypes().add(ariadneClassifier);
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return classifier;
}

From source file:org.apache.felix.sigil.eclipse.ui.internal.editors.project.DependencyManagementSection.java

License:Apache License

protected void run() {
    final Map<String, IPackageExport> exports = new HashMap<String, IPackageExport>();
    final Set<String> imports = new HashSet<String>();

    // Find all exports
    final ExportedPackageFinder exportFinder = new ExportedPackageFinder(getProjectModel(),
            new AccumulatorAdapter<IPackageExport>() {
                public void addElements(Collection<? extends IPackageExport> elements) {
                    for (IPackageExport export : elements) {
                        exports.put(export.getPackageName(), export);
                    }//  w  w w  . j  av  a2s.  com
                }
            });
    Job findExportsJob = new Job("Find exports") {
        protected IStatus run(IProgressMonitor monitor) {
            return exportFinder.run(monitor);
        }
    };
    findExportsJob.setUser(true);
    findExportsJob.schedule();

    // Find imports from Java source
    Job findImportsJob = new Job("Find imports") {
        protected IStatus run(IProgressMonitor monitor) {
            IJavaProject javaProject = getProjectModel().getJavaModel();
            try {
                IPackageFragment[] packages = javaProject.getPackageFragments();
                for (IPackageFragment pkg : packages) {
                    ICompilationUnit[] compilationUnits = pkg.getCompilationUnits();
                    for (ICompilationUnit compilationUnit : compilationUnits) {
                        IImportDeclaration[] importDecls = compilationUnit.getImports();
                        for (IImportDeclaration importDecl : importDecls) {
                            imports.add(getPackageName(importDecl));
                        }
                    }
                }
                return Status.OK_STATUS;
            } catch (JavaModelException e) {
                return new Status(IStatus.ERROR, SigilUI.PLUGIN_ID, 0, "Error finding imports", e);
            }
        }
    };
    findImportsJob.setUser(true);
    findImportsJob.schedule();

    // Wait for both jobs to complete
    try {
        findImportsJob.join();
        findExportsJob.join();
    } catch (InterruptedException e) {
        // Aborted, just do nothing
        return;
    }

    // Get the existing imports for the bundle
    IBundleModelElement bundleInfo = getProjectModel().getBundle().getBundleInfo();
    Collection<IPackageImport> existingImports = bundleInfo.getImports();
    Map<String, IPackageImport> existingImportsMap = new HashMap<String, IPackageImport>();
    for (IPackageImport existingImport : existingImports) {
        existingImportsMap.put(existingImport.getPackageName(), existingImport);
    }

    // Add imports to the bundle
    ModelElementFactory elementFactory = ModelElementFactory.getInstance();
    int count = 0;
    for (String pkgImport : imports) {
        IPackageExport export = exports.get(pkgImport);
        if (export != null && !existingImportsMap.containsKey(pkgImport)) {
            VersionRange versionRange = ModelHelper.getDefaultRange(export.getVersion());
            IPackageImport newImport = elementFactory.newModelElement(IPackageImport.class);
            newImport.setPackageName(pkgImport);
            newImport.setVersions(versionRange);
            newImport.setOptional(false);

            bundleInfo.addImport(newImport);
            count++;
        }
    }

    // Remove required bundles
    Collection<IRequiredBundle> requiredBundles = bundleInfo.getRequiredBundles();
    int requiredBundlesSize = requiredBundles.size();
    for (IRequiredBundle requiredBundle : requiredBundles) {
        bundleInfo.removeRequiredBundle(requiredBundle);
    }

    // Update the editor
    if (count + requiredBundlesSize > 0) {
        IFormPart[] parts = getPage().getManagedForm().getParts();
        for (IFormPart formPart : parts) {
            formPart.refresh();
            ((AbstractFormPart) formPart).markDirty();
        }
    }

    MessageDialog.openInformation(getManagedForm().getForm().getShell(), "Dependency Management", "Removed "
            + requiredBundlesSize + " required bundle(s) and added " + count + " imported package(s).");
}

From source file:org.apache.felix.sigil.ui.eclipse.ui.editors.project.DependencyManagementSection.java

License:Apache License

protected void run() {
    final Map<String, IPackageExport> exports = new HashMap<String, IPackageExport>();
    final Set<String> imports = new HashSet<String>();

    // Find all exports
    final ExportedPackageFinder exportFinder = new ExportedPackageFinder(getProjectModel(),
            new AccumulatorAdapter<IPackageExport>() {
                public void addElements(Collection<? extends IPackageExport> elements) {
                    for (IPackageExport export : elements) {
                        exports.put(export.getPackageName(), export);
                    }/*from   ww  w.  ja  va2s. co m*/
                }
            });
    Job findExportsJob = new Job("Find exports") {
        protected IStatus run(IProgressMonitor monitor) {
            return exportFinder.run(monitor);
        }
    };
    findExportsJob.setUser(true);
    findExportsJob.schedule();

    // Find imports from Java source
    Job findImportsJob = new Job("Find imports") {
        protected IStatus run(IProgressMonitor monitor) {
            IJavaProject javaProject = getProjectModel().getJavaModel();
            try {
                IPackageFragment[] packages = javaProject.getPackageFragments();
                for (IPackageFragment pkg : packages) {
                    ICompilationUnit[] compilationUnits = pkg.getCompilationUnits();
                    for (ICompilationUnit compilationUnit : compilationUnits) {
                        IImportDeclaration[] importDecls = compilationUnit.getImports();
                        for (IImportDeclaration importDecl : importDecls) {
                            imports.add(getPackageName(importDecl));
                        }
                    }
                }
                return Status.OK_STATUS;
            } catch (JavaModelException e) {
                return new Status(IStatus.ERROR, SigilUI.PLUGIN_ID, 0, "Error finding imports", e);
            }
        }
    };
    findImportsJob.setUser(true);
    findImportsJob.schedule();

    // Wait for both jobs to complete
    try {
        findImportsJob.join();
        findExportsJob.join();
    } catch (InterruptedException e) {
        // Aborted, just do nothing
        return;
    }

    // Get the version rules
    IPreferenceStore prefStore = SigilCore.getDefault().getPreferenceStore();
    VersionRangeBoundingRule lowerBoundRule = VersionRangeBoundingRule
            .valueOf(prefStore.getString(SigilCore.DEFAULT_VERSION_LOWER_BOUND));
    VersionRangeBoundingRule upperBoundRule = VersionRangeBoundingRule
            .valueOf(prefStore.getString(SigilCore.DEFAULT_VERSION_UPPER_BOUND));

    // Get the existing imports for the bundle
    IBundleModelElement bundleInfo = getProjectModel().getBundle().getBundleInfo();
    Set<IPackageImport> existingImports = bundleInfo.getImports();
    Map<String, IPackageImport> existingImportsMap = new HashMap<String, IPackageImport>();
    for (IPackageImport existingImport : existingImports) {
        existingImportsMap.put(existingImport.getPackageName(), existingImport);
    }

    // Add imports to the bundle
    ModelElementFactory elementFactory = ModelElementFactory.getInstance();
    int count = 0;
    for (String pkgImport : imports) {
        IPackageExport export = exports.get(pkgImport);
        if (export != null && !existingImportsMap.containsKey(pkgImport)) {
            VersionRange versionRange = VersionRange.newInstance(export.getVersion(), lowerBoundRule,
                    upperBoundRule);
            IPackageImport newImport = elementFactory.newModelElement(IPackageImport.class);
            newImport.setPackageName(pkgImport);
            newImport.setVersions(versionRange);
            newImport.setOptional(false);

            bundleInfo.addImport(newImport);
            count++;
        }
    }

    // Remove required bundles
    Set<IRequiredBundle> requiredBundles = bundleInfo.getRequiredBundles();
    int requiredBundlesSize = requiredBundles.size();
    for (IRequiredBundle requiredBundle : requiredBundles) {
        bundleInfo.removeRequiredBundle(requiredBundle);
    }

    // Update the editor
    if (count + requiredBundlesSize > 0) {
        IFormPart[] parts = getPage().getManagedForm().getParts();
        for (IFormPart formPart : parts) {
            formPart.refresh();
            ((AbstractFormPart) formPart).markDirty();
        }
    }

    MessageDialog.openInformation(getManagedForm().getForm().getShell(), "Dependency Management", "Removed "
            + requiredBundlesSize + " required bundle(s) and added " + count + " imported package(s).");
}

From source file:org.autorefactor.ui.ApplyFileMergeRefactoringsJob.java

License:Open Source License

/**
 * Executes the refactoring according to the information stored in the attributes/
 * @param monitor ProgressMonitor//from   w  ww  . ja v a  2 s. c om
 * @return
 */
protected IStatus run(IProgressMonitor monitor) {
    try {
        if (monitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }
        // Performing the merge of the properties files *.* 
        ICompilationUnit mergedPropertiesCompilationUnit = (ICompilationUnit) this.mergedPropertiesJavaElement;
        for (IJavaElement _currentJavaElement : this.javaElementsToMerge) {
            ICompilationUnit currentPropertiesToMergeCompilationUnit = (ICompilationUnit) _currentJavaElement;

            if (currentPropertiesToMergeCompilationUnit.findPrimaryType() != null) {
                for (IField _field : currentPropertiesToMergeCompilationUnit.findPrimaryType().getFields()) {
                    System.out.println("additionalVariablesList.add(_field.getElementName());");
                    additionalVariablesList.add(_field.getElementName());
                    mergedPropertiesCompilationUnit.findPrimaryType().createField(_field.getSource(), null,
                            false, monitor);
                }
                for (IMethod _method : currentPropertiesToMergeCompilationUnit.findPrimaryType().getMethods()) {
                    mergedPropertiesCompilationUnit.findPrimaryType().createMethod(_method.getSource(), null,
                            false, monitor);
                }
                for (IImportDeclaration _import : currentPropertiesToMergeCompilationUnit.getImports()) {
                    if (!mergedPropertiesCompilationUnit.getImport(_import.getElementName()).exists()) {
                        mergedPropertiesCompilationUnit.createImport(_import.getElementName(), null, monitor);
                    }
                }
            }
        }
        targetProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (Exception e) {
        e.printStackTrace();
        return new Status(IStatus.ERROR, AutoRefactorPlugin.PLUGIN_ID, e.getMessage(), e);
    } finally {
        monitor.done();
    }
    return Status.OK_STATUS;
}