While developing an Eclipse facet to extend the Dynamic Web Project, I ran into an issue where I was trying to create a Java class in the source directory, along with a package name (provided in the dialog). Within my FacetInstallDelegate, I ended up doing the following. It works, but I’m not sure it was the cleanest way to do it. If you know a better way, please let me know.
First, we take the package name and create the path string (with ‘/’ delimiters):
String[] pkgPath = cfg.getPortletPackageName().split(".");
Then, we find the source directory using the classpath entries for the workspace, and prepend it on the path string:
IPath sourceFolder = null;
for (int a = 0; a < entries.length; a++) {
IClasspathEntry e = entries[a];
if(e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
sourceFolder = e.getPath();
}
}
String path = sourceFolder != null ? sourceFolder.toString() : "src/"; /* It's 'src/' by default, so use that if we don't find anything on the classpath. Just in case. */
Given the path string, iterate over all the levels to create the respective directories:
for(int a = 0; a < pkgPath.length; ++a) {
path += "/" + pkgPath[a];
IFolder f = project.getWorkspace().getRoot().getFolder(new Path(path));
f.create(true, true, monitor);
}
path += “/”; // append one more seperator.
Now, we can create our Java class, and place it in the directory structure, therefore, in the correct package location. This way developers don’t need to move the class into the package structure manually.
ICompilationUnit cu = JavaCore.createCompilationUnitFrom(project.getWorkspace().getRoot().getFile( new Path(path + cfg.getClassName() + (cfg.getClassName().indexOf(".java") > -1 ? "" : ".java"))));
cu.createType(getBody(cfg.getClassName()), null, true, monitor);
cu.createPackageDeclaration(cfg.getPackageName(), monitor);
addImports(cu, monitor);
Works like a charm.
February 23rd, 2008 at 9:55 am
Just wanted to give a thanks for this posting. I wanted to do a quick facet myself and I just hit that whole put a class file into a directory structure thing and it was like a wall. Nothing anywhere giving a clear explanation on how to do it. I considered templates but I had problems with it interacting with a facet.