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

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

Introduction

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

Prototype

IImportContainer getImportContainer();

Source Link

Document

Returns the import container for this compilation unit.

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.CompilationUnitStructureRequestor.java

License:Open Source License

protected ImportContainer createImportContainer(ICompilationUnit parent) {
    return (ImportContainer) parent.getImportContainer();
}

From source file:org.eclipse.ajdt.ui.tests.refactoring.OrganizeImportsTest.java

License:Open Source License

/**
 * Should not remove the aspect in the imports statement
 *//*from  www. j av a 2 s. co m*/
public void testBug188845() throws Exception {
    IProject proj = createPredefinedProject("Bug 188845"); //$NON-NLS-1$
    IFile concrete = proj.getFile("src/tmp/b/ConcreteAspect.aj"); //$NON-NLS-1$
    ICompilationUnit cu = (ICompilationUnit) AspectJCore.create(concrete);

    JavaEditor editor = (JavaEditor) EditorUtility.openInEditor(cu);

    assertEquals("Should start off with 2 import statements", 2, cu.getImportContainer().getChildren().length); //$NON-NLS-1$
    OrganizeImportsAction action = new OrganizeImportsAction(editor);
    action.run(cu);
    editor.doSave(null);

    // hmmm...why do I need to do a full build here?  That's odd
    // If I don't, then I am getting some error markers.
    proj.build(org.eclipse.core.resources.IncrementalProjectBuilder.FULL_BUILD, null);

    waitForJobsToComplete();
    assertEquals("Should have only 1 import statement after reorganizing", 1, //$NON-NLS-1$
            cu.getImportContainer().getChildren().length);

    IMarker[] markers = concrete.findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE);
    if (markers.length > 0) {
        StringBuffer sb = new StringBuffer();
        sb.append("No markers should have been found, but the following markers were found on A.aj:\n"); //$NON-NLS-1$
        for (int i = 0; i < markers.length; i++) {
            sb.append("\t" + markers[i].getAttribute(IMarker.MESSAGE) + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        assertEquals(sb.toString(), 0, markers.length);
    }

}

From source file:org.eclipse.ajdt.ui.tests.refactoring.OrganizeImportsTest.java

License:Open Source License

/**
 * should add the LinkedList import statement in the proper location (not above the package declaration)
 *//*from ww w  .ja  va  2  s  . c o m*/
public void testBug236352() throws Exception {
    IProject proj = createPredefinedProject("Bug 188845"); //$NON-NLS-1$
    IFile concrete = proj.getFile("src/tmp/b/ConcreteAspect2.aj"); //$NON-NLS-1$
    ICompilationUnit cu = (ICompilationUnit) AspectJCore.create(concrete);

    JavaEditor editor = (JavaEditor) EditorUtility.openInEditor(cu);

    assertEquals("Should start off with 2 import statements", 2, cu.getImportContainer().getChildren().length); //$NON-NLS-1$
    OrganizeImportsAction action = new OrganizeImportsAction(editor);
    action.run(cu);
    editor.doSave(null);

    waitForJobsToComplete();
    assertEquals("Should have 3 import statements after reorganizing", 3, //$NON-NLS-1$
            cu.getImportContainer().getChildren().length);

    IMarker[] markers = concrete.findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE);
    if (markers.length > 0) {
        StringBuffer sb = new StringBuffer();
        sb.append(
                "No markers should have been found, but the following markers were found on ConcreteAspect2.aj:\n"); //$NON-NLS-1$
        for (int i = 0; i < markers.length; i++) {
            sb.append("\t" + markers[i].getAttribute(IMarker.MESSAGE) + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        assertEquals(sb.toString(), 0, markers.length);
    }
}

From source file:org.eclipse.ajdt.ui.tests.refactoring.OrganizeImportsTest.java

License:Open Source License

/**
 * static inner classes enclosed in an aspect should be imported with the enclosing aspect around it.
 *///from  w ww .j ava  2 s .  c  o m
public void testBug106589() throws Exception {
    IProject proj = createPredefinedProject("Bug 188845"); //$NON-NLS-1$
    IFile importer = proj.getFile("src/bug106589importer/Importer.java"); //$NON-NLS-1$
    ICompilationUnit cu = (ICompilationUnit) AspectJCore.create(importer);

    IMarker[] markers = importer.findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE);
    if (markers.length > 1) {
        StringBuffer sb = new StringBuffer();
        sb.append("Should start with 1 error, but the following markers were found on Importer.java:\n"); //$NON-NLS-1$
        for (int i = 0; i < markers.length; i++) {
            sb.append("\t" + markers[i].getAttribute(IMarker.MESSAGE) + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        assertEquals(sb.toString(), 0, markers.length);
    }

    JavaEditor editor = (JavaEditor) EditorUtility.openInEditor(cu);

    try {
        IImportContainer container = cu.getImportContainer();
        container.getChildren();
        fail("Should not start off with an import container, but instead found:\n " + container.toString()); //$NON-NLS-1$
    } catch (JavaModelException e) {
        // expected
    }

    OrganizeImportsAction action = new OrganizeImportsAction(editor);
    action.run(cu);
    editor.doSave(null);

    // hmmm...why do I need to do a full build here?  That's odd
    // If I don't, then I am getting some error markers.
    proj.build(org.eclipse.core.resources.IncrementalProjectBuilder.FULL_BUILD, null);

    waitForJobsToComplete();
    assertEquals("Should have 1 import statements after reorganizing", 1, //$NON-NLS-1$
            cu.getImportContainer().getChildren().length);

    markers = importer.findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE);
    if (markers.length > 0) {
        StringBuffer sb = new StringBuffer();
        sb.append(
                "No markers should have been found, but the following markers were found on Importer.java:\n"); //$NON-NLS-1$
        for (int i = 0; i < markers.length; i++) {
            sb.append("\t" + markers[i].getAttribute(IMarker.MESSAGE) + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        assertEquals(sb.toString(), 0, markers.length);
    }
}

From source file:org.eclipse.jst.jsp.ui.internal.contentassist.JSPProposalCollector.java

License:Open Source License

public JSPProposalCollector(ICompilationUnit cu, JSPTranslation translation) {
    super(cu);//from w ww .j av a  2s  .  co  m

    if (translation == null)
        throw new IllegalArgumentException("JSPTranslation cannot be null"); //$NON-NLS-1$

    fTranslation = translation;
    fImportContainer = cu.getImportContainer();
}

From source file:org.eclipse.jst.jsp.ui.internal.handlers.AddImportHandler.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    final IEditorSite site = HandlerUtil.getActiveEditor(event).getEditorSite();
    final ISelectionProvider provider = site.getSelectionProvider();
    final ISelection selection = provider != null ? provider.getSelection() : null;
    if (selection instanceof IStructuredSelection && selection instanceof ITextSelection) {
        final IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        final int offset = ((ITextSelection) selection).getOffset();
        final Object firstElement = structuredSelection.getFirstElement();
        if (firstElement instanceof IDOMNode) {
            final IDOMModel model = ((IDOMNode) firstElement).getModel();
            INodeAdapter adapter = model.getDocument().getAdapterFor(IJSPTranslation.class);
            if (adapter != null) {
                JSPTranslationAdapter translationAdapter = (JSPTranslationAdapter) model.getDocument()
                        .getAdapterFor(IJSPTranslation.class);
                final JSPTranslationExtension translation = translationAdapter.getJSPTranslation();
                translation.reconcileCompilationUnit();
                final ICompilationUnit cu = translation.getCompilationUnit();
                CompilationUnit astRoot = SharedASTProvider.getAST(cu, SharedASTProvider.WAIT_YES, null);
                if (astRoot != null) {
                    final ASTNode node = NodeFinder.perform(astRoot, translation.getJavaOffset(offset), 0);
                    if (node != null) {
                        SimpleName name = null;
                        if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
                            name = (SimpleName) node;
                        } else if (node.getNodeType() == ASTNode.QUALIFIED_NAME) {
                            name = ((QualifiedName) node).getName();
                        }/*from  w  w w .  ja v a  2 s  . c  om*/
                        if (name != null) {
                            IBinding binding = name.resolveBinding();
                            if (binding instanceof ITypeBinding && (binding.getJavaElement() == null
                                    || !binding.getJavaElement().exists())) {
                                // Look it up!
                                ITypeBinding typeBinding = (ITypeBinding) binding;
                                final IImportContainer importContainer = cu.getImportContainer();
                                if (!importContainer.getImport(typeBinding.getQualifiedName()).exists()) {
                                    final List typesFound = new ArrayList();
                                    final TypeNameMatchRequestor collector = new TypeNameMatcher(typesFound);
                                    IJavaSearchScope scope = SearchEngine
                                            .createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
                                    final int mode = SearchPattern.R_EXACT_MATCH
                                            | SearchPattern.R_CASE_SENSITIVE;
                                    try {
                                        new SearchEngine().searchAllTypeNames(null, mode,
                                                name.getIdentifier().toCharArray(), mode,
                                                IJavaSearchConstants.CLASS_AND_INTERFACE, scope, collector,
                                                IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
                                        final int length = typesFound.size();
                                        final List elements = new ArrayList();
                                        for (int i = 0; i < length; i++) {
                                            final TypeNameMatch match = (TypeNameMatch) typesFound.get(i);
                                            final int modifiers = match.getModifiers();
                                            if (!Flags.isPrivate(modifiers)
                                                    && !Flags.isPackageDefault(modifiers)) {
                                                elements.add(match);
                                            }
                                        }
                                        TypeNameMatch match = null;
                                        // If there's only one match, insert it; otherwise, open the dialog to choose from the list
                                        if (elements.size() == 1) {
                                            match = (TypeNameMatch) elements.get(0);
                                        } else if (elements.size() > 1) {
                                            ElementListSelectionDialog dialog = new ElementListSelectionDialog(
                                                    site.getShell(), LABEL_PROVIDER);
                                            dialog.setElements(
                                                    elements.toArray(new TypeNameMatch[elements.size()]));
                                            dialog.setTitle(JSPUIMessages.AddImportHandler_title);
                                            dialog.setMessage(JSPUIMessages.AddImportHandler_label);
                                            if (dialog.open() == Window.OK) {
                                                final Object result = dialog.getFirstResult();
                                                if (result instanceof TypeNameMatch) {
                                                    match = (TypeNameMatch) result;
                                                }
                                            }
                                        }
                                        addImport(match, model.getStructuredDocument());
                                    } catch (JavaModelException e) {
                                        Logger.logException("Exception while determining import.", e); //$NON-NLS-1$
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return null;
}

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  ww  w .  j  ava  2  s  .co m*/
        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.grails.ide.eclipse.groovy.debug.core.evaluation.GroovyJDIEvaluator.java

License:Open Source License

private String createEvaluationSourceFromSnippet(String snippet, IJavaStackFrame frame) throws CoreException {
    StringBuffer sb = new StringBuffer();
    sb.append("/////start\n");

    IJavaReferenceType jdiType = frame.getReferenceType();
    IType iType = JavaDebugUtils.resolveType(jdiType);

    // could be a closure type that doesn't exist in source
    if (iType != null && !iType.exists() && iType.getParent().getElementType() == IJavaElement.TYPE) {
        iType = (IType) iType.getParent();
    }/*from  www  .  j  av a2  s . co m*/

    if (iType != null && !iType.isInterface()) {
        ITypeRoot root = iType.getTypeRoot();
        if (root instanceof ICompilationUnit) {
            // really, a GroovyCompilationUnit
            ICompilationUnit unit = (ICompilationUnit) root;

            // package statement
            IPackageDeclaration[] pDecls = unit.getPackageDeclarations();
            if (pDecls.length > 0) {
                sb.append("package " + pDecls[0].getElementName() + ";\n");
                packageName = pDecls[0].getElementName() + ".";
            } else {
                packageName = "";
            }

            // imports
            IImportContainer container = unit.getImportContainer();
            if (container != null && container.exists()) {
                IJavaElement[] children = container.getChildren();
                for (int j = 0; j < children.length; j++) {
                    IImportDeclaration importChild = (IImportDeclaration) children[j];
                    sb.append("import ");
                    if (Flags.isStatic(importChild.getFlags())) {
                        sb.append("static ");
                    }
                    sb.append(importChild.getElementName());
                    if (importChild.isOnDemand() && !(importChild.getElementName().endsWith(".*"))) {
                        sb.append(".*");
                    }
                    sb.append(";\n");
                }
            }

            // types...create stubs for the types just so that they can be instantiated and referenced
            IType[] allTypes = unit.getAllTypes();
            for (IType otherType : allTypes) {
                if (!otherType.equals(iType)) {
                    if (otherType.isInterface()) {
                        sb.append("interface ");
                    } else if (otherType.isAnnotation()) {
                        // probably don't need this
                        sb.append("@interface ");
                    } else if (otherType.isEnum()) {
                        sb.append("enum ");
                    } else {
                        sb.append("class ");
                    }

                    // use '$' so that inner classes can be remembered
                    String qualifiedTypeName = otherType.getFullyQualifiedName('$');
                    int dotIndex = qualifiedTypeName.lastIndexOf('.') + 1;
                    String simpleName = qualifiedTypeName.substring(dotIndex);
                    sb.append(simpleName + "{ }\n");
                }
            }
        }
    }

    sb.append(snippet);
    sb.append("\n/////end");
    return sb.toString();
}

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

License:Open Source License

private static int findPositionForImport(ICompilationUnit compilationUnit) throws JavaModelException {
    if (compilationUnit.getImportContainer().exists()) {
        return compilationUnit.getImportContainer().getSourceRange().getOffset()
                + compilationUnit.getImportContainer().getSourceRange().getLength();
    } else {//ww  w  .j a  v a2 s .c o m
        IPackageDeclaration[] packageDeclarations = compilationUnit.getPackageDeclarations();
        if (packageDeclarations.length == 0) {
            return 0;
        }
        int position = 0;
        for (IPackageDeclaration declaration : packageDeclarations) {
            position = declaration.getSourceRange().getOffset() + declaration.getSourceRange().getLength();
        }
        return position;
    }
}

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);
                }/*from ww w .  j  a  v  a2  s  . c  o  m*/

                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);
        }
    }
}