Key add-on beans and services

Một phần của tài liệu Manning spring roo in action (Trang 340 - 343)

To get the most from your add-on system, you have to learn each of the OSGi services that Roo provides. The following section details some of the major services and some snippets that you can experiment with in your own add-ons.

12.3.1 ProjectOperations

You can use the ProjectOperations service to manipulate your project in a number of ways. It’s injected via

@Reference private ProjectOperations projectOperations;

There are a number of features in this service. Let's start by reviewing the ones that affect your Maven build.

CONFIGURING YOUR MAVEN BUILD

Here are a few methods that let you manipulate your pom.xml file. As with the rest of these examples, they’ll be written after the add-on command completes using a trans­

actional file manager, so your projects won't get damaged by incomplete configura­

tion changes in the case of a bug. You can adjust these features:

 Maven build plug-ins:

addBuildPlugin(Plugin), addBuildPlugins(List<Plugin>) updateBuildPlugin(Plugin) removeBuildPlugin(Plugin)

removeBuildPlugins(List<Plugin>)

 Maven dependencies:

addDependency(Dependency)

addDependencies(List<Dependency>) removeDependency(Dependency)

removeDependencies(List<Dependency>)

 Maven properties:

addProperty(Property) removeProperty(Property)

 Maven filters:

addFilter(Filter) removeFilter(Filter)

 Maven resources (properties files, XML descriptors, and the like):

addResource(String moduleName, Resource resource) removeResource(String moduleName, Resource resource)

There are more commands you can issues as well, although you need to cast to a more specific type of ProjectOperations to do so.

ADDITIONAL MAVEN OPERATIONS

Your reference to ProjectOperations also implements the MavenOperations inter­

face, which gives you the ability to create a project yourself using the create- Project() method.

You also expose whether you’re able to create a project with the isCreate- ProjectAvailable() method:

if (((MavenOperations)projectOperations).isCreateProjectAvailable()) { ...

}

You could also create a project on your own within your add-on, potentially using a separate configuration:

((MavenOperations)projectOperations).createProject(

new JavaPackage("com.foo.bar.project"),

"FooBarBaz", 6));

The snippet above creates a new project named “FooBarBaz” with the top-level pack- age of com.foo.bar.project, and using Java version 6.0.

You can also execute any valid Maven command with executeMvnCommand (String). For example:

try {

((MavenOperations)projectOperations).executeMvnCommand("jetty:run");

} catch (IOException e) { //handle error

...

}

12.3.2 The PathResolver

The PathResolver is a service that properly accesses your project files for you. It pro- vides complete file paths for your root project and any modules associated with it. It can be injected as well:

@Reference private PathResolver pathResolver;

You can use the resolver to fetch various file path roots:

String warRoot = pathResolver.getFocusedRoot(Path.SRC_MAIN_WEBAPP);

String javaRoot = pathResolver.getFocusedRoot(Path.SRC_MAIN_JAVA);

This would equate to the file path on your file system for the src/main/webapp and src/main/java directories of your currently focused module. You can also concatenate a subpath, such as

String indexFilePath = pathResolver.

getFocusedPath(Path.SRC_MAIN_WEBAPP, "index.jspx");

This points to the index file at the root of your web application.

12.3.3 The FileManager

You used the FileManager to copy files in chapter 11, so it's not completely foreign to you. All writes go through an implementation of this service. You can gain access to it from your ProjectOperations instance using injection as well:

@Reference private FileManager fileManager;

309 Key add-on beans and services

The FileManager is a transactional engine that writes files after an add-on task has been committed. If any RuntimeException is thrown, such as one thrown by the Apache commons-lang3 project's Validate annotation, the writes for all files manipu- lated via this manager won’t be performed.

As in chapter 11, you can also use it indirectly. The AbstractOperations base class contains a handy copyDirectoryContents method that you used to copy the jQuery JavaScript files in chapter 11:

copyDirectoryContents("js/jqueryui/*.js",

pathResolver.getFocusedIdentifier(Path.SRC_MAIN_WEBAPP, "/js"), true);

The copyDirectoryContents method uses the FileManager, as well.

You'll also notice the use of the pathResolver in this fragment. The PathResolver is frequently used along with the FileManager to pull together the proper source or destination paths for a given operation.

12.3.4 Manipulating files transactionally

Let's put this together with a simple file writing example. Let's say you want to create a new JavaScript file in the project's src/main/webapp/js directory:

String jsLocation = pathResolver.getFocusedIdentifier(

Path.SRC_MAIN_WEBAPP, "/js/myscript.js");

MutableFile file = fileManager.createFile(jsLocation);

try {

PrintWriter writer = new PrintWriter(file.getOutputStream());

writer.println("var myvar = 10; alert (myvar);");

catch (IOException e) {

throw new IllegalStateException("file cannot be written to");

} finally {

IOUtils.closeQuietly(writer);

}

You'll use the pathResolver to look up the proper path for the /js/myscript.js file within the webapp directory. Then, instead of creating a standard Java file structure and writing to it directly, you ask the fileManager to create a reference to a mutable file, which is a virtual buffer for the file you wish to write.

You then write your information to the file and use the Apache Commons IOUtils class’s closeQuietly() method to properly close the file. Because the PrintWriter can throw an IOException during the write process, you have to catch it and rethrow as a runtime exception, here the IllegalStateException, to handle it properly.

Roo doesn't write this file right away. It waits until the Roo shell command that issued the changes completes, and then tells the file manager to write all of the file create, update, and delete operations at once. While not 100% fail-safe, it will gener- ally stop an add-on from half-modifying a given file. For the curious, browse the Roo source code for DefaultFileManager.commit() to see the operations performed.

12.3.5 Services wrap-up

You’re only scratching the surface of the key services and beans provided by Roo. We haven’t even discussed the ITD services and type system, and unfortunately, space doesn’t allow it here. We could write an entire book on Roo add-ons, so stay tuned for that. Because the framework is under heavy refactoring for version 1.2, we decided that documenting the internal Roo services wouldn’t be useful at this time.

THIS API UNDERGOES CONSTANT TWEAKING The code we're showing you is valid as of Roo 1.2.1. One significant (albeit small) change is that the Roo team removed their own IOUtils class, and are now using the Apache Com­

mons IO library’s IOUtils methods instead.

The team also removed their own Assert class in 1.2.1, replacing it with the Apache Commons Lang project's Verify method.

In the future, more tweaks should be expected. The general add-on devel­

opment process should remain the same; however, expect to need to adjust your add-ons once deployed every time Roo is updated.

We encourage you to read the Roo source code, which is easily digestible, and review the various built-in add-ons. The project is available at http://github.com/spring­

source/spring-roo.

Một phần của tài liệu Manning spring roo in action (Trang 340 - 343)

Tải bản đầy đủ (PDF)

(406 trang)