Example usage for org.eclipse.jdt.core.dom ImportDeclaration setStatic

List of usage examples for org.eclipse.jdt.core.dom ImportDeclaration setStatic

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom ImportDeclaration setStatic.

Prototype

public void setStatic(boolean isStatic) 

Source Link

Document

Sets whether this import declaration is a static import (added in JLS3 API).

Usage

From source file:com.windowtester.eclipse.ui.convert.WTConvertAPIContext.java

License:Open Source License

/**
 * Construct a new import declaration/*  w  ww.j  a v  a  2  s .  c om*/
 * 
 * @param typeName the fully qualified type name (not <code>null</code>, not empty)
 * @param isStatic <code>true</code> if the import should be a static import
 * @return the import declaration (not <code>null</code>)
 */
private ImportDeclaration newImport(String typeName, boolean isStatic) {
    ImportDeclaration newImport = compUnit.getAST().newImportDeclaration();
    newImport.setStatic(isStatic);
    int start = 7; // 7 = position after the "import" keyword and one space
    if (isStatic)
        start += 7; // add length of "static" keyword and one space
    newImport.setName(newName(typeName, start));
    newImport.setSourceRange(0, newImport.toString().trim().length());
    return newImport;
}

From source file:de.crowdcode.kissmda.extensions.importpacker.ImportPackerTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test// w ww  .jav  a 2 s . c  o  m
public void test_Existing_Static_Imports2() {
    AST ast = AST.newAST(AST.JLS4);
    CompilationUnit cu = ast.newCompilationUnit();

    PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
    packageDeclaration.setName(ast.newName("org.kissmda.test.junit"));
    cu.setPackage(packageDeclaration);

    ImportDeclaration importDeclaration = ast.newImportDeclaration();
    importDeclaration.setName(ast.newName("org.junit.Assert.assertNotNull"));
    importDeclaration.setStatic(true);
    cu.imports().add(importDeclaration);

    logger.info(cu.toString());
    new ImportPacker(cu).pack();

    logger.info(cu.toString());

    assertEquals("package org.kissmda.test.junit;\n" //
            + "import static org.junit.Assert.assertNotNull;", cu.toString().trim());
}

From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.CreateDoPrivilegedBlockResolution.java

License:Open Source License

private ImportDeclaration createImportDeclaration(AST ast, String name, boolean isStatic) {
    ImportDeclaration importDeclaration = ast.newImportDeclaration();
    importDeclaration.setName(ast.newName(name));
    importDeclaration.setStatic(isStatic);
    return importDeclaration;
}

From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.util.ASTUtil.java

License:Open Source License

public static void addImports(ASTRewrite rewrite, CompilationUnit compilationUnit,
        Comparator<? super ImportDeclaration> comparator, boolean staticImports, String... imports) {
    requireNonNull(comparator, "import comparator");
    requireNonNull(imports, "imports");

    final AST ast = rewrite.getAST();
    SortedSet<ImportDeclaration> importDeclarations = new TreeSet<ImportDeclaration>(comparator);
    for (String importName : imports) {
        ImportDeclaration importDeclaration = ast.newImportDeclaration();
        importDeclaration.setName(ast.newName(importName));
        importDeclaration.setStatic(staticImports);
        importDeclarations.add(importDeclaration);
    }/*from  www  .j  a v a 2 s. c o m*/
    addImports(rewrite, compilationUnit, importDeclarations);
}

From source file:edu.umd.cs.findbugs.quickfix.util.ASTUtil.java

License:Open Source License

public static void addImports(ASTRewrite rewrite, CompilationUnit compilationUnit,
        Comparator<? super ImportDeclaration> comparator, boolean staticImports, String... imports) {
    checkForNull(comparator, "import comparator");
    checkForNull(imports, "imports");

    final AST ast = rewrite.getAST();
    SortedSet<ImportDeclaration> importDeclarations = new TreeSet<ImportDeclaration>(comparator);
    for (String importName : imports) {
        ImportDeclaration importDeclaration = ast.newImportDeclaration();
        importDeclaration.setName(ast.newName(importName));
        importDeclaration.setStatic(staticImports);
        importDeclarations.add(importDeclaration);
    }/* w  w  w .  java2s . c  o  m*/
    addImports(rewrite, compilationUnit, importDeclarations);
}

From source file:java5totext.input.JDTVisitor.java

License:Open Source License

@Override
public void endVisit(org.eclipse.jdt.core.dom.ImportDeclaration node) {
    ImportDeclaration element = (ImportDeclaration) this.binding.get(node);
    this.initializeNode(element, node);
    element.setStatic(new Boolean(node.isStatic()));

    if (this.binding.get(node.getName()) != null)
        element.setImportedElement((NamedElementRef) this.binding.get(node.getName()));
    this.imports.add(element);
}

From source file:lang.java.jdt.internal.UnqualifyTypeNames.java

License:Open Source License

private void visitCompilationUnit() {
    ICompilationUnit icu = JavaCore.createCompilationUnitFrom(file);

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setResolveBindings(true);/* w  ww. j  av a  2  s. c  o  m*/
    parser.setSource(icu);

    CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    IProblem[] problems = cu.getProblems();
    for (int i = 0; i < problems.length; i++) {
        if (problems[i].isError()) {
            int offset = problems[i].getSourceStart();
            int length = problems[i].getSourceEnd() - offset;
            int sl = problems[i].getSourceLineNumber();
            ISourceLocation pos = VF.sourceLocation(loc.getURI(), offset, length, sl, sl, 0, 0);
            throw new Throw(VF.string("Error(s) in compilation unit: " + problems[i].getMessage()), pos, null);
        }
    }

    // Figure out which imports we need to keep and/or need to add
    cu.accept(new GatherUsedPackages());
    calculateImportsToAdd();

    // Now, start the rewrite process, first with the imports, then with the various
    // types found in the code in the file
    rewriter = ASTRewrite.create(cu.getAST());
    ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY);

    // Throw away the current imports
    List<?> imps = lrw.getOriginalList();
    for (int i = 0; i < imps.size(); ++i) {
        lrw.remove((ASTNode) imps.get(i), null);
    }

    // Add the statically imported types back in
    for (String s : importedFullNames) {
        ImportDeclaration id = cu.getAST().newImportDeclaration();
        id.setName(cu.getAST().newName(s));
        id.setStatic(true);
        lrw.insertLast(id, null);
    }

    // Add the new imports back in
    String[] whatever = { "A" };
    String[] sortedImports = importsToAdd.toArray(whatever);
    Arrays.sort(sortedImports);

    for (String s : sortedImports) {
        ImportDeclaration id = cu.getAST().newImportDeclaration();
        id.setName(cu.getAST().newName(s));
        id.setStatic(false);
        lrw.insertLast(id, null);
    }

    cu.accept(this);

    try {
        IPath path = file.getFullPath();

        ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
        bufferManager.connect(path, LocationKind.IFILE, new NullProgressMonitor());

        ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);

        IDocument doc = textFileBuffer.getDocument();
        TextEdit te = rewriter.rewriteAST(doc, null);
        te.apply(doc);
        textFileBuffer.commit(new NullProgressMonitor(), true);

        bufferManager.disconnect(path, LocationKind.IFILE, new NullProgressMonitor());
    } catch (CoreException e) {
        throw new Throw(VF.string("Error(s) in rewrite of compilation unit: " + e.getMessage()), loc, null);
    } catch (MalformedTreeException e) {
        throw new Throw(VF.string("Error(s) in rewrite of compilation unit: " + e.getMessage()), loc, null);
    } catch (BadLocationException e) {
        throw new Throw(VF.string("Error(s) in rewrite of compilation unit: " + e.getMessage()), loc, null);
    }
}

From source file:org.eclipse.babel.tapiji.tools.java.util.ASTutils.java

License:Open Source License

public static void createImport(IDocument doc, IResource resource, CompilationUnit cu, AST ast,
        ASTRewrite rewriter, String qualifiedClassName) throws CoreException, BadLocationException {

    ImportFinder impFinder = new ImportFinder(qualifiedClassName);

    cu.accept(impFinder);/*  w  w  w  .j  a  va  2  s  .co  m*/

    if (!impFinder.isImportFound()) {
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName(qualifiedClassName.split("\\.")));
        id.setStatic(false);

        ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY);
        lrw.insertFirst(id, null);
    }

}

From source file:org.eclipse.emf.texo.generator.ImportResolver.java

License:Open Source License

/**
 * Determine all needed imports, retain existing imports if needed, update import section in the source and replace
 * all qualified names with their non-qualified equivalent (if there is an import statement).
 * //  w ww. j  a v a 2  s .  com
 * @return the updated source
 */
public String resolve() {
    Check.isNotNullArgument(source, "source"); //$NON-NLS-1$
    Check.isNotNullArgument(javaProject, "javaProject"); //$NON-NLS-1$

    // get the package name and the list of existing and needed types
    final ImportReferenceCollector importReferenceCollector = new ImportReferenceCollector();
    compilationUnit.accept(importReferenceCollector);

    // get the list of needed imports because of already present
    // non-qualified names.
    final List<ImportDeclaration> importDeclarations = determineCurrentNeededImports(
            importReferenceCollector.getExistingImports(), importReferenceCollector.getQualifiedTypes());

    final List<String> cleanedQualifedNames = cleanQualifiedNames(importReferenceCollector.getQualifiedTypes());

    // now determine which new ones should be added and if so prevent
    // collisions
    final List<String> importedNonQualifiedNames = importedNonQualifiedNames(importDeclarations);
    final List<String> namesToImport = new ArrayList<String>();

    for (String declaredTypeName : importReferenceCollector.getUnqualifiedDeclaredTypes()) {
        importedNonQualifiedNames.add(getLastSegment(declaredTypeName));
    }

    // add all the retained imports also to the list
    for (final ImportDeclaration importDeclaration : importDeclarations) {
        final String nameToImport = importDeclaration.getName().getFullyQualifiedName();
        if (!namesToImport.contains(nameToImport)) {
            namesToImport.add(nameToImport);
        }
    }

    // handle a special case that there is a collision between a class in the same
    // package and a class imported from another package. In this case the class imported
    // from the other package should not be unqualified. This is accomplished by setting the
    // imports for the same package first, then later imports are recognized as collisions
    final String packageName = importReferenceCollector.getPackageName();
    Collections.sort(cleanedQualifedNames, new QualifiedNameSorter(packageName));

    for (final String qualifiedName : cleanedQualifedNames) {
        // already done
        final String correctedQualifiedName = getCorrectQualifiedName(qualifiedName);
        if (namesToImport.contains(correctedQualifiedName)) {
            continue;
        }
        // assume that it is covered by an already existing import
        if (!correctedQualifiedName.contains(DOT)) {
            continue;
        }
        final String lastSegment = getLastSegment(correctedQualifiedName);
        if (importedNonQualifiedNames.contains(lastSegment)) {
            // do not import these names to prevent collisions
            continue;
        }
        // if only one dot then also do not import
        // this is for example values.length (where values is an array)
        if (correctedQualifiedName.indexOf(DOT) == correctedQualifiedName.lastIndexOf(DOT)) {
            continue;
        }

        // prevent collisions later
        importedNonQualifiedNames.add(lastSegment);
        namesToImport.add(correctedQualifiedName);
    }

    final AST ast = compilationUnit.getAST();
    final List<ImportDeclaration> newImports = new ArrayList<ImportDeclaration>();
    for (final String nameToImport : namesToImport) {
        // don't do these ones
        if (inPackage(packageName, nameToImport)) {
            continue;
        }
        final Name name = ast.newName(nameToImport);
        final ImportDeclaration importDeclaration = ast.newImportDeclaration();
        importDeclaration.setOnDemand(false);
        importDeclaration.setStatic(false);
        importDeclaration.setName(name);
        newImports.add(importDeclaration);
    }
    try {
        String newSource = updateSource(namesToImport, newImports, ast,
                importReferenceCollector.getPackageName());

        // DIRTY HACK: solve an issue that if an EPackage has a sub package with the same
        // name that the import resolving of the subpackage goes wrong
        // for example the KdmModelPackage has a subpackage with the same name: KdmModelPackage
        // this results in this line in the source code:
        // kdm.KdmModelPackage.initialize();
        // which is incorrect
        for (String qualifiedName : cleanedQualifedNames) {
            // find the last two segments
            if (!qualifiedName.contains(DOT)) {
                continue;
            }
            final String[] parts = DOT_PATTERN.split(qualifiedName);
            if (parts.length > 1) {
                final String part1 = parts[parts.length - 2];
                final String part2 = parts[parts.length - 1];
                {
                    final String searchString = "\t" + part1 + DOT + part2 + ".initialize();"; //$NON-NLS-1$ //$NON-NLS-2$
                    if (newSource.contains(searchString)) {
                        newSource = newSource.replace(searchString, "\t" + qualifiedName + ".initialize();"); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }
                {
                    final String searchString = " " + part1 + DOT + part2 + ".initialize();"; //$NON-NLS-1$ //$NON-NLS-2$
                    if (newSource.contains(searchString)) {
                        newSource = newSource.replace(searchString, " " + qualifiedName + ".initialize();"); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }
                {
                    final String searchString = "\n" + part1 + DOT + part2 + ".initialize();"; //$NON-NLS-1$ //$NON-NLS-2$
                    if (newSource.contains(searchString)) {
                        newSource = newSource.replace(searchString, "\n" + qualifiedName + ".initialize();"); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }
            }
        }

        return newSource;
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.eclipse.jdt.core.dom.ASTConverter.java

License:Open Source License

public ImportDeclaration convertImport(org.eclipse.jdt.internal.compiler.ast.ImportReference importReference) {
    final ImportDeclaration importDeclaration = new ImportDeclaration(this.ast);
    final boolean onDemand = (importReference.bits
            & org.eclipse.jdt.internal.compiler.ast.ASTNode.OnDemand) != 0;
    final char[][] tokens = importReference.tokens;
    int length = importReference.tokens.length;
    final long[] positions = importReference.sourcePositions;
    if (length > 1) {
        importDeclaration.setName(setQualifiedNameNameAndSourceRanges(tokens, positions, importReference));
    } else {//from w  w  w. j  ava 2 s.c  o m
        final SimpleName name = new SimpleName(this.ast);
        name.internalSetIdentifier(new String(tokens[0]));
        final int start = (int) (positions[0] >>> 32);
        final int end = (int) (positions[0] & 0xFFFFFFFF);
        name.setSourceRange(start, end - start + 1);
        name.index = 1;
        importDeclaration.setName(name);
        if (this.resolveBindings) {
            recordNodes(name, importReference);
        }
    }
    importDeclaration.setSourceRange(importReference.declarationSourceStart,
            importReference.declarationEnd - importReference.declarationSourceStart + 1);
    importDeclaration.setOnDemand(onDemand);
    int modifiers = importReference.modifiers;
    if (modifiers != ClassFileConstants.AccDefault) {
        switch (this.ast.apiLevel) {
        case AST.JLS2_INTERNAL:
            importDeclaration.setFlags(importDeclaration.getFlags() | ASTNode.MALFORMED);
            break;
        default:
            if (modifiers == ClassFileConstants.AccStatic) {
                importDeclaration.setStatic(true);
            } else {
                importDeclaration.setFlags(importDeclaration.getFlags() | ASTNode.MALFORMED);
            }
        }
    }
    if (this.resolveBindings) {
        recordNodes(importDeclaration, importReference);
    }
    return importDeclaration;
}