Example usage for org.eclipse.jdt.core IPackageFragmentRoot createPackageFragment

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot createPackageFragment

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot createPackageFragment.

Prototype

IPackageFragment createPackageFragment(String name, boolean force, IProgressMonitor monitor)
        throws JavaModelException;

Source Link

Document

Creates and returns a package fragment in this root with the given dot-separated package name.

Usage

From source file:org.eclim.plugin.jdt.command.refactoring.MoveCommand.java

License:Open Source License

@Override
public Refactor createRefactoring(CommandLine commandLine) throws Exception {
    String project = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    String packName = commandLine.getValue(Options.NAME_OPTION);

    ICompilationUnit src = JavaUtils.getCompilationUnit(project, file);
    IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(src);
    IPackageFragment pack = root.getPackageFragment(packName);
    ICompilationUnit dest = pack.getCompilationUnit(src.getElementName());
    if (dest.exists()) {
        throw new RefactorException(
                Services.getMessage("move.element.exists", pack.getElementName(), src.getElementName()));
    }/*from   w w  w  .  j  av  a 2 s  .  co  m*/

    if (!pack.exists()) {
        pack = root.createPackageFragment(packName, true, null);
    }

    IMovePolicy policy = ReorgPolicyFactory.createMovePolicy(new IResource[0], new IJavaElement[] { src });

    JavaMoveProcessor processor = new JavaMoveProcessor(policy);
    IReorgDestination destination = ReorgDestinationFactory.createDestination(pack);
    RefactoringStatus status = processor.setDestination(destination);
    if (status.hasError()) {
        throw new RefactorException(status);
    }

    Shell shell = EclimPlugin.getShell();
    processor.setCreateTargetQueries(new CreateTargetQueries(shell));
    processor.setReorgQueries(new ReorgQueries(shell));

    Refactoring refactoring = new MoveRefactoring(processor);

    // create a more descriptive name than the default.
    String desc = refactoring.getName() + " (" + src.getElementName() + " -> " + pack.getElementName() + ')';

    return new Refactor(desc, refactoring);
}

From source file:org.eclim.plugin.jdt.command.src.NewCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    String projectName = commandLine.getValue(Options.PROJECT_OPTION);
    String type = commandLine.getValue(Options.TYPE_OPTION);
    String name = commandLine.getValue(Options.NAME_OPTION);
    String srcRoot = commandLine.getValue(Options.ROOT_OPTION);

    // handle someone typing a file path instead of a fully qualified class name
    if (name.endsWith(".java")) {
        name = name.substring(0, name.length() - 5);
    }/*from  w ww . j a  v  a  2s .c  o m*/
    name = name.replace('/', '.');

    int classStart = name.lastIndexOf('.');
    final String packageName = classStart >= 0 ? name.substring(0, classStart) : name;
    final String typeName = classStart >= 0 ? name.substring(classStart + 1) : name;
    final String fileName = typeName + ".java";

    IJavaProject javaProject = JavaUtils.getJavaProject(projectName);

    ArrayList<IPackageFragmentRoot> roots = new ArrayList<IPackageFragmentRoot>();

    // find all roots the requested package is found in.
    for (IPackageFragment f : javaProject.getPackageFragments()) {
        if (f.getElementName().equals(packageName)) {
            IJavaElement parent = f.getParent();
            while (parent != null) {
                if (parent instanceof IPackageFragmentRoot) {
                    IPackageFragmentRoot root = (IPackageFragmentRoot) parent;
                    if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                        roots.add(root);
                    }
                    break;
                }
                parent = parent.getParent();
            }
        }
    }

    // the package isn't found in any roots
    if (roots.size() == 0) {
        // no root supplied, so we have to add all src roots to a list for the
        // user to choose from.
        for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
            if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                roots.add(root);
            }
        }
    }

    // still no source roots, so we have to fail
    if (roots.size() == 0) {
        throw new RuntimeException("No project source directories found.");
    }

    if (roots.size() > 1) {
        // user chosen root supplied, so grab that one.
        if (srcRoot != null) {
            roots.clear();
            for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
                if (root.getKind() == IPackageFragmentRoot.K_SOURCE && getPath(root).equals(srcRoot)) {
                    roots.add(root);
                    break;
                }
            }

            if (roots.size() == 0) {
                throw new RuntimeException("Unable to find project source directory: " + srcRoot);
            }
        }

        if (roots.size() > 1) {
            ArrayList<String> srcRoots = new ArrayList<String>();
            for (IPackageFragmentRoot root : roots) {
                srcRoots.add(getPath(root));
            }
            return srcRoots;
        }
    }

    IPackageFragmentRoot root = roots.get(0);
    IPackageFragment fragment = root.createPackageFragment(packageName, false, null);

    // locate the to-be created file
    File fragmentPath = fragment.getUnderlyingResource().getLocation().toFile();
    final File file = new File(fragmentPath, fileName);

    // make sure eclipse is up to date, in case the user
    //  deleted the file outside of eclipse's knowledge
    fragment.getUnderlyingResource().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());

    // create!
    final String content = String.format(TEMPLATE, packageName, getType(type), typeName);

    // NB: If we delete the file outside of Eclipse'
    //  awareness, it will whine if we then try to
    //  recreate it. So, if we *know* the file doesn't
    //  exist, force it.
    ICompilationUnit unit = fragment.createCompilationUnit(fileName, content, false, new NullProgressMonitor());

    if (unit == null || !file.exists()) {
        throw new RuntimeException("Could not create " + file);
    }

    JavaUtils.format(unit, CodeFormatter.K_COMPILATION_UNIT, 0, unit.getBuffer().getLength());

    return file.getAbsolutePath();
}

From source file:org.eclipse.ajdt.core.tests.AJDTCoreTestCase.java

License:Open Source License

public IPackageFragment createPackage(String name, IPackageFragmentRoot sourceFolder, IJavaProject javaProject)
        throws CoreException {
    if (sourceFolder == null)
        sourceFolder = createDefaultSourceFolder(javaProject);
    return sourceFolder.createPackageFragment(name, false, null);
}

From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java

License:Open Source License

/**
 * Creates the new type using the entered field values.
 * //from  w w  w . j  a  va  2s  .  co m
 * @param monitor a progress monitor to report progress.
 * @throws CoreException Thrown when the creation failed.
 * @throws InterruptedException Thrown when the operation was canceled.
 */
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }

    monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 8);

    IPackageFragmentRoot root = getPackageFragmentRoot();
    IPackageFragment pack = getPackageFragment();
    if (pack == null) {
        pack = root.getPackageFragment(""); //$NON-NLS-1$
    }

    if (!pack.exists()) {
        String packName = pack.getElementName();
        pack = root.createPackageFragment(packName, true, new SubProgressMonitor(monitor, 1));
    } else {
        monitor.worked(1);
    }

    boolean needsSave;
    ICompilationUnit connectedCU = null;

    try {
        String typeName = getTypeNameWithoutParameters();

        boolean isInnerClass = isEnclosingTypeSelected();

        IType createdType;
        ImportsManager imports;
        int indent = 0;

        Set /* String (import names) */ existingImports;

        String lineDelimiter = null;
        if (!isInnerClass) {
            lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());

            String cuName = getCompilationUnitName(typeName);
            ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, //$NON-NLS-1$
                    new SubProgressMonitor(monitor, 2));
            // create a working copy with a new owner

            needsSave = true;
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now a (primary) working copy
            connectedCU = parentCU;

            IBuffer buffer = parentCU.getBuffer();

            String simpleTypeStub = constructSimpleTypeStub();
            String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
            buffer.setContents(cuContent);

            CompilationUnit astRoot = createASTForImports(parentCU);
            existingImports = getExistingImports(astRoot);

            imports = new ImportsManager(astRoot);
            // add an import that will be removed again. Having this import solves 14661
            imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));

            String typeContent = constructTypeStub(parentCU, imports, lineDelimiter);

            int index = cuContent.lastIndexOf(simpleTypeStub);
            if (index == -1) {
                AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0);
                int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
                int end = typeNode.getStartPosition() + typeNode.getLength();
                buffer.replace(start, end - start, typeContent);
            } else {
                buffer.replace(index, simpleTypeStub.length(), typeContent);
            }

            createdType = parentCU.getType(typeName);
        } else {
            IType enclosingType = getEnclosingType();

            ICompilationUnit parentCU = enclosingType.getCompilationUnit();

            needsSave = !parentCU.isWorkingCopy();
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now for sure (primary) a working copy
            connectedCU = parentCU;

            CompilationUnit astRoot = createASTForImports(parentCU);
            imports = new ImportsManager(astRoot);
            existingImports = getExistingImports(astRoot);

            // add imports that will be removed again. Having the imports solves 14661
            IType[] topLevelTypes = parentCU.getTypes();
            for (int i = 0; i < topLevelTypes.length; i++) {
                imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
            }

            lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType);
            StringBuffer content = new StringBuffer();

            String comment = getTypeComment(parentCU, lineDelimiter);
            if (comment != null) {
                content.append(comment);
                content.append(lineDelimiter);
            }

            content.append(constructTypeStub(parentCU, imports, lineDelimiter));
            IJavaElement sibling = null;
            if (enclosingType.isEnum()) {
                IField[] fields = enclosingType.getFields();
                if (fields.length > 0) {
                    for (int i = 0, max = fields.length; i < max; i++) {
                        if (!fields[i].isEnumConstant()) {
                            sibling = fields[i];
                            break;
                        }
                    }
                }
            } else {
                IJavaElement[] elems = enclosingType.getChildren();
                sibling = elems.length > 0 ? elems[0] : null;
            }

            createdType = enclosingType.createType(content.toString(), sibling, false,
                    new SubProgressMonitor(monitor, 2));

            indent = StubUtility.getIndentUsed(enclosingType) + 1;
        }
        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // add imports for superclass/interfaces, so types can be resolved correctly

        ICompilationUnit cu = createdType.getCompilationUnit();

        imports.create(false, new SubProgressMonitor(monitor, 1));

        JavaModelUtil.reconcile(cu);

        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // set up again
        CompilationUnit astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);

        createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));

        // add imports
        imports.create(false, new SubProgressMonitor(monitor, 1));

        removeUnusedImports(cu, existingImports, false);

        JavaModelUtil.reconcile(cu);

        ISourceRange range = createdType.getSourceRange();

        IBuffer buf = cu.getBuffer();
        String originalContent = buf.getText(range.getOffset(), range.getLength());

        String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
                originalContent, indent, lineDelimiter, pack.getJavaProject());
        formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);
        if (!isInnerClass) {
            String fileComment = getFileComment(cu);
            if (fileComment != null && fileComment.length() > 0) {
                buf.replace(0, 0, fileComment + lineDelimiter);
            }
        }
        fCreatedType = createdType;

        if (needsSave) {
            cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
        } else {
            monitor.worked(1);
        }

    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
        monitor.done();
    }
}

From source file:org.eclipse.ajdt.ui.tests.builder.BuilderTest.java

License:Open Source License

/**
 * Test for bug 78579 - when you create a package, this should be copied
 * over to the bin dir. Similarly, when you delete the package, the bin
 * dir should be updated.// w ww. j a  v a 2 s.c o m
 * 
 * @throws Exception
 */
public void testCreateAndDeleteNewPackage() throws Exception {
    IProject simpleProject = createPredefinedProject("AnotherSimpleAJProject"); //$NON-NLS-1$

    IJavaProject javaProject = JavaCore.create(simpleProject);
    waitForJobsToComplete();

    String srcPath = javaProject.getUnderlyingResource().getLocation().toOSString() + File.separator + "src" //$NON-NLS-1$
            + File.separator + "newPackage"; //$NON-NLS-1$

    String binPath = javaProject.getUnderlyingResource().getLocation().toOSString() + File.separator + "bin" //$NON-NLS-1$
            + File.separator + "newPackage"; //$NON-NLS-1$

    IFolder src = simpleProject.getFolder("src"); //$NON-NLS-1$
    if (!src.exists()) {
        src.create(true, true, null);
    }
    waitForJobsToComplete();

    IFolder newPackage = src.getFolder("newPackage"); //$NON-NLS-1$
    assertFalse("newPackage should not exist under src tree! (path=" + srcPath + ")", newPackage.exists()); //$NON-NLS-1$ //$NON-NLS-2$

    IFolder bin = simpleProject.getFolder("bin"); //$NON-NLS-1$
    if (!bin.exists()) {
        bin.create(true, true, null);
    }
    waitForJobsToComplete();
    IFolder newBinPackage = bin.getFolder("newPackage"); //$NON-NLS-1$
    assertFalse("newPackage should not exist under bin tree! (path=" + binPath + ")", newBinPackage.exists()); //$NON-NLS-1$ //$NON-NLS-2$

    waitForJobsToComplete();

    String str = "AnotherSimpleAJProject" + File.separator + "src"; //$NON-NLS-1$ //$NON-NLS-2$
    IPath path = new Path(str);
    IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(res);
    root.createPackageFragment("newPackage", true, null); //$NON-NLS-1$

    simpleProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    waitForJobsToComplete();

    // If either of these fail, then it's more likely than not to be
    // down to the timings of driving this programatically (this is
    // why there is a sleep above.
    IFolder newPackage2 = src.getFolder("newPackage"); //$NON-NLS-1$
    assertTrue("newPackage should exist under src tree! (path=" + srcPath + ")", newPackage2.exists()); //$NON-NLS-1$ //$NON-NLS-2$
    waitForJobsToComplete();
    simpleProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    waitForJobsToComplete();
    IFolder newBinPackage2 = bin.getFolder("newPackage"); //$NON-NLS-1$
    assertTrue("newPackage should exist under bin tree! (path=" + binPath + ")", newBinPackage2.exists()); //$NON-NLS-1$ //$NON-NLS-2$
    waitForJobsToComplete();

    newPackage.delete(true, null);
    waitForJobsToComplete();

    // If either of these fail, then it's more likely than not to be
    // down to the timings of driving this programatically (this is
    // why there is a sleep above.
    IFolder newPackage3 = src.getFolder("newPackage"); //$NON-NLS-1$
    assertFalse("newPackage should not exist under src tree! (path=" + srcPath + ")", newPackage3.exists()); //$NON-NLS-1$ //$NON-NLS-2$
    waitForJobsToComplete();
    simpleProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    waitForJobsToComplete();
    IFolder newBinPackage3 = bin.getFolder("newPackage"); //$NON-NLS-1$
    assertFalse("newPackage should not exist under bin tree! (path=" + binPath + ")", newBinPackage3.exists()); //$NON-NLS-1$ //$NON-NLS-2$

    waitForJobsToComplete();
}

From source file:org.eclipse.che.jdt.core.ImportOrganizeTest.java

License:Open Source License

@Test
public void test1() throws Exception {
    File junitSrcArchive = new File(JUnitSourceSetup.class.getClassLoader()
            .getResource(JavaProjectHelper.JUNIT_SRC_381.toOSString()).getFile());
    assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());

    JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", junitSrcArchive,
            JavaProjectHelper.JUNIT_SRC_ENCODING);

    ICompilationUnit cu = (ICompilationUnit) fJProject1
            .findElement(new Path("junit/runner/BaseTestRunner.java"));
    assertNotNull("BaseTestRunner.java", cu);

    IPackageFragmentRoot root = (IPackageFragmentRoot) cu.getParent().getParent();
    IPackageFragment pack = root.createPackageFragment("mytest", true, null);

    ICompilationUnit colidingCU = pack.getCompilationUnit("TestListener.java");
    colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);

    String[] order = new String[0];
    IChooseImportQuery query = createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" },
            new int[] { 2 });

    OrganizeImportsOperation op = createOperation(cu, order, 99, false, true, true, query);
    op.run(null);/*from   ww w.j  a v a2  s . com*/

    assertImports(cu, new String[] { "java.io.BufferedReader", "java.io.File", "java.io.FileInputStream",
            "java.io.FileOutputStream", "java.io.IOException", "java.io.InputStream", "java.io.PrintWriter",
            "java.io.StringReader", "java.io.StringWriter", "java.lang.reflect.InvocationTargetException",
            "java.lang.reflect.Method", "java.lang.reflect.Modifier", "java.text.NumberFormat",
            "java.util.Properties", "junit.framework.AssertionFailedError", "junit.framework.Test",
            "junit.framework.TestListener", "junit.framework.TestSuite" });
}

From source file:org.eclipse.che.jdt.core.ImportOrganizeTest.java

License:Open Source License

@Test
public void test1WithOrder() throws Exception {
    File junitSrcArchive = new File(JUnitSourceSetup.class.getClassLoader()
            .getResource(JavaProjectHelper.JUNIT_SRC_381.toOSString()).getFile());
    assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());

    JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", junitSrcArchive,
            JavaProjectHelper.JUNIT_SRC_ENCODING);

    ICompilationUnit cu = (ICompilationUnit) fJProject1
            .findElement(new Path("junit/runner/BaseTestRunner.java"));
    assertNotNull("BaseTestRunner.java", cu);

    IPackageFragmentRoot root = (IPackageFragmentRoot) cu.getParent().getParent();
    IPackageFragment pack = root.createPackageFragment("mytest", true, null);

    ICompilationUnit colidingCU = pack.getCompilationUnit("TestListener.java");
    colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);

    String[] order = new String[] { "junit", "java.text", "java.io", "java" };
    IChooseImportQuery query = createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" },
            new int[] { 2 });

    OrganizeImportsOperation op = createOperation(cu, order, 99, false, true, true, query);
    op.run(null);/* w w w. ja  va  2s  .  c  om*/

    assertImports(cu, new String[] { "junit.framework.AssertionFailedError", "junit.framework.Test",
            "junit.framework.TestListener", "junit.framework.TestSuite", "java.text.NumberFormat",
            "java.io.BufferedReader", "java.io.File", "java.io.FileInputStream", "java.io.FileOutputStream",
            "java.io.IOException", "java.io.InputStream", "java.io.PrintWriter", "java.io.StringReader",
            "java.io.StringWriter", "java.lang.reflect.InvocationTargetException", "java.lang.reflect.Method",
            "java.lang.reflect.Modifier", "java.util.Properties" });
}

From source file:org.eclipse.che.jdt.core.ImportOrganizeTest.java

License:Open Source License

@Test
public void testVariousTypeReferences() throws Exception {
    IPackageFragmentRoot sourceFolder = JavaProjectHelper.addSourceContainer(fJProject1, "src");

    IPackageFragment pack = sourceFolder.createPackageFragment("test", false, null);
    for (int ch = 'A'; ch < 'M'; ch++) {
        String name = String.valueOf((char) ch);
        ICompilationUnit cu = pack.getCompilationUnit(name + ".java");
        String content = "public class " + name + " {}";
        cu.createType(content, null, false, null);
    }/* w  w w . j a  v a2 s  . c  o  m*/
    for (int ch = 'A'; ch < 'M'; ch++) {
        String name = "I" + String.valueOf((char) ch);
        ICompilationUnit cu = pack.getCompilationUnit(name + ".java");
        String content = "public interface " + name + " {}";
        cu.createType(content, null, false, null);
    }

    StringBuffer buf = new StringBuffer();
    buf.append("public class ImportTest extends A implements IA, IB {\n");
    buf.append("  private B fB;\n");
    buf.append("  private Object fObj= new C();\n");
    buf.append("  public IB foo(IC c, ID d) throws IOException {\n");
    buf.append("   Object local= (D) fObj;\n");
    buf.append("   if (local instanceof E) {};\n");
    buf.append("   return null;\n");
    buf.append("  }\n");
    buf.append("}\n");

    pack = sourceFolder.createPackageFragment("other", false, null);
    ICompilationUnit cu = pack.getCompilationUnit("ImportTest.java");
    cu.createType(buf.toString(), null, false, null);

    String[] order = new String[0];
    IChooseImportQuery query = createQuery("ImportTest", new String[] {}, new int[] {});

    OrganizeImportsOperation op = createOperation(cu, order, 99, false, true, true, query);
    op.run(null);

    assertImports(cu, new String[] { "java.io.IOException", "test.A", "test.B", "test.C", "test.D", "test.E",
            "test.IA", "test.IB", "test.IC", "test.ID", });
}

From source file:org.eclipse.che.jdt.core.ImportOrganizeTest.java

License:Open Source License

@Test
public void testInnerClassVisibility() throws Exception {
    IPackageFragmentRoot sourceFolder = JavaProjectHelper.addSourceContainer(fJProject1, "src");

    IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("public class C {\n");
    buf.append("  public static class C1 {\n");
    buf.append("    public static class C2 {\n");
    buf.append("    }\n");
    buf.append("  }\n");
    buf.append("}\n");
    pack1.createCompilationUnit("C.java", buf.toString(), false, null);

    IPackageFragment pack2 = sourceFolder.createPackageFragment("test2", false, null);

    buf = new StringBuffer();
    buf.append("package test2;\n");

    buf.append("import test2.A.A1;\n");
    buf.append("import test2.A.A1.A2;\n");
    buf.append("import test2.A.A1.A2.A3;\n");
    buf.append("import test2.A.B1;\n");
    buf.append("import test2.A.B1.B2;\n");
    buf.append("import test1.C;\n");
    buf.append("import test1.C.C1.C2;\n");

    buf.append("public class A {\n");
    buf.append("    public static class A1 {\n");
    buf.append("        public static class A2 {\n");
    buf.append("            public static class A3 {\n");
    buf.append("            }\n");
    buf.append("        }\n");
    buf.append("    }\n");

    buf.append("    public static class B1 {\n");
    buf.append("        public static class B2 {\n");
    buf.append("        }\n");

    buf.append("        public static class B3 {\n");
    buf.append("            public static class B4 extends C {\n");
    buf.append("                B4 b4;\n");
    buf.append("                B3 b3;\n");
    buf.append("                B2 b2;\n");
    buf.append("                B1 b1;\n");
    buf.append("                A1 a1;\n");
    buf.append("                A2 a2;\n");
    buf.append("                A3 a3;\n");
    buf.append("                C1 c1;\n");
    buf.append("                C2 c2;\n");
    buf.append("            }\n");
    buf.append("        }\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu2 = pack2.createCompilationUnit("A.java", buf.toString(), false, null);

    String[] order = new String[0];
    IChooseImportQuery query = createQuery("A", new String[] {}, new int[] {});

    OrganizeImportsOperation op = createOperation(cu2, order, 99, false, true, true, query);
    op.run(null);/*  w w w. j  av a 2 s. com*/

    assertImports(cu2, new String[] { "test1.C", "test1.C.C1.C2", "test2.A.A1.A2", "test2.A.A1.A2.A3" });
}

From source file:org.eclipse.che.jdt.core.ImportOrganizeTest.java

License:Open Source License

@Test
public void testClearImports() throws Exception {
    IPackageFragmentRoot sourceFolder = JavaProjectHelper.addSourceContainer(fJProject1, "src");

    IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.Vector;\n");
    buf.append("public class C {\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("C.java", buf.toString(), false, null);

    String[] order = new String[0];
    IChooseImportQuery query = createQuery("C", new String[] {}, new int[] {});

    OrganizeImportsOperation op = createOperation(cu, order, 99, false, true, true, query);
    op.run(null);// www  . j  av a2s.c o m

    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("public class C {\n");
    buf.append("}\n");
    assertEqualString(cu.getSource(), buf.toString());
}