Abstract:
20 pages
English

Abstract:

-

Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres
20 pages
English
Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres

Description




Tutorial: Enhancing Java with Spoon

Renaud Pawlak
Rensselaer Polytechnic Institute, Hartford Campus
275 Windsor St, Hartford, CT 06120

Carlos Noguera and Nicolas Petitprez
INRIA Futurs
LIFL (UMR 8022) - Universite Lille 1
59655 Villeneuve d'Ascq Cedex France


Abstract:
Have you ever thought that the Java compiler could check more than what it does now? Have
you ever thought a lot of code needs to be written and maintained manually while it could be
automatically generated or validated by the compiler? Spoon is a framework that allows you
to enhance the Java semantics through static analysis and generative programming. With
Spoon, you can write compilation components called “Spoonlets”, which can be deployed in
Eclipse using the SpoonJDT plugin. Spoonlets can provide generic validations or
transformations, which are not provided from scratch by the compiler, such as the ones
provided by Findbugs project (http://findbugs.sourceforge.net/). Spoonlets can also
implement validations and transformations to support your favorite frameworks (SAX, Struts,
Hibernate ...) in order to simplify their use and avoid common mistakes. In this tutorial, we
learn how to use and create new Spoonlets, which will help to dramatically increase the
quality of your own Java developments, but also the developments of the programmers
working with you.

Table of contents
1 Getting Started with Spoon ............................................................. ...

Sujets

Informations

Publié par
Nombre de lectures 69
Langue English
Poids de l'ouvrage 2 Mo

Extrait

Tutorial: Enhancing Java with Spoon Renaud Pawlak Rensselaer Polytechnic Institute, Hartford Campus 275 Windsor St, Hartford, CT 06120 Carlos Noguera and Nicolas Petitprez INRIA Futurs LIFL (UMR 8022) - Universite Lille 1 59655 Villeneuve d'Ascq Cedex France
Abstract: Have you ever thought that the Java compiler could check more than what it does now? Have you ever thought a lot of code needs to be written and maintained manually while it could be automatically generated or validated by the compiler? Spoon is a framework that allows you to enhance the Java semantics through static analysis and generative programming. With Spoon, you can write compilation components called “Spoonlets”, which can be deployed in Eclipse using the SpoonJDT plugin. Spoonlets can provide generic vali dations or transformations, which are not provided from scratch by the compiler, such as the ones provided by Findbugs project (http://findbugs.sourceforge.net/). Spoonle ts can also implement validations and transformations to support your favorite frameworks (SAX, Struts, Hibernate ...) in order to simplify their use and avoid common mistakes. In this tutorial, we learn how to use and create new Spoonlets, which will help to dramatically increase the quality of your own Java developments, but also the developments of the programmers working with you. Table of contents 1 Getting Started with Spoon ............................................................................................ 2 1.1 What is a Spoonlet?................................................................................................ 2 1.2 Step 1: installing the SpoonJDT plugin .................................................................. 2 1.3Step2:deployingaSpoonletinEclipse..................................................................21.4 Available Spoonlets ............................................................................................... 5 2 Creating your own Spoonlet........................................................................................... 5 2.1 Programming a processor ....................................................................................... 6 2.2 Packaging a Spoonlet ............................................................................................. 6 3 Developing Processors..................................................................................................10 3.1 Development mode ...............................................................................................10 3.2 Configurable Processors........................................................................................11 3.2.1 Property-driven Configuration .......................................................................11 3.2.2 Annotation-driven Configuration...................................................................13 3.3 Quick Fixes...........................................................................................................14 4GenerativeProgrammingwithSpoon............................................................................174.1 Template Principles...............................................................................................17 4.2 A Simple Template ...............................................................................................18 5 Resources .....................................................................................................................20
Tutorial: Enhancing Java with Spoon
page 1 out of 20
1 Getting Started with Spoon Here, we show how to enhance Java with Spoon. This is done with a compilation component called a Spoonlet. 1.1 What is a Spoonlet? A Spoonlet is a compilation component distributed as a packaged jar file that contains one or several program processors written in Java. These processors can validate Java programs using static analysis, or transform the program using generative programming techniques. A Spoonlet can be deployed in Eclipse and applied to an Eclipse Java project. It then acts like a plugin that extends or restricts the Java language capabilities through static analysis and/or transformations.As examples, you can imagine a Spoonlet to: force the definition of Javadoc comments on public methods and fields (report errors when not defined); discourage the use of reflection by reporting warnings when it is used; automatically transform the program to insert a serialVersionUID  field when the class implements Serializable ; report an error when a visited class of a visitor pattern does not define the accept method- in general, validate that a design pattern is correctly implemented; transform the body of a setter method annotated with @Persistent to save the object’s state change in a data storage; etc. With the SpoonJDT Eclipse plugin, all the Spoonlet warnings, errors, and other messages are well-integrated to the Eclipse environment and are reported exac tly like regular Java compilation problems. Hence, a Spoonlet can really be seen as a compilation component that enhances the Java language to fit better your development context. 1.2 Installing the SpoonJDT plugin In order to deploy a Spoonlet in your Eclipse environment, you first need t o install the SpoonJDT plugin, which is a simple Spoonlet container. This plugin is generic to all the Spoonlets and needs to be installed only once. Eclipse 3.2 and Java 5 is required to install SpoonJDT plugin. Use the update manager with this URL ( http://spoon.gforge.inria.fr/eclipse ) to find and install the plugin. More information about using the update manager is available here: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.user/tasks/tasks-34.htm 1.3 Deploying a Spoonlet in Eclipse SpoonJDT by itself is an empty container and you need to deploy Spoonlets to enable actual program processing. Let us deploy the VSuite findbugs  Spoonlet on a target project. First, make sure you have a Java target project (name it target-project ) with a few classes
Tutorial: Enhancing Java with Spoon
page 2 out of 20
that contain some coding problems. Note: we recommend that you start this tutorial in a brand new Eclipse workspace. We recommend that you create an src  source folder. The created class is example.MyClass : p a ck a g e  example;  p u b l ic  c l a s s MyClass {     p r ivate  i n t  i = 1;          p u b l ic  v o id test() {         i f (5 > 2) {             i  1 + i ++ - 5; =  }  }          @Override     p u b l i c String toString() {         r e tu r n  s u p e r .toString().substring(0);  } } Note: the class shown here contains statements and expressions which are confusing and can be considered as bugs (such as i=i++  or substring(0) , which both have no effect); however, Eclipse’s JDT doesn’t report any warnings or errors.
Let us now deploy a Spoonlet that will enhance Java in order to detect this kind of problems.
Tutorial: Enhancing Java with Spoon
page 3 out of 20
VSuite is a project that aims at finding and reporting problems in your Java code. The providedfindbugs Spoonlet contains some of the bugs covered by the well-known FindBugs project. The following steps describe how to use this Spoonlet in a target Eclipse Java project. 1. Get the latest version of vsuite-findbugs-xx.jar that you will find on the Spoon website and store it in target-project (only local jars are supported at the moment). 2. Right click on the target-project Java project root icon (make sure you are in Java perspective). Go to Properties -> Java compiler -> Spoon . 3. Enable Spoon processing and add vsuite-findbugs-xx.jar  as a local jar. Several Spoon processors are available, each one performing a specific va lidation: you can enable/disable them and (sometimes) apply some configuration.
4. Press the "Apply" or "OK" button. Processors are then automatically applied to the target Java project (messages are reported when needed).
Tutorial: Enhancing Java with Spoon
page 4 out of 20
Repeat this process for deploying other Spoonlets. Finally, note that SpoonJDT allows Spoonlets to be run in 4 modes: Default: the code generation step, if any, is hidden to the use r (this mode is recommended);Advanced: the code is generated and accessible in a target directory; NoOutput: no code is generated (not recommended, but useful when a Spoonlet is only validating the program, like VSuite and AVal Spoonlets); NoCompile: Spoon generates but does not compile the code (useful when generating code in another project, which has its own compiling environment). 1.4 Available Spoonlets Anyone can create and distribute Spoonlets. The Spoon project provides some useful, general-purpose Spoonlets described at http://spoon.gforge.inria.fr/SubProjects/Main . 2 Creating your own Spoonlet It is often the case that general purpose validations or transformations are not the most interesting for a given development context. For instance, you may want to enhance Java to take into account framework-specific idioms or patterns. These may vary depending on your environment (colleagues, company, customers, frameworks). That’s why it is interesting to create your own Spoonlet to ensure some environmental programming conventions for yourself, your colleagues, your customers, code auditors, freelance developers, outsourced developments, etc.
Tutorial: Enhancing Java with Spoon
page 5 out of 20
2.1 Programming a processor Before moving forward, let us create a Java project called spoonlet-project to work in. Note that to access the Spoon API, spoon.jar must be in your classpath. When using the SpoonJDT plugin, the right spoon.jar  will be automatically added to your project’s classpath when Spoon processing is activated. To create a Spoonlet, you first need to program a processor. A processor is usually a kind of scanner that traverses the program’s AST (Abstract Syntax Tree) in order to statically validate or transform the program. With the Spoon API, the AST is defined in the spoon.reflect sub-packages and gives access to the entire Java program, both for reading and modification. In the case you are working with Eclipse, your AST will correspond to the code of the currently processed Java project. A processor corresponds to a Java class that implements spoon.processing.Processor<T> and defines the process method. In Spoon, the processor is parameterized by a T  type parameter (a.k.a. generics ) that gives the type of program element to be processed. If you want to process all the elements of your program, you set T  to CtElement : the elements’ root. If you only need to traverse the method declarations, you set T  to CtMethod . As an example, let us program a processor that will report warnings when public methods are not documented with a Javadoc comment. p a ck a g e  example;  i mp o rt  spoon.processing.AbstractProcessor; i mp o rt  spoon.processing.Severity; i mp o rt  spoon.reflect.declaration.CtMethod; i mp o rt  spoon.reflect.declaration.ModifierKind;  p u b l ic  c l a s s  JavadocProcessor ext end s  AbstractProcessor<CtMethod<?>> {  p u b l ic  v o id process(CtMethod<?> m) {   i f  (m.getModifiers().contains(ModifierKind. PUBLIC )) {    i f (m.getDocComment() == nu l l  || m.getDocComment().equals( "" )) {  getEnvironment().report( t h is , Severity. WARNING , m,       "undocumented method" );  }  }  } } 2.2 Packaging a Spoonlet To be deployed in a Spoonlet container such as Eclipse’s SpoonJDT, the Spoonlet jar file must contains a spoon.xml  deployment descriptor. This file describes the available processors that should be used to validate or transform the program. Note that processors are applied in the order they are declared in the deployment descriptor. In addition, they can be set to active , mandatory , and visible . When not active, the processor is not applied to the program by default and must be activated manually by the user through t he UI. When mandatory, the processor cannot be deactivated by the user. When not visible, the processor is not shown to the final user so that it cannot be (de)activated.
Tutorial: Enhancing Java with Spoon
page 6 out of 20
Note that each processor may define a set of UI-configurable properties, of which default values can be set in the deployment descriptor. Properties will be explained in a further section. Also, when a Spoonlet implements automatic program transformations using Spoon templates, it must specify a location for the template source files. For our simple example that tests for Javadoc on public methods, the spoon.xml  file will look like: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE spoon SYSTEM "http://spoon.gforge.inria.fr/pub/xml/spoonlet.dtd"> <spoon>  <processor name="Javadoc Processor"     class="example.JavadocProcessor" active="true"  doc="Checks that a public method is documented with a Javadoc comment">  </processor>   </spoon> Then, to package the Spoonlet, you just need to create a jar that contains the compiled processor classes (and any utility classes) and the spoon.xml  file, which can be located anywhere in the directory structure. Right click on the project and choose “Export…”.
Tutorial: Enhancing Java with Spoon
page 7 out of 20
Find more information on how to create a jar file here: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/tasks-33.htmFinally, you can apply this Spoonlet to you target project (such as the one created at the beginning of this tutorial – you can remove the vsuite-findbugs Spoonlet for clarity).
Tutorial: Enhancing Java with Spoon
page 8 out of 20
Once applied, undocumented public methods will raise warnings.
Tutorial: Enhancing Java with Spoon
page 9 out of
20
3 Developing Processors In this section, we will describe how to develop efficiently configurable processors for validation.3.1 Development mode When developing processors, it is not convenient to package and deploy Spoonlets each time a change has to be done. SpoonJDT provides a way to import Spoonlets from an Eclipse Java project of the current workspace. To do so, in the Spoon properties of target-project , use “Add descriptors…” and select the spoon.xml  file that corresponds to your under-development Spoonlet in spoonlet-project . When the Javadoc processor will be changed, it will be automatically reloaded by the plugin when target-project  is cleaned.
As an example, you can try to modify the reported message of JavadocProcessor  and clean target-project : the warnings should be automatically updated. In the following screenshot, we simply add exclamation marks to the reported warning message and clean target-project .
Tutorial: Enhancing Java with Spoon
page 10 out of 20
3.2 Configurable Processors Processors can be used as is, but most of the time, the users will wish to adapt their scope and behavior to better fit their needs, depending on the developed project and development environment. There are two ways a processor can be parameterized by the user: at a processor level with propertiesat a source code level with annotations ( metadata ) 3.2.1 Property-driven Configuration A property is a field defined by a processor class and annotated by @Property . Default values for these properties can be defined directly in Java, but also in the spoon.xml  file (which overrides the Java default values). As an example, let us modify the Javadoc processor example to add a property that will specify if the processor should report an error or a warning. To do this, the best is to add a severity property. p a ck a g e  example;  i mp o rt  spoon.processing.AbstractProcessor; i mp o rt  spoon.processing.Property; i mp o rt  spoon.processing.Severity; i mp o rt  spoon.reflect.declaration.CtMethod; i mp o rt  spoon.reflect.declaration.ModifierKind;  p u b l ic  c l a s s  JavadocProcessor ext end s  AbstractProcessor<CtMethod<?>> {  @Property  Severity severity = Severity. WARNING ;
Tutorial: Enhancing Java with Spoon
page 11 out of 20
  • Univers Univers
  • Ebooks Ebooks
  • Livres audio Livres audio
  • Presse Presse
  • Podcasts Podcasts
  • BD BD
  • Documents Documents