/**
  * Adds a library entry with source attachment to a IJavaProject.
  *
  * @param jproject The parent project
  * @param path The path of the library to add
  * @param sourceAttachPath The source attachment path
  * @param sourceAttachRoot The source attachment root path
  * @return The handle of the created root
  * @throws JavaModelException
  */
 public static IPackageFragmentRoot addLibrary(
     IJavaProject jproject, IPath path, IPath sourceAttachPath, IPath sourceAttachRoot)
     throws JavaModelException {
   IClasspathEntry cpe = JavaCore.newLibraryEntry(path, sourceAttachPath, sourceAttachRoot);
   addToClasspath(jproject, cpe);
   IResource workspaceResource = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
   if (workspaceResource != null) {
     return jproject.getPackageFragmentRoot(workspaceResource);
   }
   return jproject.getPackageFragmentRoot(path.toString());
 }
  /**
   * Adds a source container to a IJavaProject.
   *
   * @param jproject The parent project
   * @param containerName The name of the new source container
   * @param inclusionFilters Inclusion filters to set
   * @param exclusionFilters Exclusion filters to set
   * @param outputLocation The location where class files are written to, <b>null</b> for project
   *     output folder
   * @return The handle to the new source container
   * @throws CoreException Creation failed
   */
  public static IPackageFragmentRoot addSourceContainer(
      IJavaProject jproject,
      String containerName,
      IPath[] inclusionFilters,
      IPath[] exclusionFilters,
      String outputLocation)
      throws CoreException {
    IProject project = jproject.getProject();
    IContainer container = null;
    if (containerName == null || containerName.length() == 0) {
      container = project;
    } else {
      IFolder folder = project.getFolder(containerName);
      if (!folder.exists()) {
        CoreUtility.createFolder(folder, false, true, null);
      }
      container = folder;
    }
    IPackageFragmentRoot root = jproject.getPackageFragmentRoot(container);

    IPath outputPath = null;
    if (outputLocation != null) {
      IFolder folder = project.getFolder(outputLocation);
      if (!folder.exists()) {
        CoreUtility.createFolder(folder, false, true, null);
      }
      outputPath = folder.getFullPath();
    }
    IClasspathEntry cpe =
        JavaCore.newSourceEntry(root.getPath(), inclusionFilters, exclusionFilters, outputPath);
    addToClasspath(jproject, cpe);
    return root;
  }
 /**
  * Initializes the source folder field with a valid package fragment root. The package fragment
  * root is computed from the given Java element.
  *
  * @param elem the Java element used to compute the initial package fragment root used as the
  *     source folder
  */
 protected void initContainerPage(IJavaElement elem) {
   IPackageFragmentRoot initRoot = null;
   if (elem != null) {
     initRoot = JavaModelUtil.getPackageFragmentRoot(elem);
     try {
       if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
         IJavaProject jproject = elem.getJavaProject();
         if (jproject != null) {
           initRoot = null;
           if (jproject.exists()) {
             IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
             for (int i = 0; i < roots.length; i++) {
               if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                 initRoot = roots[i];
                 break;
               }
             }
           }
           if (initRoot == null) {
             initRoot = jproject.getPackageFragmentRoot(jproject.getResource());
           }
         }
       }
     } catch (JavaModelException e) {
       JavaPlugin.log(e);
     }
   }
   setPackageFragmentRoot(initRoot, true);
 }
  /**
   * Tests that the output folder settings for a source folder cause the class file containers to be
   * updated
   */
  public void testWPUpdateOutputFolderSrcFolderChanged() throws Exception {
    IJavaProject project = getTestingProject();
    IApiComponent component = getWorkspaceBaseline().getApiComponent(project.getElementName());
    assertNotNull("the workspace component must exist", component);
    int before = component.getApiTypeContainers().length;

    ProjectUtils.addFolderToProject(project.getProject(), "bin3");
    IContainer container = ProjectUtils.addFolderToProject(project.getProject(), "src2");
    // add to bundle class path
    IBundleProjectService service = ProjectUtils.getBundleProjectService();
    IBundleClasspathEntry next =
        service.newBundleClasspathEntry(new Path("src2"), new Path("bin3"), new Path("next.jar"));
    ProjectUtils.addBundleClasspathEntry(project.getProject(), next);
    waitForAutoBuild();

    // retrieve updated component
    component = getWorkspaceBaseline().getApiComponent(project.getElementName());
    assertTrue(
        "there must be one more container after the change",
        before < component.getApiTypeContainers().length);
    IPackageFragmentRoot root = project.getPackageFragmentRoot(container);
    assertTrue(
        "the class file container for src2 must be 'bin3'",
        "bin3".equals(root.getRawClasspathEntry().getOutputLocation().toFile().getName()));
  }
 protected IPackageFragmentRoot getFragmentRoot(IJavaElement elem) {
   IPackageFragmentRoot initRoot = null;
   if (elem != null) {
     initRoot = (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
     try {
       if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
         IJavaProject jproject = elem.getJavaProject();
         if (jproject != null) {
           initRoot = null;
           if (jproject.exists()) {
             IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
             for (int i = 0; i < roots.length; i++) {
               if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                 initRoot = roots[i];
                 break;
               }
             }
           }
           if (initRoot == null) {
             initRoot = jproject.getPackageFragmentRoot(jproject.getResource());
           }
         }
       }
     } catch (JavaModelException e) {
       // TODO
       e.printStackTrace();
     }
   }
   return initRoot;
 }
Пример #6
0
 /**
  * Adds a new source container specified by the container name to the source path of the specified
  * project
  *
  * @param jproject
  * @param containerName
  * @return the package fragment root of the container name
  * @throws CoreException
  */
 public static IPackageFragmentRoot addSourceContainer(IJavaProject jproject, String containerName)
     throws CoreException {
   IProject project = jproject.getProject();
   IPackageFragmentRoot root =
       jproject.getPackageFragmentRoot(addFolderToProject(project, containerName));
   IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath());
   addToClasspath(jproject, cpe);
   return root;
 }
 /**
  * Adds a variable entry with source attachment to a IJavaProject. Can return null if variable can
  * not be resolved.
  *
  * @param jproject The parent project
  * @param path The variable path
  * @param sourceAttachPath The source attachment path (variable path)
  * @param sourceAttachRoot The source attachment root path (variable path)
  * @return The added package fragment root
  * @throws JavaModelException
  */
 public static IPackageFragmentRoot addVariableEntry(
     IJavaProject jproject, IPath path, IPath sourceAttachPath, IPath sourceAttachRoot)
     throws JavaModelException {
   IClasspathEntry cpe = JavaCore.newVariableEntry(path, sourceAttachPath, sourceAttachRoot);
   addToClasspath(jproject, cpe);
   IPath resolvedPath = JavaCore.getResolvedVariablePath(path);
   if (resolvedPath != null) {
     return jproject.getPackageFragmentRoot(resolvedPath.toString());
   }
   return null;
 }
Пример #8
0
  private IPackageFragmentRoot createSourceFolder() throws CoreException {
    IFolder folder = project.getFolder("src");
    folder.create(false, true, null);
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);

    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
    javaProject.setRawClasspath(newEntries, null);
    return root;
  }
Пример #9
0
 /** @see AbstractJavaSearchScope#packageFragmentRoot(String, int, String) */
 public IPackageFragmentRoot packageFragmentRoot(
     String resourcePathString, int jarSeparatorIndex, String jarPath) {
   int index = -1;
   boolean isJarFile = jarSeparatorIndex != -1;
   if (isJarFile) {
     // internal or external jar (case 3, 4, or 5)
     String relativePath = resourcePathString.substring(jarSeparatorIndex + 1);
     index = indexOf(jarPath, relativePath);
   } else {
     // resource in workspace (case 1 or 2)
     index = indexOf(resourcePathString);
   }
   if (index >= 0) {
     int idx = this.projectIndexes[index];
     String projectPath = idx == -1 ? null : (String) this.projectPaths.get(idx);
     if (projectPath != null) {
       IJavaProject project =
           JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectPath));
       if (isJarFile) {
         IResource resource = JavaModel.getWorkspaceTarget(new Path(jarPath));
         if (resource != null) return project.getPackageFragmentRoot(resource);
         return project.getPackageFragmentRoot(jarPath);
       }
       Object target =
           JavaModel.getWorkspaceTarget(
               new Path(this.containerPaths[index] + '/' + this.relativePaths[index]));
       if (target != null) {
         if (target instanceof IProject) {
           return project.getPackageFragmentRoot((IProject) target);
         }
         IJavaElement element = JavaModelManager.create((IResource) target, project);
         return (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
       }
     }
   }
   return null;
 }
Пример #10
0
  /**
   * Returns the first package root for the given java project
   *
   * @param javaProject the project to search in
   * @return the first package root, or null
   */
  @Nullable
  public static IPackageFragmentRoot getSourcePackageRoot(IJavaProject javaProject) {
    IPackageFragmentRoot packageRoot = null;
    List<IPath> sources = BaseProjectHelper.getSourceClasspaths(javaProject);

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    for (IPath path : sources) {
      IResource firstSource = workspace.getRoot().findMember(path);
      if (firstSource != null) {
        packageRoot = javaProject.getPackageFragmentRoot(firstSource);
        if (packageRoot != null) {
          break;
        }
      }
    }
    return packageRoot;
  }
 /**
  * Creates and adds a class folder to the class path.
  *
  * @param jproject The parent project
  * @param containerName
  * @param sourceAttachPath The source attachment path
  * @param sourceAttachRoot The source attachment root path
  * @return The handle of the created root
  * @throws CoreException
  */
 public static IPackageFragmentRoot addClassFolder(
     IJavaProject jproject, String containerName, IPath sourceAttachPath, IPath sourceAttachRoot)
     throws CoreException {
   IProject project = jproject.getProject();
   IContainer container = null;
   if (containerName == null || containerName.length() == 0) {
     container = project;
   } else {
     IFolder folder = project.getFolder(containerName);
     if (!folder.exists()) {
       CoreUtility.createFolder(folder, false, true, null);
     }
     container = folder;
   }
   IClasspathEntry cpe =
       JavaCore.newLibraryEntry(container.getFullPath(), sourceAttachPath, sourceAttachRoot);
   addToClasspath(jproject, cpe);
   return jproject.getPackageFragmentRoot(container);
 }
  public boolean performFinish() {
    try {

      if (customMediatorModel.getSelectedOption().equals("new.mediator")) {
        project = createNewProject();
        IFolder srcFolder = ProjectUtils.getWorkspaceFolder(project, "src", "main", "java");
        JavaUtils.addJavaSupportAndSourceFolder(project, srcFolder);

        /*create the new Java project*/
        String className = customMediatorModel.getMediatorClassName();
        String packageName = customMediatorModel.getMediatorClassPackageName();
        IJavaProject iJavaProject = JavaCore.create(project);
        IPackageFragmentRoot root = iJavaProject.getPackageFragmentRoot(srcFolder);
        IPackageFragment sourcePackage = root.createPackageFragment(packageName, false, null);

        /*get the Mediator class template*/
        String template = CustomMediatorClassTemplate.getClassTemplete(packageName, className);
        ICompilationUnit cu =
            sourcePackage.createCompilationUnit(className + ".java", template, false, null);

        project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        try {
          IEditorPart javaEditor = JavaUI.openInEditor(cu);
          JavaUI.revealInEditor(javaEditor, (IJavaElement) cu);
        } catch (Exception e) {
          log.error(e);
        }
      } else {
        project = customMediatorModel.getMediatorProject();
        project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
      }
      File pomfile = project.getFile("pom.xml").getLocation().toFile();
      getModel().getMavenInfo().setPackageName("bundle");
      if (!pomfile.exists()) {
        createPOM(pomfile);
        addDependancies(project);
      }
      MavenProject mavenProject = MavenUtils.getMavenProject(pomfile);
      boolean pluginExists =
          MavenUtils.checkOldPluginEntry(
              mavenProject, "org.apache.felix", "maven-bundle-plugin", "2.3.4");
      if (!pluginExists) {
        Plugin plugin =
            MavenUtils.createPluginEntry(
                mavenProject, "org.apache.felix", "maven-bundle-plugin", "2.3.4", true);

        Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode(plugin);
        Xpp3Dom instructionNode = MavenUtils.createXpp3Node("instructions");
        Xpp3Dom bundleSymbolicNameNode =
            MavenUtils.createXpp3Node(instructionNode, "Bundle-SymbolicName");
        Xpp3Dom bundleNameNode = MavenUtils.createXpp3Node(instructionNode, "Bundle-Name");
        ;
        Xpp3Dom exportPackageNode = MavenUtils.createXpp3Node(instructionNode, "Export-Package");
        Xpp3Dom dynamicImportNode =
            MavenUtils.createXpp3Node(instructionNode, "DynamicImport-Package");
        bundleSymbolicNameNode.setValue(project.getName());
        bundleNameNode.setValue(project.getName());
        if (customMediatorModel.getMediatorClassPackageName() != null
            && !customMediatorModel.getMediatorClassPackageName().trim().isEmpty()) {
          exportPackageNode.setValue(customMediatorModel.getMediatorClassPackageName());
        } else {
          IJavaProject javaProject = JavaCore.create(project);
          if (null != javaProject) {
            StringBuffer sb = new StringBuffer();
            for (IPackageFragment pkg : javaProject.getPackageFragments()) {
              if (pkg.getKind() == IPackageFragmentRoot.K_SOURCE) {
                if (pkg.hasChildren()) {
                  sb.append(pkg.getElementName()).append(",");
                }
              }
            }
            exportPackageNode.setValue(sb.toString().replaceAll(",$", ""));
          }
        }
        dynamicImportNode.setValue("*");
        configurationNode.addChild(instructionNode);
        MavenUtils.saveMavenProject(mavenProject, pomfile);
      }

      project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
      ProjectUtils.addNatureToProject(project, false, MEDIATOR_PROJECT_NATURE);
      MavenUtils.updateWithMavenEclipsePlugin(
          pomfile,
          new String[] {JDT_BUILD_COMMAND},
          new String[] {MEDIATOR_PROJECT_NATURE, JDT_PROJECT_NATURE});
      customMediatorModel.addToWorkingSet(project);
      project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
      refreshDistProjects();
    } catch (CoreException e) {
      log.error(e);
    } catch (Exception e) {
      log.error(e);
    }
    return true;
  }
  /**
   * This method is a hook which gets called after the source folder's text input field has changed.
   * This default implementation updates the model and returns an error status. The underlying model
   * is only valid if the returned status is OK.
   *
   * @return the model's error status
   */
  protected IStatus containerChanged() {
    StatusInfo status = new StatusInfo();

    fCurrRoot = null;
    String str = getPackageFragmentRootText();
    if (str.length() == 0) {
      status.setError(NewWizardMessages.NewContainerWizardPage_error_EnterContainerName);
      return status;
    }
    IPath path = new Path(str);
    IResource res = fWorkspaceRoot.findMember(path);
    if (res != null) {
      int resType = res.getType();
      if (resType == IResource.PROJECT || resType == IResource.FOLDER) {
        IProject proj = res.getProject();
        if (!proj.isOpen()) {
          status.setError(
              Messages.format(
                  NewWizardMessages.NewContainerWizardPage_error_ProjectClosed,
                  BasicElementLabels.getPathLabel(proj.getFullPath(), false)));
          return status;
        }
        IJavaProject jproject = JavaCore.create(proj);
        fCurrRoot = jproject.getPackageFragmentRoot(res);
        if (res.exists()) {
          if (res.isVirtual()) {
            status.setError(NewWizardMessages.NewContainerWizardPage_error_FolderIsVirtual);
            return status;
          }
          try {
            if (!proj.hasNature(JavaCore.NATURE_ID)) {
              if (resType == IResource.PROJECT) {
                status.setError(NewWizardMessages.NewContainerWizardPage_warning_NotAJavaProject);
              } else {
                status.setWarning(
                    NewWizardMessages.NewContainerWizardPage_warning_NotInAJavaProject);
              }
              return status;
            }
            if (fCurrRoot.isArchive()) {
              status.setError(
                  Messages.format(
                      NewWizardMessages.NewContainerWizardPage_error_ContainerIsBinary,
                      BasicElementLabels.getPathLabel(path, false)));
              return status;
            }
            if (fCurrRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
              status.setWarning(
                  Messages.format(
                      NewWizardMessages.NewContainerWizardPage_warning_inside_classfolder,
                      BasicElementLabels.getPathLabel(path, false)));
            } else if (!jproject.isOnClasspath(fCurrRoot)) {
              status.setWarning(
                  Messages.format(
                      NewWizardMessages.NewContainerWizardPage_warning_NotOnClassPath,
                      BasicElementLabels.getPathLabel(path, false)));
            }
          } catch (JavaModelException e) {
            status.setWarning(NewWizardMessages.NewContainerWizardPage_warning_NotOnClassPath);
          } catch (CoreException e) {
            status.setWarning(NewWizardMessages.NewContainerWizardPage_warning_NotAJavaProject);
          }
        }
        return status;
      } else {
        status.setError(
            Messages.format(
                NewWizardMessages.NewContainerWizardPage_error_NotAFolder,
                BasicElementLabels.getPathLabel(path, false)));
        return status;
      }
    } else {
      status.setError(
          Messages.format(
              NewWizardMessages.NewContainerWizardPage_error_ContainerDoesNotExist,
              BasicElementLabels.getPathLabel(path, false)));
      return status;
    }
  }
Пример #14
0
  /**
   * Convert the empty project to an Acceleo project.
   *
   * @param project The newly created project.
   * @param selectedJVM The name of the selected JVM (J2SE-1.5 or JavaSE-1.6 recommended).
   * @param allModules The description of the module that need to be created.
   * @param shouldGenerateModules Indicates if we should generate the modules in the project or not.
   *     The wizard container to display the progress monitor
   * @param monitor The monitor.
   */
  public static void convert(
      IProject project,
      String selectedJVM,
      List<AcceleoModule> allModules,
      boolean shouldGenerateModules,
      IProgressMonitor monitor) {
    String generatorName = computeGeneratorName(project.getName());
    AcceleoProject acceleoProject = AcceleowizardmodelFactory.eINSTANCE.createAcceleoProject();
    acceleoProject.setName(project.getName());
    acceleoProject.setGeneratorName(generatorName);

    // Default JRE value
    acceleoProject.setJre(selectedJVM);
    if (acceleoProject.getJre() == null && acceleoProject.getJre().length() == 0) {
      acceleoProject.setJre("J2SE-1.5"); // $NON-NLS-1$		
    }

    if (shouldGenerateModules) {
      for (AcceleoModule acceleoModule : allModules) {
        String parentFolder = acceleoModule.getParentFolder();
        IProject moduleProject =
            ResourcesPlugin.getWorkspace().getRoot().getProject(acceleoModule.getProjectName());
        if (moduleProject.exists()
            && moduleProject.isAccessible()
            && acceleoModule.getModuleElement() != null
            && acceleoModule.getModuleElement().isIsMain()) {
          IPath parentFolderPath = new Path(parentFolder);
          IFolder folder = moduleProject.getFolder(parentFolderPath.removeFirstSegments(1));
          acceleoProject
              .getExportedPackages()
              .add(
                  folder
                      .getProjectRelativePath()
                      .removeFirstSegments(1)
                      .toString()
                      .replaceAll(
                          "/", //$NON-NLS-1$
                          "\\.")); //$NON-NLS-1$
        }
        // Calculate project dependencies
        List<String> metamodelURIs = acceleoModule.getMetamodelURIs();
        for (String metamodelURI : metamodelURIs) {
          // Find the project containing this metamodel and add a dependency to it.
          EPackage ePackage = AcceleoPackageRegistry.INSTANCE.getEPackage(metamodelURI);
          if (ePackage != null && !(ePackage instanceof EcorePackage)) {
            Bundle bundle = AcceleoWorkspaceUtil.getBundle(ePackage.getClass());
            acceleoProject.getPluginDependencies().add(bundle.getSymbolicName());
          }
        }
      }
    }

    try {
      IProjectDescription description = project.getDescription();
      description.setNatureIds(
          new String[] {
            JavaCore.NATURE_ID,
            IBundleProjectDescription.PLUGIN_NATURE,
            IAcceleoConstants.ACCELEO_NATURE_ID,
          });
      project.setDescription(description, monitor);

      IJavaProject iJavaProject = JavaCore.create(project);

      // Compute the JRE
      List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
      IExecutionEnvironmentsManager executionEnvironmentsManager =
          JavaRuntime.getExecutionEnvironmentsManager();
      IExecutionEnvironment[] executionEnvironments =
          executionEnvironmentsManager.getExecutionEnvironments();
      for (IExecutionEnvironment iExecutionEnvironment : executionEnvironments) {
        if (acceleoProject.getJre().equals(iExecutionEnvironment.getId())) {
          entries.add(
              JavaCore.newContainerEntry(JavaRuntime.newJREContainerPath(iExecutionEnvironment)));
          break;
        }
      }

      // PDE Entry (will not be generated anymore)
      entries.add(
          JavaCore.newContainerEntry(
              new Path("org.eclipse.pde.core.requiredPlugins"))); // $NON-NLS-1$

      // Sets the input / output folders
      IFolder target = project.getFolder("src"); // $NON-NLS-1$
      if (!target.exists()) {
        target.create(true, true, monitor);
      }

      IFolder classes = project.getFolder("bin"); // $NON-NLS-1$
      if (!classes.exists()) {
        classes.create(true, true, monitor);
      }

      iJavaProject.setOutputLocation(classes.getFullPath(), monitor);
      IPackageFragmentRoot packageRoot = iJavaProject.getPackageFragmentRoot(target);
      entries.add(
          JavaCore.newSourceEntry(
              packageRoot.getPath(), new Path[] {}, new Path[] {}, classes.getFullPath()));

      iJavaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
      iJavaProject.open(monitor);

      AcceleoProjectUtils.generateFiles(
          acceleoProject, allModules, project, shouldGenerateModules, monitor);

      // Default settings
      AcceleoBuilderSettings settings = new AcceleoBuilderSettings(project);
      settings.setCompilationKind(AcceleoBuilderSettings.COMPILATION_PLATFORM_RESOURCE);
      settings.setResourceKind(AcceleoBuilderSettings.BUILD_XMI_RESOURCE);
      settings.save();
    } catch (CoreException e) {
      AcceleoUIActivator.log(e, true);
    }
  }
Пример #15
0
  public void testASTRewriteExample() throws Exception {
    // create a new project
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("Test");
    project.create(null);
    project.open(null);
    try {
      // set the Java nature and Java build path
      IProjectDescription description = project.getDescription();
      description.setNatureIds(new String[] {JavaCore.NATURE_ID});
      project.setDescription(description, null);

      IJavaProject javaProject = JavaCore.create(project);

      // build path is: project as source folder and JRE container
      IClasspathEntry[] cpentry =
          new IClasspathEntry[] {
            JavaCore.newSourceEntry(javaProject.getPath()),
            JavaRuntime.getDefaultJREContainerEntry()
          };
      javaProject.setRawClasspath(cpentry, javaProject.getPath(), null);
      Map<String, String> options = new HashMap<>();
      options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
      options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4");
      javaProject.setOptions(options);

      // create a test file
      IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(project);
      IPackageFragment pack1 = root.createPackageFragment("test1", false, null);
      StringBuffer buf = new StringBuffer();
      buf.append("package test1;\n");
      buf.append("public class E {\n");
      buf.append("    public void foo(int i) {\n");
      buf.append("        while (--i > 0) {\n");
      buf.append("            System.beep();\n");
      buf.append("        }\n");
      buf.append("    }\n");
      buf.append("}\n");
      ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

      // create an AST
      ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
      parser.setSource(cu);
      parser.setResolveBindings(false);
      CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
      AST ast = astRoot.getAST();

      // create the descriptive ast rewriter
      ASTRewrite rewrite = ASTRewrite.create(ast);

      // get the block node that contains the statements in the method body
      TypeDeclaration typeDecl = (TypeDeclaration) astRoot.types().get(0);
      MethodDeclaration methodDecl = typeDecl.getMethods()[0];
      Block block = methodDecl.getBody();

      // create new statements to insert
      MethodInvocation newInv1 = ast.newMethodInvocation();
      newInv1.setName(ast.newSimpleName("bar1"));
      Statement newStatement1 = ast.newExpressionStatement(newInv1);

      MethodInvocation newInv2 = ast.newMethodInvocation();
      newInv2.setName(ast.newSimpleName("bar2"));
      Statement newStatement2 = ast.newExpressionStatement(newInv2);

      // describe that the first node is inserted as first statement in block, the other one as last
      // statement
      // note: AST is not modified by this
      ListRewrite listRewrite = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
      listRewrite.insertFirst(newStatement1, null);
      listRewrite.insertLast(newStatement2, null);

      // evaluate the text edits corresponding to the described changes. AST and CU still
      // unmodified.
      TextEdit res = rewrite.rewriteAST();

      // apply the text edits to the compilation unit
      Document document = new Document(cu.getSource());
      res.apply(document);
      cu.getBuffer().setContents(document.get());

      // test result
      String preview = cu.getSource();

      buf = new StringBuffer();
      buf.append("package test1;\n");
      buf.append("public class E {\n");
      buf.append("    public void foo(int i) {\n");
      buf.append("        bar1();\n");
      buf.append("        while (--i > 0) {\n");
      buf.append("            System.beep();\n");
      buf.append("        }\n");
      buf.append("        bar2();\n");
      buf.append("    }\n");
      buf.append("}\n");
      assertEquals(preview, buf.toString());
    } finally {
      project.delete(true, null);
    }
  }
  public boolean performFinish() {
    try {
      project = createNewProject();
      sourceFolder = ProjectUtils.getWorkspaceFolder(project, "src", "main", "java");
      javaProject = JavaCore.create(project);
      root = javaProject.getPackageFragmentRoot(sourceFolder);
      JavaUtils.addJavaSupportAndSourceFolder(project, sourceFolder);
      addDependancies(project);

      String className = filterModel.getFilterClass();
      String packageName = filterModel.getFilterClassPackage();

      IPackageFragment sourcePackage = root.createPackageFragment(packageName, false, null);

      ICompilationUnit cu =
          sourcePackage.createCompilationUnit(
              className + ".java", getFilterClassSource(packageName, className), false, null);
      project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());

      File pomfile = project.getFile("pom.xml").getLocation().toFile();
      getModel().getMavenInfo().setPackageName("bundle");
      if (!pomfile.exists()) {
        createPOM(pomfile);
      }

      MavenProject mavenProject = MavenUtils.getMavenProject(pomfile);

      mavenProject.getModel().getProperties().put("CApp.type", "lib/registry/filter");

      Plugin plugin =
          MavenUtils.createPluginEntry(
              mavenProject, "org.apache.felix", "maven-bundle-plugin", "2.3.4", true);

      Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode(plugin);
      Xpp3Dom instructionNode = MavenUtils.createXpp3Node(configurationNode, "instructions");
      Xpp3Dom symbolicNameNode = MavenUtils.createXpp3Node(instructionNode, "Bundle-SymbolicName");
      symbolicNameNode.setValue(mavenProject.getArtifactId());
      Xpp3Dom bundleNameNode = MavenUtils.createXpp3Node(instructionNode, "Bundle-Name");
      bundleNameNode.setValue(mavenProject.getArtifactId());
      Xpp3Dom exportPackageNode = MavenUtils.createXpp3Node(instructionNode, "Export-Package");
      exportPackageNode.setValue(packageName);
      Xpp3Dom dynamicImportNode =
          MavenUtils.createXpp3Node(instructionNode, "DynamicImport-Package");
      dynamicImportNode.setValue("*");

      Repository repo = new Repository();
      repo.setUrl("http://maven.wso2.org/nexus/content/groups/wso2-public/");
      repo.setId("wso2-maven2-repository-1");

      mavenProject.getModel().addRepository(repo);
      mavenProject.getModel().addPluginRepository(repo);

      List<Dependency> dependencyList = new ArrayList<Dependency>();

      Map<String, JavaLibraryBean> dependencyInfoMap =
          JavaLibraryUtil.getDependencyInfoMap(project);
      Map<String, String> map = ProjectDependencyConstants.DEPENDENCY_MAP;
      for (JavaLibraryBean bean : dependencyInfoMap.values()) {
        if (bean.getVersion().contains("${")) {
          for (String path : map.keySet()) {
            bean.setVersion(bean.getVersion().replace(path, map.get(path)));
          }
        }
        Dependency dependency = new Dependency();
        dependency.setArtifactId(bean.getArtifactId());
        dependency.setGroupId(bean.getGroupId());
        dependency.setVersion(bean.getVersion());
        dependencyList.add(dependency);
      }
      MavenUtils.addMavenDependency(mavenProject, dependencyList);
      MavenUtils.saveMavenProject(mavenProject, pomfile);
      ProjectUtils.addNatureToProject(project, false, Constants.REGISTRY_FILTER_PROJECT_NATURE);
      MavenUtils.updateWithMavenEclipsePlugin(
          pomfile,
          new String[] {JDT_BUILD_COMMAND},
          new String[] {Constants.REGISTRY_FILTER_PROJECT_NATURE, JDT_PROJECT_NATURE});
      project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());

      try {
        refreshDistProjects();
        IEditorPart javaEditor = JavaUI.openInEditor(cu);
        JavaUI.revealInEditor(javaEditor, (IJavaElement) cu);
      } catch (Exception e) {
        /* ignore */
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return true;
  }
  /**
   * Opens a selection dialog that allows to select a source container.
   *
   * @return returns the selected package fragment root or <code>null</code> if the dialog has been
   *     canceled. The caller typically sets the result to the container input field.
   *     <p>Clients can override this method if they want to offer a different dialog.
   * @since 3.2
   */
  protected IPackageFragmentRoot chooseContainer() {
    IJavaElement initElement = getPackageFragmentRoot();
    Class<?>[] acceptedClasses = new Class[] {IPackageFragmentRoot.class, IJavaProject.class};
    TypedElementSelectionValidator validator =
        new TypedElementSelectionValidator(acceptedClasses, false) {
          @Override
          public boolean isSelectedValid(Object element) {
            try {
              if (element instanceof IJavaProject) {
                IJavaProject jproject = (IJavaProject) element;
                IPath path = jproject.getProject().getFullPath();
                return (jproject.findPackageFragmentRoot(path) != null);
              } else if (element instanceof IPackageFragmentRoot) {
                return (((IPackageFragmentRoot) element).getKind()
                    == IPackageFragmentRoot.K_SOURCE);
              }
              return true;
            } catch (JavaModelException e) {
              JavaPlugin.log(e.getStatus()); // just log, no UI in validation
            }
            return false;
          }
        };

    acceptedClasses =
        new Class[] {IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class};
    ViewerFilter filter =
        new TypedViewerFilter(acceptedClasses) {
          @Override
          public boolean select(Viewer viewer, Object parent, Object element) {
            if (element instanceof IPackageFragmentRoot) {
              try {
                return (((IPackageFragmentRoot) element).getKind()
                    == IPackageFragmentRoot.K_SOURCE);
              } catch (JavaModelException e) {
                JavaPlugin.log(e.getStatus()); // just log, no UI in validation
                return false;
              }
            }
            return super.select(viewer, parent, element);
          }
        };

    StandardJavaElementContentProvider provider = new StandardJavaElementContentProvider();
    ILabelProvider labelProvider =
        new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
    dialog.setValidator(validator);
    dialog.setComparator(new JavaElementComparator());
    dialog.setTitle(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_title);
    dialog.setMessage(
        NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_description);
    dialog.addFilter(filter);
    dialog.setInput(JavaCore.create(fWorkspaceRoot));
    dialog.setInitialSelection(initElement);
    dialog.setHelpAvailable(false);

    if (dialog.open() == Window.OK) {
      Object element = dialog.getFirstResult();
      if (element instanceof IJavaProject) {
        IJavaProject jproject = (IJavaProject) element;
        return jproject.getPackageFragmentRoot(jproject.getProject());
      } else if (element instanceof IPackageFragmentRoot) {
        return (IPackageFragmentRoot) element;
      }
      return null;
    }
    return null;
  }