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()) {
		m_project.create(null);
	}
	m_project.open(null);
	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 = {
			JavaCore.newSourceEntry(m_project.getFullPath().append("src")),
			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);
	Assert.isTrue(srcFolder.exists());
} catch (CoreException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	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.

1 thought on “Eclipse JDT Tutorial – Dynamic load Java projects to workspace”

Leave a Comment