Eclipse JDT Tutorial – Dynamic load Java projects to workspace

In previous post, I have shown how to use Java Model to create a new project, access an existing project, and dynamically import/load an existing project directory into workspace.

The real question is if we want to parse a large number of projects(e.g. 1000) and those projects do not have .project file under it's directory. Then dynamic loading projects would not work at all.

In this article, I will show how to dynamically load a large number of projects into workspace. When you loop the directory which contains a large number of open source projects, for each directory do the following:

1. Create a project stub in workspace with the directory name

IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
m_project = root.getProject(projectName);
try {
	// Create the project
	if (!m_project.exists()) {
	javaProject = JavaCore.create(m_project);
	IProjectDescription description = m_project.getDescription();
	description.setNatureIds(new String[] { JavaCore.NATURE_ID });
	m_project.setDescription(description, null);
	// need to check to make sure this is right JRE
	IClasspathEntry[] buildPath = {
			JavaRuntime.getDefaultJREContainerEntry() };
		// set the classpath
	javaProject.setRawClasspath(buildPath, m_project.getFullPath()
			.append("bin"), null);
		// create the src folder
	IFolder folder = m_project.getFolder("src");
	if (!folder.exists())
		folder.create(true, true, null);
		srcFolder = javaProject.getPackageFragmentRoot(folder);
} catch (CoreException e) {
	// TODO Auto-generated catch block
	return false;

2. Recursively walk down each sub-directory, for each .java file do the following:

1. read java source file under the project directory
2. get the package info through regular expression: Pattern.compile("^package\\s+([^;]+);");
3. add each file to the Java Model according to the package names

IPackageFragment fragment = srcFolder.createPackageFragment(pkg_name_from_java_file, true, null);
fragment.createCompilationUnit(java_file_name, code_from_java_file, true, null);

3. Use ASTParser to parse each project and get wanted information

It looks like loading/importing existing projects to workspace, but actually it is really creating new projects with existing source code.

Category >> Java Development Tools (JDT)  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Dmitry on 2012-3-23

    Thank you! It’s very useful for my work now!.

Leave a comment