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

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

Introduction

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

Prototype

IImportDeclaration getImport(String name);

Source Link

Document

Returns the first import declaration in this compilation unit with the given name.

Usage

From source file:com.sun.codemodel.ClassGenerator.java

License:Apache License

private ICompilationUnit addClass(ElementClass ec, ICompilationUnit of, IProgressMonitor pm)
        throws JavaModelException {
    JDefinedClass c = ec.getjDefClass();
    IImportDeclaration imp = of.getImport("javax.xml.namespace.QName");
    if (imp == null || (!imp.exists())) {
        of.createImport("javax.xml.namespace.QName", null, Flags.AccDefault, pm);
    }/*from  ww w . jav a  2 s.c o  m*/
    imp = of.getImport("javax.xml.bind.annotation.XmlElementDecl");
    if (imp == null || (!imp.exists())) {
        of.createImport("javax.xml.bind.annotation.XmlElementDecl", null, Flags.AccDefault, pm);
    }
    imp = of.getImport("javax.xml.bind.JAXBElement");
    if (imp == null || (!imp.exists())) {
        of.createImport("javax.xml.bind.JAXBElement", null, Flags.AccDefault, pm);
    }
    IType t = of.getType("ObjectFactory");
    if (t != null && t.exists()) {
        String lineDelimiter = StubUtility.getLineDelimiterUsed(project);
        t.createField("private final static QName _" + c.name() + "_QNAME= new QName(\""
                + ec.getElementType().getNamespaceURI() + "\", \"" + ec.getElementType().getLocalPart() + "\");"
                + lineDelimiter, null, false, pm);

        t.createMethod(generateFirstMethod(c, lineDelimiter), null, false, pm);
        t.createMethod(generateSecondMethod(ec, lineDelimiter), null, false, pm);
    } else
        throw new JavaModelException(
                new Exception("Error ObjectFactory class does not exists in compilation unit"),
                JavaModelStatus.ERROR);

    return of;
}

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   www  .  j av a  2 s.c o  m*/
 * @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;
}

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

License:Open Source License

private IStatus run0(IProgressMonitor monitor) throws Exception {

    final int startSize = 2;
    monitor.beginTask("", startSize);
    try {//from  ww  w.  j  av  a  2  s.  c om
        if (monitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }

        if (extensionRefactoringUnit != null && baseRefactoringUnit != null) {
            ICompilationUnit extensionCompilationUnit = extensionRefactoringUnit.getCompilationUnit();
            ICompilationUnit baseCompilationUnit = baseRefactoringUnit.getCompilationUnit();
            IType primaryType = extensionCompilationUnit.findPrimaryType();

            //               System.out.println("ApplyOverloadingRefactoringsJob.run0 " + "extension: " + extensionCompilationUnit.getElementName()
            //                     + " base: " + baseCompilationUnit.getElementName());
            //               System.out.println("ApplyOverloadingRefactoringsJob.run0 " + "extension: " + extensionCompilationUnit.getJavaProject().getElementName()
            //                     + " base: " + baseCompilationUnit.getJavaProject().getElementName());
            //               System.out.println("ApplyOverloadingRefactoringsJob.run0 " + "base SRC: " + baseCompilationUnit.getSource());

            //               for(IMethod _method : baseRefactoringUnit.getCompilationUnit().findPrimaryType().getMethods()){
            //                  System.out.println("_baseMethod: " + _method.getElementName());
            //               }

            for (IMethod _overridingMethod : primaryType.getMethods()) {
                //                  System.out.println("_overridingMethod " + _overridingMethod.getElementName());

                IAnnotation overrideAnnotation = null;
                for (IAnnotation _annotation : _overridingMethod.getAnnotations()) {
                    if (_annotation.getElementName().equals("OverrideRequiredAspectMethod"))
                        overrideAnnotation = _annotation;
                }

                if (overrideAnnotation != null) {
                    IMethod realOverridingMethod = null;

                    for (IMethod _overridingMethod2 : primaryType.getMethods()) {
                        if (_overridingMethod2.getElementName()
                                .equals("_privk3_" + _overridingMethod.getElementName()))
                            realOverridingMethod = _overridingMethod2;
                    }

                    IMethod toRemove = null;

                    for (IMethod _method : baseRefactoringUnit.getCompilationUnit().findPrimaryType()
                            .getMethods()) {
                        if (_method.getElementName().equals(realOverridingMethod.getElementName())
                        /*&& _method.getNumberOfParameters() == realOverridingMethod.getNumberOfParameters()
                           && areParametersEquivalent(_method.getParameterTypes(), realOverridingMethod.getParameterTypes())*/) {
                            toRemove = _method;
                        }
                    }

                    IMethod oldOriginal = null;

                    for (IMethod _method : baseRefactoringUnit.getCompilationUnit().findPrimaryType()
                            .getMethods()) {
                        if (_method.getElementName().endsWith("_original_" + _overridingMethod.getElementName())
                        /*&& _method.getNumberOfParameters() == _overridingMethod.getNumberOfParameters()
                           && areParametersEquivalent(_method.getParameterTypes(), _overridingMethod.getParameterTypes())*/) {
                            oldOriginal = _method;
                        }
                    }

                    if (toRemove != null && oldOriginal == null) {
                        overrideRequiredMethod(baseRefactoringUnit, toRemove, realOverridingMethod, monitor);
                    } else if (toRemove != null && oldOriginal != null) {
                        ArrayList<IMethod> originalMethods = getAllOriginalMethods(baseRefactoringUnit,
                                _overridingMethod.getElementName());
                        overrideRequiredMethodOriginal(baseRefactoringUnit, toRemove, realOverridingMethod,
                                originalMethods.size(), monitor);
                    }
                    targetProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
                }
            }

            // Adding the additional methods included by the extension
            for (IMethod _method : extensionRefactoringUnit.getCompilationUnit().findPrimaryType()
                    .getMethods()) {
                IAnnotation extensionAnnotation = null;
                for (IAnnotation _annotation : _method.getAnnotations()) {
                    if (_annotation.getElementName().equals("AddExtensionMethod"))
                        extensionAnnotation = _annotation;
                }
                if (extensionAnnotation != null || additionalVariablesList.contains(_method.getElementName())) {
                    IMethod baseMethod = getMethod(baseRefactoringUnit, _method);
                    if (baseMethod == null || (baseMethod != null && !baseMethod.exists())) {
                        baseRefactoringUnit.getCompilationUnit().findPrimaryType()
                                .createMethod(_method.getSource(), null, true, monitor);
                        IMethod privk3baseMethod = getPrivateMethod(extensionRefactoringUnit, _method);
                        if (privk3baseMethod != null) {
                            baseRefactoringUnit.getCompilationUnit().findPrimaryType()
                                    .createMethod(privk3baseMethod.getSource(), null, true, monitor);
                        }
                    }
                }
            }

            // Adding the imports needed by the injected code
            for (IImportDeclaration _import : extensionCompilationUnit.getImports()) {
                if (!baseCompilationUnit.getImport(_import.getElementName()).exists()) {
                    baseCompilationUnit.createImport(_import.getElementName(), null, monitor);
                }
            }

            //               System.out.println("ApplyOverloadingRefactoringsJob.run0.after " + "extension: " + extensionCompilationUnit.getElementName()
            //                     + " base: " + baseCompilationUnit.getElementName());
            //               System.out.println("ApplyOverloadingRefactoringsJob.run0.after " + "extension: " + extensionCompilationUnit.getJavaProject().getElementName()
            //                     + " base: " + baseCompilationUnit.getJavaProject().getElementName());

            //               for(IMethod _method : baseRefactoringUnit.getCompilationUnit().findPrimaryType().getMethods()){
            //                  System.out.println("_baseMethod: " + _method.getElementName());
            //               }
        }
    } finally {
        monitor.done();
    }
    return Status.OK_STATUS;
}

From source file:org.eclipse.objectteams.otdt.ui.tests.refactoring.reorg.PasteActionTest.java

License:Open Source License

public void test3() throws Exception {
    //      printTestDisabledMessage("test for bug#19007");
    ICompilationUnit cuA = createCUfromTestFile(getPackageP(), "A");
    ICompilationUnit cuB = createCUfromTestFile(getPackageP(), "B");

    try {/*from  w w w  . j  a va2 s.c  om*/
        IJavaElement elem0 = cuA.getImport("java.lang.*");
        IImportContainer importContainer = cuB.getImportContainer();

        assertTrue("y does not exist", elem0.exists());
        assertTrue("B does not exist", importContainer.exists());

        IJavaElement[] copyJavaElements = { elem0 };
        IResource[] copyResources = {};
        IJavaElement[] pasteJavaElements = { importContainer };
        IResource[] pasteResources = {};
        PasteAction paste = verifyEnabled(copyResources, copyJavaElements, pasteResources, pasteJavaElements);
        paste.run((IStructuredSelection) paste.getSelection());
        compareContents("A");
        compareContents("B");
    } finally {
        delete(cuA);
        delete(cuB);
    }
}

From source file:org.fastcode.popup.actions.easycreate.NewMemberCreateActionSupport.java

License:Open Source License

/**
 *
 * @param compUnit//w  w w .j  ava2s.co m
 * @param type
 * @throws Exception
 */
protected void addImport(final ICompilationUnit compUnit, final IType type) throws Exception {

    if (type == null || !type.exists()) {
        throw new Exception("type does not exit");
    }

    final String pkg = type.getPackageFragment().getElementName();
    if (pkg.equals("java.lang")) {
        return;
    }

    if (this.createVariableData.getCompUnitType().equals(GROOVY_EXTENSION) && pkg.equals("java.util")) {
        return;
    }

    IImportDeclaration imp = compUnit.getImport(pkg + ".*");

    if (imp == null || !imp.exists()) {
        imp = compUnit.getImport(type.getFullyQualifiedName());
        if (imp == null || !imp.exists()) {
            compUnit.createImport(type.getFullyQualifiedName(), null, null);
        }
    }
}

From source file:org.fastcode.util.SourceUtil.java

License:Open Source License

/**
 *
 * @param fromType//from   ww  w  . ja va 2  s .  c  om
 * @param toType
 * @throws Exception
 */
public static void copyImports(final ICompilationUnit fromCompUnit, final ICompilationUnit toCompUnit,
        final IMethod method) throws Exception {
    final Map<String, String> importMap = new HashMap<String, String>();

    for (final IImportDeclaration imp : fromCompUnit.getImports()) {
        if (!imp.getElementName().endsWith(ASTERISK)) {
            final int off = imp.getElementName().lastIndexOf(DOT_CHAR);
            final String className = imp.getElementName().substring(off + 1);
            final IImportDeclaration declaration = toCompUnit.getImport(imp.getElementName());

            if (declaration != null && declaration.exists()) {
                continue;
            }

            if (method != null) {
                boolean matchParameter = false;
                for (final String parameterType : method.getParameterTypes()) {
                    if (className.equals(getSignatureSimpleName(parameterType))) {
                        matchParameter = true;
                        break;
                    }
                }
                for (final String exceptionType : method.getExceptionTypes()) {
                    if (className.equals(getSignatureSimpleName(exceptionType))) {
                        matchParameter = true;
                        break;
                    }
                }
                if (!matchParameter) {
                    continue;
                }
            }

            if (importMap.containsKey(className)) {
                // conflict found, special handling later
                continue;
            }
            boolean match = false;
            // Check for conflicts
            for (final IImportDeclaration toimp : toCompUnit.getImports()) {
                final int off1 = toimp.getElementName().lastIndexOf(DOT_CHAR);
                final String clsName = toimp.getElementName().substring(off1 + 1);
                if (clsName.equals(className)) {
                    match = true;
                    // conflict found, special handling later
                }
                if (!importMap.containsKey(clsName)) {
                    importMap.put(clsName, toimp.getElementName());
                }
                if (match) {
                    break;
                }
            }
            if (!match) {
                toCompUnit.createImport(imp.getElementName(), null, null);
            }

        }
    }
}

From source file:org.fastcode.util.SourceUtil.java

License:Open Source License

/**
 * @param compilationUnit//from www.  j a v  a  2s  .  c  o  m
 * @param annotationsArray
 * @param placeHolders
 * @return
 * @throws Exception
 */
public static String createAnnotations(final FastCodeContext fastCodeContext,
        final ICompilationUnit compilationUnit, final IJavaProject javaProject, final String[] annotationsArray,
        final Map<String, Object> placeHolders) throws Exception {
    final GlobalSettings globalSettings = getInstance();

    if (annotationsArray == null || annotationsArray.length == 0) {
        return EMPTY_STR;
    }

    final StringBuilder annotations = new StringBuilder();

    for (final String annot : annotationsArray) {
        if (annot.trim().equals(EMPTY_STR)) {
            continue;
        }
        final int off = annot.indexOf(LEFT_PAREN);
        String annotName = annot;
        if (off != -1) {
            annotName = annot.substring(0, off);
        }

        if (annotName.startsWith("@")) {
            annotName = annotName.substring(1);
        }
        String annotation = annot.trim();
        if (globalSettings.getAnnotationTypesMap().containsKey(annotName)) {
            final String fullAnotTypeName = globalSettings.getAnnotationTypesMap().get(annotName);
            final IType fullAnotType = javaProject.findType(fullAnotTypeName);
            if (fullAnotType != null && fullAnotType.exists()) {
                if (compilationUnit != null) {
                    final IImportDeclaration importDeclaration = compilationUnit.getImport(fullAnotTypeName);
                    if (importDeclaration == null || !importDeclaration.exists()) {
                        compilationUnit.createImport(fullAnotTypeName, null, null);
                    }
                } else if (fastCodeContext != null) {
                    String imp = "import " + fullAnotTypeName + ";";
                    if (fastCodeContext.getPlaceHolders().containsKey(CLASS_IMPORTS_STR)) {
                        imp = fastCodeContext.getPlaceHolders().get(CLASS_IMPORTS_STR) + NEWLINE + imp;
                    }
                    fastCodeContext.addToPlaceHolders(CLASS_IMPORTS_STR, imp);
                }
            }
        } else {
            final IType fullAnotType = javaProject.findType(annotName);
            if (fullAnotType != null && fullAnotType.exists()) {
                annotation = fullAnotType.getElementName();
            }
        }
        getGlobalSettings(placeHolders);
        annotation = evaluateByVelocity(annotation, placeHolders);
        if (!annotation.startsWith("@")) {
            annotation = "@" + annotation;
        }
        annotations.append(evaluateByVelocity(annotation, placeHolders) + NEWLINE);

    }
    return annotations.toString().trim();
}

From source file:org.jboss.tools.common.refactoring.MarkerResolutionUtils.java

License:Open Source License

public static void deleteImportForAnnotation(String qualifiedName, IAnnotation annotation,
        ICompilationUnit compilationUnit, IBuffer buffer, MultiTextEdit rootEdit) throws JavaModelException {
    IImportDeclaration importDeclaration = compilationUnit.getImport(qualifiedName);
    IImportContainer importContainer = compilationUnit.getImportContainer();
    if (importDeclaration.exists() && importContainer.exists()) {
        int importSize = importContainer.getSourceRange().getOffset()
                + importContainer.getSourceRange().getLength();

        if (rootEdit != null) {
            int annotationStart = annotation.getSourceRange().getOffset();
            int annotationEnd = annotationStart + annotation.getSourceRange().getLength();
            String textBefore = buffer.getText(importSize, annotationStart - importSize);
            String textAfter = buffer.getText(annotationEnd, buffer.getLength() - annotationEnd);
            if (checkImport(textBefore, qualifiedName) && checkImport(textAfter, qualifiedName)) {
                int numberOfSpaces = 0;
                if (!isLastImport(importContainer, importDeclaration)) {
                    numberOfSpaces = getNumberOfSpacesToDelete(importDeclaration.getSourceRange().getOffset()
                            + importDeclaration.getSourceRange().getLength(), buffer);
                }//  w w  w.  j  ava 2  s  .c  om

                TextEdit edit = new DeleteEdit(importDeclaration.getSourceRange().getOffset(),
                        importDeclaration.getSourceRange().getLength() + numberOfSpaces);
                rootEdit.addChild(edit);
            }
        } else {
            String text = buffer.getText(importSize, buffer.getLength() - importSize);
            if (checkImport(text, qualifiedName)) {
                importDeclaration.delete(false, new NullProgressMonitor());
            }
        }
    }

    if (rootEdit == null) {
        synchronized (compilationUnit) {
            compilationUnit.reconcile(ICompilationUnit.NO_AST, true, null, null);
        }
    }
}

From source file:org.jboss.tools.servers.wildfly.swarm.core.internal.MainClassDetector.java

License:Open Source License

private static boolean hasContainerImport(IType t) {
    ICompilationUnit compilationUnit = t.getCompilationUnit();
    if (compilationUnit == null) {
        return false;
    }//from   w w w.  j ava2 s  .co  m
    return compilationUnit.getImport("org.wildfly.swarm.container.Container").exists()
            || compilationUnit.getImport("org.wildfly.swarm.Swarm").exists();
}

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

License:Open Source License

public static void removeImport(ICompilationUnit compilationUnit, String name) throws JavaModelException {
    LOGGER.debug("Removing import " + name);
    IProgressMonitor monitor = new NullProgressMonitor();
    ICompilationUnit workingCopy = createWorkingCopy(compilationUnit);
    workingCopy.getImport(name).delete(true, monitor);
    saveAndClose(workingCopy);//from  w  w w . ja  v a 2 s.co  m
}