MASARYK UNIVERSITY FACULTY}w¡¢£¤¥¦§¨  OF I !"#$%&'()+,-./012345

CDI beans inspection with dynamic navigable graph

MASTER’STHESIS

Jakub Niedermertl

Brno, Autumn 2014 Declaration

Hereby I declare, that this paper is my original authorial work, which I have worked out by my own. All sources, references and literature used or excerpted during elaboration of this work are properly cited and listed in complete reference to the due source.

Advisor: Mgr. Marek Grác, Ph.D.

ii Acknowledgement

I would like to thank to the consultant, Ing. OndˇrejŽižka, and the advisor, Mgr. Marek Grác, Ph.D., for their advice and guidance during the creation of this thesis.

iii Abstract

This thesis deals with CDI technology and visualization of relations among CDI beans in IDE. The thesis describes the CDI technology, its API, its runtime environment – WildFly – and tools for static analysis of CDI projects in IDE. A couple of plugins extending Eclipse IDE and WildFly server is designed and implemented allowing to visualize and inspect CDI beans and their relations in Eclipse IDE. Both local projects in form of source code and running projects deployed in application server can be inspected.

iv Keywords

CDI, visualization, EE, Weld, WildFly, Eclipse RCP, Eclipse IDE, e4, JBoss Tools, Tycho, TinkerPop

v Contents

1 Introduction3

2 Analysis5 2.1 Requirements ...... 5 2.2 Architecture outline ...... 6

3 Contexts and Dependency Injection8 3.1 CDI Bean ...... 9 3.2 Enabling CDI ...... 10 3.3 Injection ...... 10 3.4 Producer members ...... 12 3.5 Scopes ...... 13 3.6 Qualifiers ...... 15 3.7 Other CDI features ...... 16 3.8 BeanManager API ...... 17 3.9 Weld ...... 18

4 WildFly 20 4.1 Extending Wildfly ...... 21 4.2 Undertow ...... 21 4.3 Accessing BeanManager ...... 22

5 Eclipse platform and Eclipse IDE 23 5.1 Eclipse platform ...... 23 5.2 OSGi framework end Equinox ...... 24 5.3 Project e4 ...... 25 5.4 Eclipse IDE ...... 27 5.5 Zest ...... 27 5.6 Tycho ...... 29

6 JBoss Tools 31 6.1 CDI Tools ...... 31 6.2 Server Tools ...... 33

1 7 TinkerPop 34 7.1 Blueprints ...... 34 7.2 Pipes ...... 36 7.3 Gremlin ...... 37 7.4 Frames ...... 38

8 Design and implementation 40 8.1 Design ...... 40 8.1.1 Used technologies...... 42 ...... 42 8.2 Weld extension ...... 43 8.3 Common data model ...... 43 8.4 Eclipse plugins and user interface ...... 43 8.5 CDI compatibility ...... 48 8.6 Installation ...... 48 8.7 Implementation problems ...... 49 8.8 Possible extensions ...... 51

9 Conclusion 52

A Content of electronic attachment 58

2 Chapter 1 Introduction

Software projects are getting more complex and larger every day. Accord- ing to study of Deshpande and Riehle the pace of growth of open source1 project is exponential [1]. This brings new challenges to software devel- opers in managing projects and getting oriented. Integrated development environments come with wide range of tools to facilitate the process of development. It could be context aware code completion, code structure overview, type hierarchy visualization and others. The goal of this thesis project is to design and develop similar tool to support of Java Enterprise Edition applications using CDI2 technology. The tool is supposed to help developers to get an overview of the project by visualizing relations of beans. The core features of CDI technology are bean life-cycle management and, as the name implies, dependency injection. These features allow to keep the code less complicated. On the other hand, the separation of bean definition and its usage bring questions like ‘What is the implementation of this bean?’ or ‘Where is this bean implementation used?’. This thesis project should help to answer these questions visually by creating a graph of beans and their types showing the origin of beans and their usage. It should allow users to filter beans according their attributes for them to be able to focus only on certain part of application. It should also provide detailed information about selected bean. The tool is intended to work with both forms of projects – source code and deployed running application. According to my research, there is no other project dealing with this problem. Implemented tool, called CDI Inspector, consists of two parts. A Wild- Fly3 application server extension, that gathers CDI related information about

1http://opensource.org/osd 2Contexts and Dependency Injection 3Described in chapter4.

3 1. INTRODUCTION running applications and provides it over REST4 protocol. And a set of plu- gins to Eclipse IDE5 that is able to visualize and inspect data from WildFly extension and also examine local source code projects. Chapter2 sums project requirements and outline its architecture. Fol- lowing five chapters describe used technologies. Chapter8 describes design of CDI Inspector and particular implemented units.

4Representational State Transfer, http://www.ics.uci.edu/~fielding/pubs/ dissertation/rest_arch_style.htm 5Described in chapter5

4 Chapter 2 Analysis

2.1 Requirements

The goal of the practical part of thesis is to design and implement a set of tools to analyze CDI applications with respect to CDI beans and their attributes and to visualize obtained information. The system should be able to process both running projects deployed in application server and projects in form of source code in IDE. The visualization is intended to be helpful to developers. So it has to allow to be used interactively, to show detailed information about nodes and to filter shown nodes. Because of the extent of CDI technology it is not required to cover all its features but rather focus on basic attributes of beans and its relations. The thesis topic was offered and the project development consulted by Czech branch of Red Hat1 company. This influenced the requirements, par- ticularly selection of used technologies because result project should be compatible with products. Hence, the project requirements are following: • The system should provide the extension of Java EE application server in order to get information about running applications and make this information available over REST2 protocol. • The system should provide an extension of an IDE in order to get information about projects in form of source code. • The system should provide visualization of CDI beans and their rela- tions from both sources. • User should be able to filter graph nodes based on attributes of beans. • The system should provide detailed information for displayed graph nodes.

1http://www.redhat.com 2Representational state transfer

5 2. ANALYSIS

• The system should allow user to jump from visualized bean to source code of bean implementation if local project is inspected.

• The system should take into account possible future alternative visu- alizations of data provided by server extension.

• The application server extension should minimize its effect on de- ployed applications.

• All parts of system should be easy to install and use.

• Project code base should be ready for collaborative development.

2.2 Architecture outline

Because of the requirement of compatibility with Red Hat products, Wild- Fly3 is used as an application server and Eclipse IDE4 in conjunction with JBoss Tools5 is used as target platform for source code project analysis and visualization. The project consists of two logical components. A WildFly extension that deals with extraction of data about running CDI applications, and making them available via HTTP protocol in JSON format. The other component is a set of Eclipse IDE plugins and has two goals. To analyze CDI project in form of source code, and to provide a GUI to visualize data in graph-like form from both components in conjunction with graph filtering. The graph should reflect basic bean attributes and relations of injecting and producing. The source code analysis is based on a JBoss Tools plugin for CDI support. Filtering is accelerated using a graph database. From the use-case analysis point of view the system is pretty simple. There is only one role interaction withc the system – user, typically a devel- oper. This user can perform only two use-cases as shown in figure 2.1. Either to analyze local or remote project. Both use-cases are extended by filtering use-case that allows to focus only on certain part of visualized graph. Local inspection use-case is very straightforward. User selects a CDI project in Eclipse IDE window, and activate a context menu item to start inspection. Then CDI Inspection window is opened, if necessary, and graph is drawn.

3Described in chapter4. 4Described in chapter5. 5Described in chapter6.

6 2. ANALYSIS

Figure 2.1: Usecase diagram

To start remote inspection use-case user has ensure that CDI Inspector window is visible. Then he or she selects a toolbar button to open a dialog for deployed application selection. The dialog allows either to directly enter URL of running application or to select an application, the deployment of which is managed by IDE, from list.

7 Chapter 3 Contexts and Dependency Injection

Contexts and Dependency Injection (CDI) is a Java Enterprise Edition1 (Java EE) standard specified by JSR 2992 (version 1.0) in 2009 and later by JSR 3463 (version 1.1) in 2013. It is the main building block of Java EE modularity. Most important features brought by CDI are: dependency injection, object life-cycle management, event passing and support for cross-cutting con- cerns. They allow to decouple application components and keep the source well structured. Dependency injection is an implementation of design pattern Inversion of control by Martin Fowler. Conventional components layering naturally leads to high-level parts being dependent on low-level parts. Such depen- dency makes the code rigid and hard to maintain. Figure 3.1 shows such layout. If the higher level component (A) is changed, code in dependent component (B) will require update. Inversion of control (figure 3.2) pattern suggests to decouple dependent parts by introducing new component – common interface (C). Such layout allows high level components to use services of low level component without being aware of their particular implementation. Thus low level component can be replaced by another without modification of high level component. [2]

Figure 3.1: Standard dependency Figure 3.2: Inversion of control

1http://www.oracle.com/technetwork/java/javaee/overview/index. html 2https://jcp.org/en/jsr/detail?id=299 3https://jcp.org/en/jsr/detail?id=346

8 3. CONTEXTSAND DEPENDENCY INJECTION

CDI implements the Inversion of control pattern. It means that objects in application using CDI can declare a dependency on some Java type and CDI will provide an instances of this type either by using existing instance or by creating new one. This injection service is, as part of CDI, provided to application by Java EE server. [4]

3.1 CDI Bean

“In CDI, a bean is a source of contextual objects that define application state and/or logic” [3]. Life-cycle of bean instances is managed by CDI container. Each bean has following attributes:

• a (nonempty) set of bean types, • a (nonempty) set of qualifiers4, • a scope5, • optionally, a bean Expression Language6 name, • a set of interceptor bindings, • a bean implementation.

Bean type can be almost any Java type: Java class, interface, type param- eterized by type parameters or variables, array (component type is taken into account) or primitive type. Primitive types are considered equivalent to their object wrapping classes. [3,4] Bean attributes, except the last two mentioned, serve as a key for depen- dency resolution process. Injection point, a place in code where injection of a dependency is required, declares some restrictions on bean instance of which should be injected. These restrictions are related to bean attributes. There are several sources of beans in CDI applications. Selected classes7 in application archive may represent beans – class beans. Bean instances can be also produced by producer members8. Session beans, as defined by Enterprise JavaBeans (EJB)9, can also be injected using CDI.[4,5]

4Described in section 3.6. 5Described in section 3.5. 6https://jcp.org/en/jsr/detail?id=341 7Described in section 3.2 8Described in section 3.4. 9https://jcp.org/en/jsr/detail?id=318

9 3. CONTEXTSAND DEPENDENCY INJECTION

3.2 Enabling CDI

At the deploy time each Java EE application is examined in order to decide whether or not to enable the support of CDI technology. If it is found that the support should be enabled, application archive is scanned and a list of beans and a list of injection points are computed. CDI specification recognizes two different kinds of archives that are associated with different modes of archive scanning: The archive can be either explicit bean archive or implicit bean archive. Explicit bean archive, is identified by containing of beans.xml file. Application that uses CDI technology can be packaged in of the following archive: EAR, JAR, WAR. For EAR and JAR bundles the beans.xml is located in META-INF direc- tory, for WAR it is in WEB-INF directory. Explicit bean archive implies that all suitable10 classes automatically became class beans. Implicit bean archive does not contain beans.xml file in specified di- rectories and only beans annotated by some scope11 annotation become class beans. This option is new in CDI 1.1. [7,6].

3.3 Injection

Injection is a process of finding suitable bean for an injection point, obtain- ing a bean instance and passing the instance to injection point member. CDI allows injection of fields, method parameters and constructor param- eters. Each class member that requires dependency injection is annotated by Inject12 annotation. Snippet1 shows injection of all three kinds of members. Line 4 shows injection into a field. Annotating of a constructor (line 7) allows CDI to create an instance with all its dependencies so that the object is never in inconsistent state. Similar effect can be achieved by initializer method (line 12) – a Inject annotated method. The advantage of such methods is that they can be used both for CDI initialization and then by regular application code. Injections are processed in following order: con- structor, fields, initializer methods. [4]

10Class bean requirements available at http://docs.jboss.org/cdi/spec/1.1/ cdi-spec.html#what_classes_are_beans 11See section 3.5 12javax.inject.Inject

10 3. CONTEXTSAND DEPENDENCY INJECTION

1 class Vehicle { 2 3 @Inject 4 private int seatCount; 5 6 @Inject 7 public Car(int seatCount) { 8 this.seatCount = seatCount; 9 } 10 11 @Inject 12 public void setSeatCount(int seatCount) { 13 this.seatCount = seatCount; 14 } 15 }

Code listing 1: Example of CDI injection

Injectable objects are generaly bean instances. Beans can be of various kinds [5]:

• class beans

• producer member beans

• Java EE resources

• session beans

The process of finding proper bean for certain injection point is called type-safe resolution. The type-safe resolution algorithm takes into account type and qualifiers of the injection point and tries to find a bean, the type set of which contains the injection point type and the set of qualifiers of the bean contains all qualifiers of the injection point. Beans that fulfill these conditions are called assignable.[7] There are three possible outcomes of type-safe resolution algorithm. Ide- ally exactly one assignable bean is found and an instance of it is injected. Otherwise there are none or more then one suitable beans. These situa- tions are called unsatisfied dependency and ambiguous dependency re- spectively, and their occurrence presents an error state that is reported by appropriate exception. Applications are scanned at deploy time for these kinds of problems and if either of them occurs, the deploy will fail.

11 3. CONTEXTSAND DEPENDENCY INJECTION

3.4 Producer members

Producer members are methods and fields annotated by Produces13 an- notation. They serve as one source of beans. Sometimes it can be difficult to arrange all necessary initializational operations in constructor, JPA14 en- tities can be en example. In such situations producer methods can be used, instead of simple class beans, to create and return an instance of requested bean. Another use-case of producer methods are beans the instances of which depend on application state or place, they are injected into. [4] Code listing2 shows usual example of a producer method – random generator (line 10). Producer fields (line 7) are often used for constants or precomputed results. They can be understood as a syntactic sugar for a producing methods returning constant value. Typesets of produced beans correspond to method return types or types of producing field.

1 public class RandomNumberGenerator { 2 3 private Random random = 4 new Random(System.currentTimeMillis()); 5 6 @Produces 7 public static final String foo = "bar"; 8 9 @Produces 10 public int getRandomNumber() { 11 return random.nextInt(100); 12 } 13 }

Code listing 2: Producer members [4]

Producer methods can have parameters that allow to customize returned bean instance. Parameters of Produces annotated method are considered to be injection points and are injected similarly to parameters of initializer methods. In addition to beans that can be usually injected, producer meth- ods are offered one special bean of type InjectionPoint15 (listing4). This bean provides information about injection target. Thus the producing method can adjust the returned object according to individual injection

13javax.enterprise.inject.Produces 14Java Persistence API, http://www.oracle.com/technetwork/java/javaee/ tech/persistence-jsp-140049.html 15javax.enterprise.inject.spi.InjectionPoint

12 3. CONTEXTSAND DEPENDENCY INJECTION

points. Typical example is injection of a logger that is aware of target class name as shown in listing3.

1 @Produces 2 Logger createLogger(InjectionPoint injectionPoint) { 3 return Logger.getLogger(injectionPoint.getMember().↩ ↪ getDeclaringClass().getName()); 4 }

Code listing 3: Method producing a logger [4]

1 public interface InjectionPoint { 2 public Type getType(); 3 public Set getQualifiers(); 4 public Member getMember(); 5 public Bean getBean(); 6 public Annotated getAnnotated(); 7 public boolean isDelegate(); 8 public boolean isTransient(); 9 }

Code listing 4: InjectionPoint interface

First three methods of InjectionPoint interface are important from CDI Inspector perspective. getType() method returns the type that is required by the injection point, getQualifiers() returns set of injec- tion point qualifiers and getMember() returns reference to either field or method that defines that injection point.

3.5 Scopes

Scope is one of the bean attributes. It determines life-cycle of the bean that is when the beans are created and destroyed. CDI specification comes with four predefined scopes. It is also possible for application developers to de- fine their own scope however this option is rather intended for framework developers. Predefined scopes are: [4,8]

Request scope Instances of this scope lives for a duration of single HTTP request.

Conversation scope allows programmer to define length of life of man- aged instances. By default it works similarly as request scope and

13 3. CONTEXTSAND DEPENDENCY INJECTION

the duration can be lengthen up to the duration of HTTP session. It is intended for holding a state during several requests that together forms a single task. For instance filling a multi-page form.

Session scope corresponds to a HTTP session.

Application scope defines that bean instances are shared across whole ap- plication.

Specification also defines a pseudo-scope called dependent. Life-cycle of bean instance of dependent scope is defined by the injection target. New instance of dependent scoped bean is created for each injection point . Scopes are assigned to beans by annotations of classes (in case of class beans) or of producer members (in case of producer members). Bean sources that are not annotated by any scope annotation define dependent beans. Relevant annotations for predefined scopes are: ApplicationScoped16, TransactionScope17, SessionScoped18, RequestScoped19 and Dependent20. Listing5 shows scope annotation of class (line 2) and producer method (line 6). Code snipped also shows session scoped class Foo to implement Serializable21 interface. Session scoped and transaction scoped beans should implement this interface for application server to be able to passi- vate them.

1 @SessionScoped 2 public class Foo implements Serializable { 3 private static final long serialVersionUID = 1L; 4 5 @RequestScoped 6 public int bar() { 7 return 0; 8 } 9 }

Code listing 5: Example of scope annotations

16javax.enterprise.context.ApplicationScoped 17javax.transaction.TransactionScope 18javax.enterprise.context.SessionScoped 19javax.enterprise.context.RequestScoped 20javax.enterprise.context.Dependent 21java.io.Serializable

14 3. CONTEXTSAND DEPENDENCY INJECTION

3.6 Qualifiers

Sometimes it could come handy to have more than one bean of the same type. CDI introduces marking annotations – qualifiers – to distinguish among such beans. Both sources of beans and injection points can be an- notated by qualifiers. It is possible to use more than one qualifier for the same entity. As mentioned in section 3.3, the type-safe resolution algorithm reflects qualifiers in process of selecting a suitable bean for injection point and ensures that all qualifiers of injection point are present in set of quali- fiers of assignable bean. [4] Code listing6 demonstrates a qualifier definition. It is a runtime anno- tation annotated by Qualifier22. Following listing7 shows a qualified producer. The bean is of type String23 and the qualification allows it to be distinguished among other beans of the same type set. Snippet number 8 shows annotating of injection points. Field annotation (line 5) is pretty natural. When injecting into a method parameter (line 8) there is only one Inject annotation. However each parameter can be preceded by its own list of qualifiers.

1 @Qualifier 2 @Retention(RUNTIME) 3 @Target({METHOD, FIELD, PARAMETER, TYPE}) 4 public @interface Red { 5 }

Code listing 6: Qualifier definition

1 public class Foo { 2 3 @Red 4 @Produces 5 private final String redCode = "#ff0000"; 6 }

Code listing 7: Qualified producer field

CDI also allows qualifier interfaces to define methods. Values of quali- fier methods are reflected by type-safe resolution algorithm. Using different

22javax.inject.Qualifier 23java.lang.String

15 3. CONTEXTSAND DEPENDENCY INJECTION

1 public class Bar { 2 3 @Red 4 @Inject 5 private String colorCode; 6 7 @Inject 8 public void setColor(@Red String color) { 9 // ... 10 } 11 }

Code listing 8: Qualified injection points

method values rather then defining new qualifiers can reduce number of qualifiers. There is one special predefined qualifier – Named24. It allows to use beans in the Expression Language25. Beans are referenced using value of Named annotation. The qualifier can also annotate class or producer mem- ber without specifying a value. In that case the class or member name with first letter lowered is used as name. Except exact qualifier matching CDI specification allows more general filtering of assignable beans. Following two predefined qualifiers are in- tended to qualify injection points only. Default26 is automatically assigned to beans that do not explicitly define any qualifier except Named and to any injection points that are not explicitly qualified. It ensures that unqualified injection points will only get injected unqualified beans. [9] Any27 is a qualifier that is automatically assigned to all beans, no matter what qualifier they declare. Hence an injection point annotated by Any can be injected by any bean regardless its qualifiers. [10]

3.7 Other CDI features

This section briefly describes several other important features of CDI spec- ification that CDI Inspector is not focused on.

24javax.inject.Named 25https://java.net/projects/el-spec/ 26javax.enterprise.inject.Default 27javax.enterprise.inject.Any

16 3. CONTEXTSAND DEPENDENCY INJECTION

Annotations PostConstruct28 and PreDestroy29 allows to mark life- cycle callback methods that are called right after all injections are done and before the bean instance is destroyed, respectively. [4] Disposer methods are methods one parameter of which is annotated by Disposes30. They are called at the end of life-cycle of bean instance that matches the annotated parameter. It allows to perform cleanup operations similarly to pre-destory method. CDI specification allows to have multiple implementations of one bean interface. It can be achieved by selecting one primary implementation, that remains untouched, and the alternative implementations are annotated by Alternative31. Such implementations are disabled by default and ap- plication can be instructed to use alternative annotation in beans.xml configuration file. Interceptors is a concept to dealing with cross-cutting concerns. It allows to call same piece of code on multiple places by simple method annotation. CDI support this concept by ability to define interceptor bindings – an annotations that marks both the interceptor implementation and place of its usage. Multiple interceptor bindings and a scope definition can be bundled into one annotation – stereotype – to prevent the code from being congested by annotations. Decorators is another tool defined by CDI to support cross-cutting con- cerns. Unlike interceptors, they perform context aware interception. Dec- orators are interface implementations that intercept calls of own interface and are able to extend or alter such calls. Events allows to decouple application components by message passing communication. Classes that want to send messages can inject instance on Event32 interface that do so by using fire() method. Message receiving classes defines methods that has Observes33 annotated parameters.

3.8 BeanManager API

This section describes CDI framework API necessary to obtain information about beans and their relations.

28javax.annotation.PostConstruct 29javax.annotation.PreDestroy 30javax.enterprise.inject.Disposes 31javax.enterprise.inject.Alternative 32javax.enterprise.event.Event 33javax.enterprise.event.Observes.

17 3. CONTEXTSAND DEPENDENCY INJECTION

BeanManager34 is a central interface of CDI framework. It is intended to be used mostly by CDI extension and its 39 methods allows nearly full control of framework. Among other things it can for instance create new beans or injection points or fire arbitrary events. From perspective of CDI Inspector the most important method is getBeans() shown in snippet9. It allows to get a set of all beans managed by CDI using the Any qualifier (listing 10).

1 public interface BeanManager { 2 3 // ... 4 5 public Set> getBeans(Type beanType, 6 Annotation... qualifiers); 7 }

Code listing 9: getBeans method declaration

1 // BeanManager manager = ... 2 Set> allBeans = this.beanManager.getBeans(Object.class, 3 new AnnotationLiteral() {});

Code listing 10: Obtaining all beans

Elements of returned set are instances of Bean35 interface. getInjectionPoints() method of this interface gives a notion of injec- tion relations among beans. Bean interface also extends interface BeanAttributes36 (shown in listing 11) that describes attributes of beans as mentioned in section 3.1. Method getName() return Expression Lan- guage name of the bean, other methods are self-explanatory.

3.9 Weld

Weld is a reference implementation of CDI specification developed by Red Hat. It is used by Java EE application servers like WildFly or GlassFish. It

34javax.enterprise.inject.spi.BeanManager 35javax.enterprise.inject.spi.Bean 36javax.enterprise.inject.spi.BeanAttributes

18 3. CONTEXTSAND DEPENDENCY INJECTION

1 public interface BeanAttributes { 2 public Set getTypes(); 3 public Set getQualifiers(); 4 public Class getScope(); 5 public String getName(); 6 public Set> getStereotypes(); 7 public boolean isAlternative(); 8 }

Code listing 11: BeanAttributes interface

can also be used in servlet-only environments like Tomcat or in conjunction with pure Java SE37.[11] Although CDI API provide almost complete picture about beans, it can’t distinguish between field producer and method producer. Weld describes these entities by two different classes: ProducerField38 and ProducerMethod39.

37http://www.oracle.com/technetwork/java/javase/overview/index. html 38org.jboss.weld.bean.ProducerField 39org.jboss.weld.bean.ProducerMethod

19 Chapter 4 WildFly

WildFly is an application server by Red Hat written in Java. Its first version, number 8, is a direct successor of JBoss Application Server 7. It implements Java EE 7 platform specification. [12] The server can be started in two different modes. Standalone mode denotes server instance working independently. Domain mode allows mul- tiple servers to share the same configuration. Depending on used mode, the server follows different configuration files. The files are located at (rela- tively to WildFly installation folder) standalone/configuration/ standalone.xml and domain/configuration/domain.xml, respec- tively. [13] WildFly has modular architecture. It consists of small module managing core and modules (alternatively called extensions) stored in modules direc- tory (relatively to WildFly installation folder). WildFly distribution comes with basic set of modules, others can be added by users. Module related settings is stored in configuration files. Both of them has XML format similar structure. Key tags with respect to moduels are and . Sub-elements of states which modules should be loaded. Extension is a unit of packaging and distribution. Each extension con- sists of one or more subsystems, units of functionality. List of enabled sub- systems and their configurations are held in sub-elements of tag . Listing 12 shows part of standalone.xml configuration file. WildFly employs JBoss Modules1 project to separate classes of different modules. Extensions can define dependencies on each other. Each module has a its own classloader2 that only allows it to access own classes or classes of the dependencies. [14]

1https://docs.jboss.org/author/display/MODULES/Introduction 2http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader. html

20 4. WILDFLY

1 2 3 4 5 ... 6 7 9 ... 10 11 12 13 ... 14

Code listing 12: Snippet of standalone.xml configuration file

4.1 Extending Wildfly

WildFly extension consists of extension descriptor file module.xml and one or more Java archives containing implementation. Key information stored in descriptor file are: extension name, references to Java archives compris- ing the extension and list of dependencies in form of other extensions. [15] Each extension has to implement Extension3 interface. The implemen- tation is referenced by standard Java ServiceLoader API4. initialize() method of Extension interface allows subsystem to register of deploy- ment processors. Deployment processor, represented by instance of DeploymentUnit- Processor5 interface, is a deployment operation callback. It can alter the application being deployed, obtain information about such application or perform any other operation at deployment time.

4.2 Undertow

Undertow is an embeddable web server written in Java and developed by Red Hat. It comprises an integral part of WildFly server. [16]

3org.jboss.as.controller.Extension 4http://docs.oracle.com/javase/7/docs/api/java/util/ ServiceLoader.html 5org.jboss.as.server.deployment.DeploymentUnitProcessor

21 4. WILDFLY

Key concept of processing a HTTP request by Undertow is chaining of HttpHandler6 interface instance. As shown in listing 13, the interface contains a single method that could either serve the request or pass it to arbitrary other handler. In general there is no pipeline of handlers defined by Undertow. [17]

1 public interface HttpHandler { 2 void handleRequest(HttpServerExchange exchange) 3 throws Exception; 4 }

Code listing 13: HttpHandler interface

WildFly uses HandlerWrapper7 no chain HTTP handlers and allows extensions to register HandlerWrapper instances with application han- dler chains. In conjunction with requested address matching, it allows to shade particular requests form an application and process them by exten- sion.

4.3 Accessing BeanManager

BeanManager instance is managed by WeldBootstrapService8, a MSC9 service. There is one instance of BeanManager and managing service per application. In order to get a reference to WeldBootstrapService, one has to declare new MSC service depending on coveted service. A new ser- vice has then access to service registry containing WeldBootstrap- Service instance. [18]

6io.undertow.server.HttpHandler 7io.undertow.server.HandlerWrapper 8org.jboss.as.weld.WeldBootstrapService 9Modular Service Container, https://docs.jboss.org/author/display/MSC/ Home

22 Chapter 5 Eclipse platform and Eclipse IDE

5.1 Eclipse platform

Eclipse platform is a set of Java frameworks and services that allows to create an IDE1. It consists of the core element, Eclipse RCP, and application components related to software development . For example: comprehen- sive text editor, debugging framework, support for application help and others. Eclipse platform structure is outlined in figure 5.1. The platform is developed by Eclipse Foundation. [19, 20] Eclipse RPC2 is a minimum set of plugins of the platform that allows to create rich desktop applications not necessarily related to IDE. Key compo- nent of Eclipse RPC are:

SWT (Standard Widget Toolkit) is a Java widget toolkit for creation native looking user interfaces. JFace framework, built on top of SWT, pro- vides higher level of abstraction when accessing SWT elements.

Workbench – set of tools to manage workspace resource.

Equinox – an application container enabling modularity and plugin de- pendency management of applications based on Eclipse RCP.

Application model, DI (Dependency injection), user interface framework allowing to decouple UI3 model from both its implementation and business code.

1Integrated Development Environment 2Rich Client Platform 3User Interface

23 5. ECLIPSE PLATFORM AND ECLIPSE IDE

Figure 5.1: Eclipse platform

5.2 OSGi framework end Equinox

OSGi4 is a set of specifications defining component and service model for Java. Equinox is an OSGi implementation used by Eclipse RCP to achieve modularity. [21] OSGi specification contains three key concepts: modularity, life-cycle management and services. Modularity deals with division application into modules (also denoted as bundles or plugins in context of Eclipse) that can cooperate. Modules are Java archives containing module descriptor file located at META-INF/MANIFEST.MF with respect to bundle root. De- scriptor file contains among basic descriptive attributes, like bundle name, symbolic name or version, a list of module dependencies in form of module names and versions or imported packages and list of exported packages. This allows to introduce effective, yet safe module cooperation based on separate class loading. [19] Next aspect is life-cycle management. It allows to define life-cycle call- backs of plugins and lazy module start. It means that at the time of OSGi runtime startup, the runtime only verifies availability of dependencies. De- pendency module is only loaded when some class of this module is re- quired. It allows fast runtime start and saves system resources. OSGi services enable modules to communicate with each other using publish-find-bind5 pattern. Apart form OSGi implementation Equinox also implements p2 speci- fication6. It is a provisioning platform for Eclipse. p2 allows to manage,

4Open Service Gateway initiative 5http://bethorough.wordpress.com/2008/11/03/ service-oriented-computing-publish-find-bind/ 6http://eclipse.org/equinox/p2/

24 5. ECLIPSE PLATFORM AND ECLIPSE IDE install and update OSGi bundle of Eclipse RPC. Plugins and plugin groups, features, are distributed using repositories. [22]

5.3 Project e4

Project e4 (sometimes denoted Eclipse 4) is a new architecture of Eclipse RPC that appeared first in Eclipse 4.2 (the first stable release of fourth gen- eration). Even though the project is used in stable releases, it is still un- der development and some parts of API are provisional. The main aim of the project is to simplify Eclipse programming model in order to lower maintenance costs and make platform available to wider developer com- munity. [19, 23] Key concepts of e4 architecture are:

• Application model

• Dependency injection

• Behavioral annotations

• Platform services

• Platform scripting using dynamic languages

• CSS customizable appearance

Following text describes concepts relevant to CDI Inspector. Application model is an object model that describes RCP application. It contains both visual and non-visual elements. Visual elements can be for example Eclipse windows, parts or toolbars and non-visual can be handlers – a named link to action performing class. Application model contains all elements of application and their states. It is interactive, serializable, cus- tomizable and extendable. The model can be changed at run-time using API. It also reflects user customization of graphical interface like changing windows layout of workspace. The model nodes has bidirectional map- ping to XML. Application state is stored in XML file, plugins can extend applications by defining a XML snippet that is later merged with applica- tion model. Most of model nodes allows developer to store custom data. Key asset of application model is decoupling. Classes that constitute UI are referenced form model an don’t contain any mutual linkage in code. This naturally comes with life-cycle management – classes referenced form the model are instantiated and destroyed by platform. [19].

25 5. ECLIPSE PLATFORM AND ECLIPSE IDE

Figure 5.2: Eclipse context hierarchy[24]

Application model managed classes can utilize dependency injection. It is inspired by CDI and even reuses some CDI annotations. Fields and constructor and method parameters can by injected by annotating the class member by Inject7. Injection resolution is based on types of injected in- stance and context. Context is a string indexed hash map that holds in- stances available for injection. The indices are fully qualified names of man- aged instance. Several application model nodes define their own context. Contexts are, based on model hierarchy, connected into a tree structure (figure 5.2). The lookup procedure first check the current context if search fails, parent context is checked. Classes managed by application model are also offered to use so called behavioral annotations. They can be for instance life-cycle callbacks Post- Construct8 and PreDestroy9 that works similarly to CDI, or Execute10 that denotes method to call when a class is used as action handler in appli- cation model. Behavioral annotations automatically enable method param- eter dependency injection. Platform services allow application to easily access e4 API using injec- tion. It replaces platform singletons of previous Eclipse 3 API, like Platform11 or PlatformUI12. Services allows to perform wide range of action. For example: EModelService13 allows directly manipulate appli- cation model, ESelectionService14 gives access to currently selected

7javax.inject.Inject 8javax.annotation.PostConstruct 9javax.annotation.PreDestroy 10org.eclipse.e4.core.di.annotations.Execute 11org.eclipse.core.runtime.Platform 12org.eclipse.ui.PlatformUI 13org.eclipse.e4.ui.workbench.modeling.EModelService 14org.eclipse.e4.ui.workbench.modeling.ESelectionService

26 5. ECLIPSE PLATFORM AND ECLIPSE IDE elements of UI or IEventBroker15 provides ability for application com- ponents to communicate by sending events.

5.4 Eclipse IDE

Eclipse IDE is an IDE based on Eclipse platform by adding plugins for software developments. Architecture of Eclipse IDE is shown 5.3. Most of IDE plugins uses obsolete Eclipse 3 API for historical reasons. That’s why there is a compatibility layer on top of Eclipse platform allowing these plugins to be executed. Following list describes the most important sets of Eclipse IDE plugins: PDE (Plugin Development Environment) provides tools related to Eclipse RPC plugins development. It allows to create, test and debug plugins, and also to create features, p2 repositories and RCP applications. [25] JDT (Java Development Tools) allows Java development in Eclipse. It comes with Java project types, plenty of wizards and views. JDT also con- tains plugins for Java compilation, code validation and editing. To support such features JDT is able to create a comprehensive object model of source code. [26] WTP (Web Tools Platform) is set of plugins allowing Java EE develop- ment. There are components supporting for example JPA, EJB16, JSF17 or JavaScript and also for managing aplication servers and deploy- ments. [27]

5.5 Zest

Zest is an visualization toolkit for Eclipse developed by Eclipse Foundation. It is focused on creating graph-like (nodes interconnected by edges) inter- active visualizations. It was designed as a lightweight alternative to GEF18, a framework for creating rich graphical editors. [28] Zest is based on Draw2d, a toolkit for laying out and rendering to SWT canvas. Draw2d allows to define graphical components – figures – that can be grouped in parent-child manner. Figure have a rectangular shape

15org.eclipse.e4.core.services.events.IEventBroker 16Enterprise JavaBeans 17JavaServer Faces 18Graphical Editing Framework, http://www.eclipse.org/gef/

27 5. ECLIPSE PLATFORM AND ECLIPSE IDE

Figure 5.3: Eclipse IDE architecture [19]

and can be interconnected using anchors and edges. Figures as well as whole visualization are able to listen to SWT events. This allows seamless integration with Eclipse environment. [29] Zest works with concept of items. There are four types of items: graphs, nodes, connections and containers. All classes representing these items are descendants of standard SWT class Widget19 and can take all of its advan- tages like listeners. Graph item represents root of visualization, a canvas. A layout algorithm is assigned to each graph to determine default positions of vertices. The vertex can be represented either by atomic node item or container item that is able to hold sub-nodes and work as a root of sub- graph. Nodes and containers are interconnected by means of the last type of item – connections. Each type of node is assigned an Draw2d figure that defines its appearance. Default node figure allows to show a image and/or a text label. There are two levels of abstraction available in Zest API. The low level API directly manipulates nodes and connection as shown in listing 14. The high level API is base on JFace20 project principles. Such API al- lows to visualize arbitrary hierarchical object structure by implementing IGraphEntityContentProvider21 interface and standard JFace

19org.eclipse.swt.widgets.Widget 20User interface framework built on top of SWT. http://wiki.eclipse.org/JFace 21org.eclipse.zest.core.viewers.IGraphEntityContentProvider

28 5. ECLIPSE PLATFORM AND ECLIPSE IDE

1 // Composite parent = ... 2 Graph graph = new Graph(parent, SWT.NONE); 3 GraphNode node = new GraphNode(g, SWT.NONE, "label1"); 4 GraphNode node2 = new GraphNode(g, SWT.NONE, "label2"); 5 new GraphConnection(graph, SWT.NONE, node, node2); 6 g.setLayoutAlgorithm(new SpringLayoutAlgorithm(), true);

Code listing 14: Zest API example

ILabelProvider22 interface. These two implementations together with a root object of visualized structure are passed to an instance of GraphViewer23 that takes care of creation of a graph item, traversing the structure and creating nodes and connections.

1 public interface IGraphEntityContentProvider 2 extends IStructuredContentProvider { 3 public Object[] getConnectedTo(Object entity); 4 }

Code listing 15: IGraphEntityContentProvider interface

As shown in code listing 15, the IGraphEntityContentProvider interface define only one new method on top of standard JFace interfaces. getConnectedTo() method, given a model object of graph node, returns targets of connections incident to the input object.

5.6 Tycho

Eclipse IDE doesn’t use any Java widely accepted build system like Ant24 or Maven25, but it uses its own system to compile and build projects. It allows Eclipse IDE to fully integrate the build system and provide complete user interface for sytem settings. The key disadvantage of Eclipse IDE build system, compared to systems like Maven, is that it is hard to use in collaborative environment. It lacks a dependency management, so the use in collaborative environment would require to introduce a new system to share binary dependencies or put them

22org.eclipse.jface.viewers.ILabelProvider 23org.eclipse.zest.core.viewers.GraphViewer 24http://ant.apache.org/ 25https://maven.apache.org/

29 5. ECLIPSE PLATFORM AND ECLIPSE IDE in some version control system. Also the configuration of build system is not designed to be shared. Project Tycho was created in order to cope with this problem. It allows to use Maven to build OSGi plugins, Eclipse plugins, features and create p2 repositories. It is a project maintained by Eclipse Foundation. The major contributor is Sonatype company, that also participates on Maven develop- ment. The key Tycho aim is to prevent metadata duplication. Standard Maven built projects declares their dependencies in project descriptor file – pom.xml and the dependencies themselves are store in Maven repository also described by a pom file. Tycho, on the other hand, produces OSGi bundles that keep the dependency description in MANIFEST.MF file. OSGi bundle are also usually distributed in p2 repositories, but maven reposito- ries are also capable to keep OSGi bundles. Tycho fundamentally changes the maven compilation. Pom file is used only to store build configuration and repository location specification. Project dependencies description is kept in manifest file. p2 repositories are used to resolve dependencies. There are two ways to specify a set of artifact to resolve dependencies against. It can be either all artifacts of all p2 repositories listed in pom.xml, or one can provide finer specification using *.target files that contains list of allowed artifacts. The compilation process change causes that standard Maven projects can’t be build in conjunction with Tycho projects. So one can’t directly use maven artifact as dependencies of Tycho project. A workaround is to create a standard Maven project that downloads necessary artifacts from Maven repository and wraps them in form of OSGi bundles. These bundles are put in standard maven local repository. Tycho support of Maven repositories allows to use such artifacts as dependency. Thus wrapped Maven artifact can be used by OSGi application.

30 Chapter 6 JBoss Tools

JBoss Tools is a set of open source plugins to Elipse IDE developed by Red Hat. It is distributed as separately installable feature or bundled with Eclipse IDE and additional branding. [30] The goal of these plugins is to extend support for various Java EE related technologies as well as to enable Eclipse to work with tools developed by Red Hat. JBoss Tools consist of projects adding or extending Eclipse support for Maven, JPA, CDI, web service, mobile development and others.

6.1 CDI Tools

CDI Tools brings a set of instruments to make the development of CDI application easier. It consists of two logical parts. One comes with complex beans.xml file editor and a set of wizards allowing to generate code of various CDI elements like qualifiers or interceptors. [31] The other part is based on object model of project source code. It creates a new object model of CDI application similar to the model defined by original CDI API. Such model allows JBoss Tools users to easily navigate from code of injection points to file containing definition of resolved bean, view list of assignable beans for certain injection point or validate that each injection point has exactly one assignable bean. It basically preforms type- safe resolution based on static code analysis. Aforementioned object model is used by CDI Inspector to retrieve infor- mation about local CDI projects. The key interface of this model is IBeanManager1. It plays similar role to this model as BeanManager do to CDI API except that it does not provides methods to change the model. The subinterface of IBeanManager – ICDIProject2 – can be obtained form object representing an general Eclipse project as shown in listing 16.

1org.jboss.tools.cdi.core.IBeanManager 2org.jboss.tools.cdi.core.ICDIProject

31 6. JBOSS TOOLS

1 private static ICDIProject getCdiProjectFromProject(IProject ↩ ↪ project) { 2 CDICoreNature nature = CDIUtil.getCDINatureWithProgress(↩ ↪ project); 3 ICDIProject cdiProject = nature.getDelegate(); 4 return cdiProject; 5 }

Code listing 16: Obtaining an instance of ICDIProject

Among 42 methods of IBeanManager interface (listing 17), there are two methods relevant to CDI Inspector. getBeans() method without pa- rameters (line 2) return all beans found in project. getBeans(boolean, IInjectionPoint) (line 3) allows to find suitable beans to given injection points.

1 public interface IBeanManager { 2 IBean[] getBeans(); 3 Collection getBeans( 4 boolean attemptToResolveAmbiguousDependency, 5 IInjectionPoint injectionPoint); 6 // ... 7 }

Code listing 17: IBeanManager interface

Both methods return instances of IBean3 interface that describes beans. Listing 18 also shows only the most relevant methods of this interface. Method getBeanClass reference the class of bean if the bean is a class- bean. If the bean is a producer member, it references a class that defines the producer member. Method at lines 4-7 a related to bean attributes. getInjectionPoints() returns all injection points that the bean con- tains. And finally open() allows to open the editor with bean implemen- tation. Code listing 18 also demonstrates that CDI Tools model mixes Eclipse’s type system (represented by IType4) and its own (represented by IParametedType5). CDI Tools type system is build on top of the Eclipse’s and the main advantage of this system is that it can more easily describe type parameters.

3org.jboss.tools.cdi.core.IBean 4org.eclipse.jdt.core.IType 5org.jboss.tools.common.java.IParametedType

32 6. JBOSS TOOLS

1 public interface IBean extends IScoped, IStereotyped, 2 ICDIElement, IVariable, IAnnotated { 3 IType getBeanClass(); 4 String getName(); 5 Collection getLegalTypes(); 6 Collection getQualifiers(); 7 boolean isDependent(); 8 Collection getInjectionPoints(); 9 void open(); 10 // ... 11 }

Code listing 18: IBean interface

6.2 Server Tools

Server tools is a set of plugins that extends Eclipse WTP by providing full support for Red Hat application server. It allows to manage such servers, deploy applications onto them and change server setting. [32] The underlying object structure of this tool represents each type of server by different class. This property is used by CDI Inspector to filter applica- tions running on WildFly server. Code snippet 19 demonstrates recognition of WildFly server given an standard Eclipse interface describing applications servers – IServer6.

1 IURLProvider urlProvider = (IURLProvider) server.getAdapter( 2 IURLProvider.class); 3 boolean isWildflyServer = urlProvider instanceof ↩ ↪ Wildfly8Server;

Code listing 19: WildFly server recognition

6org.eclipse.wst.server.core.IServer

33 Chapter 7 TinkerPop

This chapter describes key dependency of visualization part of CDI Inspec- tor. TinkerPop graph database is used to create object model of visualization that allows filtering. TinkerPop is a working group developing Java graph database framework of the same name. [33] Graph database stores data in form of graph structure that consists of nodes, edges and their properties. Every element is usually directly linked to neighbor elements [34]. This allows effective data browsing based its relations, in contract to standard relational databases, where data of the same type are clustered into tables. Graph database represents one branch NoSQL databases [35]. Although TinkerPop comes with its own graph database implementa- tion, primary aim of this project is to create unifying interface for Java graph databases and to build higher level tools that allows to fully utilize the power of graph databases. Most significant projects of framework can be organized into a stack structure based on its dependencies as shown in figure 7.1. The top most project Rexster is a graph server that provides graph database functionality over either REST or proprietary binary proto- col. Standard well-known algorithms for processing graphs (like Deep-first search, Dijkstra’s or Shortest path) are provided by project Furnace. The four lowest layers, used in CDI Inspector project, are described in following sections. [36, 37, 38]

7.1 Blueprints

Blueprints, the lowest layer of TinkerPop stack, is a unifying interface for graph databases. Databases can implement this interface in order to extend their interoperability. Applications the code of which depend purely on Blueprints can easily change underlying database implementation. Users of Blueprints supporting databases can also utilize higher levels of TinkerPop stack for graph processing. Blueprints is not only implemented by stan-

34 7. TINKERPOP

Figure 7.1: TinkerPop stack [36]

dard graph databases like Neo4j1 but there are also bindings for JDBC2 or JPA. [36] Blueprints defines a database common denominator – property graph model. This model presents graph as a set of graph elements – vertices and edges. Each element is uniquely identified by a Java object and holds a string-keyed map of its properties. In addition to these attributes vertices carry sets of incoming and outgoing edges. Edges keep track about head and tail vertex and a label that expresses a meaning of the edge. Thus the property graph model can be understood as a attributed, edge-labeled, directed multi-graph. [40, 41] Figure 7.2 depicts a small example of property graph that follows a structure used in CDI Inspector. It shows a Java type Constants that con- tains an Integer bean producing member. Each element is identified by an Integer object (numbers are auto-generated by default). Edges are labeled to differentiate their role. Bullet-starting lines are vertex properties. Blueprints API is simple and straightforward as shown in listing follow- ing listing. The first line (obtaining database instance) is the only database specific. A snippet describes creation of two interconnected vertices. [36]

1http://www.neo4j.org/ 2Java Database Connectivity

35 7. TINKERPOP

Figure 7.2: Example property graph

1 Graph graph = new TinkerGraph(); 2 Vertex a = graph.addVertex(null); 3 Vertex b = graph.addVertex(null); 4 a.setProperty("name","marko"); 5 b.setProperty("name","peter"); 6 Edge e = graph.addEdge(null, a, b, "knows"); 7 e.setProperty("since", 2006); Manipulating the property graph model represents a core of Blueprints API. Besides that, it also standardize an interface for transactions and in- dexing. Although the Blueprints is mainly an interface, it also comes with light- weight reference implementation called TinkerGraph. TinkerGraph is a POJO3 based, in-memory graph database with optional persistence. It sup- ports all Blueprints features except for transactions. [39]

7.2 Pipes

Pipes is a dataflow framework. Although it is primarily intended for graph processing, the design of framework allow to process data of any kind. The idea of Pipes resembles new Java 8 Stream API. The main interface Pipe4 represents an elementary unit of data processing. It can trans- form or filter data or execute some side effect operation. Type parameters S and E defines input and output types of an operation. Pipes can be chained

3http://www.martinfowler.com/bliki/POJO.html 4com.tinkerpop.pipes.Pipe

36 7. TINKERPOP

into pipelines to perform more complex operations. Framework consists of infrastructure classes and a library of predefined Pipe implementations of various kind. [42] Following code listing shows creation and usage of operation that re- moves a character from string and count the number of remaining ones. [42]

1 Pipe pipeline = new Pipeline( 2 new RemoveCharacterPipe("o"), 3 new CountCharactersPipe()); 4 pipeline.setStarts(Arrays.asList("marko","josh","peter")); 5 for(Integer number : pipeline) { 6 System.out.println(number); 7 } Pipes allows naturally traverse the graph and extract information based on elements adjacency. Pipe defined in following listing refers to graph on figure 7.2. It returns a set of vertices representing all types that are produced by members of an input type (also represented by vertex).

1 Pipe producedTypePipe = 2 new Pipeline( 3 new VerticesVerticesPipe(Direction.OUT, "hasMember"), 4 new VerticesVerticesPipe(Direction.OUT, "produces"), 5 new VerticesVerticesPipe(Direction.OUT, "mainType"), 6 new DuplicateFilterPipe());

7.3 Gremlin

Gremlin is a domain specific language for traversing graphs based on Groovy language5. It plays similar role to graph databases as SQL does to relational databases. However unlike SQL it is not a standard. Gremlin extends Groovy by adding several classes to allow using Blueprints and Pipes. The Gremlin code is usually more compact and readable compared to Java using Pipes. [43] There are three ways how to use Gremlin. It can be used as a part of Groovy interpret, as a string in Java code that is compiled and executed at run time or in Java annotations in conjunction with Frames (as described in section 7.4). Following snippet shows usage of Gremlin is Java code. The code de- fines a pipe that has exactly same semantics as the one defined in previous listing. Condensed syntax is redeemed by the lost of type safety.

5http://groovy.codehaus.org/

37 7. TINKERPOP

1 Pipe producedTypePipe = Gremlin.compile( 2 "_().out(’hasMember’).out(’produces’).out(’mainType’).↩ ↪ dedup()");

7.4 Frames

Using Blueprints low level API can be often too laborious. Framework Frames brings a higher level of abstraction by mapping graph elements to Java objects. It is similar concept to ORM6 and relational databases. The high level approach has several advantages: it is easier to write and maintain the code and it helps to avoid errors by enforcing a database schema. Blueprints on its own can’t ensure any structure of stored data. [44] Each type of object that is mapped by Frames is defined by an interface. Annotations of interface methods determine the mapping. There are several method annotations. The most commons are:

@Property is used to annotate getters and setters of underlying vertex prop- erties. The value parameter defines property name.

@Adjacency marks method related to adjacent vertices. It could be getters, setter or methods adding a neighbor vertex into collection. Annota- tion has two parameters. label sets the name of edge representing the adjacency and optional direction that determines an edge di- rection. If two different types of nodes are adjacent, it is not required for both to define their relationship.

@GremlinGroovy annotation allows to define the method result using Grem- lin language. It is often used to reference vertices that are not in direct adjacency.

Following code shows a definition of Frames annotated interface. Method getName at line 3 does not have a corresponding setter. This is made pos- sible by allowing to use both Blueprints API and Frames mapping at the same time.

6Object-relational mapping

38 7. TINKERPOP

1 public interface Person { 2 @Property("name") 3 public String getName(); 4 5 @Adjacency(label="knows") 6 public Iterable getKnowsPeople(); 7 8 @Adjacency(label="knows") 9 public void addKnowsPerson(final Person person); 10 11 @GremlinGroovy("it.out(’knows’).out(’knows’).dedup") 12 public Iterable getFriendsOfAFriend() 13 } Next code listing describes how to obtain a framed object. Instance of FramedGraph7 class allows to create a framing object based on graph el- ement identifier and mapping interface class. Other framed objects can be naturally obtained by calling getter methods of existing framed objects.

1 Graph graph = ...; 2 FramedGraphFactory factory = new FramedGraphFactory(new ↩ ↪ GremlinGroovyModule()); 3 FramedGraph framedGraph = factory.create(graph); 4 Person person = framedGraph.getVertex(1, Person.class); 5 person.getName();

7com.tinkerpop.frames.FramedGraph

39 Chapter 8 Design and implementation

8.1 Design

As outlined in chapter2, Analysis, the implementation has to have two parts – Ecilpse plugin and a WildFly extension. WildFly extension wraps a single subsystem that registers a deployment processor. This processor – a routine called at the time of each application deployment – ensures obtaining of instance of BeanManager and hooking the application so that a HTTP request on particular application address will result in JSON serialized data about CDI beans as an answer. All depen- dencies that are not provided by application server are bundled together with application code. The other part that integrates with Eclipse IDE consists of three plugins that are grouped together in one installable feature. The division is caused by limitations of OSGi framework and Tycho. The application logic is stored in main CDI Inspector plugin. External dependencies from Maven reposi- tories are packed in separate Library wrapper module because they can’t be used directly in Tycho compiled project as described in section 5.6. The last Eclipse plugin contains common data model of transferred data. This code is shared between Eclipse and WildFly part so it is hold separately. Figure 8.1 shows architecture of whole system as a deployment diagram. The main plugin provides an user interface for CDI Inspector, ensures extraction data about local projects, and allows to visualize and inspect data from both sources. The plugin uses e4 project constructs for structuring and window management. However it also uses Eclipse 3 elements in order to integrate with IDE components running in compatibility layer. The user interface part uses standard JFace library. Local data extraction is done by interaction with IBeanManager class. The result of both type of extractions is an object model that is suitable for JSON serialization and describes data in similar way as CDI API do. This model is later converted into a graph oriented model that is based on graph database framework TinkerPop. The

40 8. DESIGN AND IMPLEMENTATION

Figure 8.1: Deployment diagram

Figure 8.2: Inspect local project sequence diagram

graph oriented model is used for filtering as well as visualization by Zest library. Two use-cases are provided to user by the main Eclipse plugin as shown in diagram 2.1 in Analysis chapter. Both use-cases have a similar goal – to get information about CDI beans and visualize the. The key difference in data extraction is documented by sequence diagrams 8.2 (corresponding to Inspect local project use-case) and 8.3 (corresponding to Inspect remote project use-case).

41 8. DESIGN AND IMPLEMENTATION

Figure 8.3: Inspect remote project sequence diagram

8.1.1 Used technologies Selection of many used technologies naturally follows from requirements. Because of cooperation with Red Hat, relevant products of this company are used where possible. It determines usage of application server WildFly in conjunction with CDI implementation Weld as well as Eclipse IDE. For some technologies, like CDI Tools, there is probably no alternative.

Graph database There are many Java, open source graph databases that could be used in CDI Inspector. The most popular1 are probably Neo4j2 and OritentDB3. The main advantage of selected TinkerPop over mentioned databases is that the TinkerPop is actually a framework that allows to change implementation is necessary. The development of TinkerPop is also intentionally delayed compared to leading databases like in order to provide simple and stable API.

1According to my research based on number of find tutorials and related questions on http://stackoverflow.com 2http://www.neo4j.org 3http://www.orientechnologies.com/orientdb/

42 8. DESIGN AND IMPLEMENTATION

8.2 Weld extension

As mentioned is section 8.1, the Weld extension wraps one subsystem. This subsystem register a deployment processor at application server boot time. Deployment processor (represented by class CdiiDeployment- Processor4) has to perform two tasks for each deployment. To create new service with dependency on WeldBootstrapService that allows to obtains BeanManager instance. And to register an Undertow HTTP han- dler. This handler forwards all requests to deployed application except for address in form of /cdii. A request to such address is not passed to the application itself, but is processed by the han- dler. It extracts CDI related data from bean manager, serialize them and return them with “application/json” Content-Type header.

8.3 Common data model

A common model (class diagram on figure 8.4) is used as a target form both local and remote data extraction. The model is inspired by original BeanManager API. It is focused on covering basic relations among beans, types and members. They are particularly: • Bean beeing of some type. • Bean being injection into injecion point. • Bean being produced by a member. • Being a member of a type. The model is annotated using Jakckson library5 annotations allowing mapping to JSON representation. Jackson library supports object references so that the result JSON need not to contain one object multiple times in case of back references. Yet result JSON code remains simple enough to be simply parsed by other tools. Listing 20 shows an example of serialized data model.

8.4 Eclipse plugins and user interface

As mentioned in section 8.1 the Eclipse extending part of CDI Inspector consists of three plugins. Library wrapping plugin and common model

4cz.muni.fi.cdii.wildfly.deployment.CdiiDeploymentProcessor 5https://github.com/FasterXML/jackson-databind

43 8. DESIGN AND IMPLEMENTATION

Figure 8.4: Class diagram of common model

1 { 2 "@id" : 1, 3 "beans" : [ { 4 "@id" : 2, 5 "type" : { 6 "@id" : 3, 7 "package_" : "cz.muni.fi.cdii.webapp", 8 "name" : "HelloBean", 9 "typeParameters" : [ ], 10 "isArray" : false, 11 "members" : [ ] 12 },

Code listing 20: Snippet of serialized common data model

44 8. DESIGN AND IMPLEMENTATION

Figure 8.5: Package explorer context menu item

plugin holds dependencies for main CDI Inspector plugin that contain the application logic. Following text introduces CDI Inspector plugin based on provided user interface. Local project inspection can be initiate by selection Inspect CDI Beans menu item form context menu of project item in Package Explorer6 window (figure 8.5). It requires CDI support7 to be enabled for the inspected project. If not already visible, it opens CDI Inspector window containing project visualization similar to he one shown at figure 8.6. Visualization contains three types of nodes:

Bean nodes drawn in pink color. Label consists of qualifiers, scope and bean type. Bean nodes of graph of local project allow user to jump to bean implementation source code using context menu.

Type nodes drawn in violet color. Node label is a simple type name op- tionally followed by type parameters. This node is a container node. In contains nodes of class members involved in CDI. Container node can be opened or closed by clicking the triangle preceding label text.

Member nodes located in type nodes. The color is either blue or green for fields or methods, respectively. Label of field node is a simple type name followed by field name. Label of method is created sim- ilarly and parenthesis containing types of method parameters are ap- pended.

Nodes are connected by three kinds of edges as described at figure 8.7. Edges representing main type association are grey and unoriented. Ori- ented edges of red and blue color represent production and insertion as- sociation, respectively. Similarly to underlying CDI Tools model, a graph

6Package Explorer window is standard component of Eclipse Java Development Tools project. 7CDI support can be set in project Properties → Project facets tab.

45 8. DESIGN AND IMPLEMENTATION

Figure 8.6: Visualization example

Figure 8.7: Schema of visualization

visualization is able to express an error state where there are more then one assignable bean injected into one member. Visualization doesn’t graphically differentiate multiple injection points of one method. CDI Inspector window has a toolbar (figure 8.8) that allows user to (in following order): increase, decrease or reset zoom of the graph; open or close all nodes; restore original graph layout, refresh the model (reinspect currently explored project), open a dialog to enter address of running ap- plication to inspect, open CDI Details and CDI Filter windows.

Figure 8.8: CDI Inspector toolbar

46 8. DESIGN AND IMPLEMENTATION

Figure 8.9: Filter window

Figure 8.9 depicts CDI Filter window. It allows user to interactively filter the graph by specifying conditions that visible beans has to fulfill. In addition to complying bean nodes, its types, producers, and targets of injections are always visible. It is possible to filter based on bean main type, package of bean main type, Expression Language names or qualifiers. Filtering is performed continuously without confirming the form. All available information about selected node can be view in CDI details window (figure 8.10). The tree of details window can also contain buttons to navigate to related graph nodes.

Figure 8.10: Details window

47 8. DESIGN AND IMPLEMENTATION

Figure 8.11: Inspect running application dialog

Remote application inspections is initiated by clicking Inspect running application icon in CDI Inspector window. If the window is not visible, it can be opened using standard Eclipse dialog Menu → Window → Show view → Other .... The toolbar item opens a dialog (figure 8.11) for selecting of address of running application. User can either directly enter the URL of application context or select one from running Eclipse managed WildFly applications listed in the center of the dialog.

8.5 CDI compatibility

Both extraction algorithm for getting CDI related information from appli- cation server and IDE purely depends on single API – BeanManager or IBeanMangeer, respectively. Any extraction code doesn’t implement al- gorithms described in CDI specification. This should aid forward compati- bility of implemented tools. CDI Inspector was developed against WilfFly 8 supporting CDI 1.1 and JBoss Tools 4.1.1 supporting CDI 1.0. As long as the API of BeanManager and IBeanMangeer remains backward compatible, CDI Inspector should work with new versions of CDI implementations and CDI Tools.

8.6 Installation

Installation of Eclipse plugin is straightforward. After a compilation, it is sufficient to add directory 8/code/

8Project git repository is available at https://github.com/jakub-n/ CDI-inspector or it is a part of electronical attachement of this thesis.

48 8. DESIGN AND IMPLEMENTATION

eclipse-plugin/repository/target/repository to Eclipse update sites9 and install feature named CDI Inspector. To install WildFly extension, one should copy content of /code/-plugin/ cdii-extension/target/module to module sub-directory of WildFly installation. Then WildFly configuration also has to be changed. If applica- tion server is run in standard standalone configuration, relevant configura- tion file is located at standalone/configuration/standalone.xml with respect to WildFly installation directory. It has XML format. Tag /server/extensions should by extended by

1 and tag /server/profile by

1

8.7 Implementation problems

This section describes some major problems met during the implementa- tion. Some project has very austere documentation and are not developer friendly. An example can be JBoss Tools that are well documented from user point of view, but it is not intended to by used as a library. The only documentation is a short javadoc10 in code. Similarly at the beginning of CDI Inspector development the only documentation of e4 project was short in-code javadoc and some tutorials by Lars Vogel11. The Zest visualization library, even though it probably the best library for given purpose, is a little buggy. Nodes sometimes spontaneously stick together while opening or closing container nodes. It sometimes fails to draw a several connections or draw them incorrectly. Spring layout algo- rithm is nearly useless in conjunction with JFace API approach and also used Tree layout algorithm provides questionable results. The major prob- lem with Zest is that version 1.x is no longer developed and version 2.0 is still not stable, sometimes even not compilable. [45, 46] As described in section 5.6, it is quite complicated to use Maven depen- dencies in conjunction with creation of Eclipse plugin. It requires to execute at least two separate Maven runs. One for wrapping libraries from Maven

9Menu → Help → Install New Software... → Work with field. 10http://www.oracle.com/technetwork/java/javase/documentation/ javadoc-137458.html 11http://www.vogella.com/tutorials/eclipse.html

49 8. DESIGN AND IMPLEMENTATION repository to from of OSGi modules and the other to compile Eclipse plugin and bundle it with wrapped dependencies. Common data model is shared between server and IDE components. The goal was to enable sharing on level of compiled units in order to min- imize risk of incompatible versions and to avoid necessity to maintain two build configurations. The model is compiled and put into Maven repository in form package that is both Maven artifact and OSGi bundle. The package doesn’t contain its dependencies so both components, WildFly extension and Eclipse plugin, has to provide these dependencies. Tycho project works well for standard work-flows. However it lacks support for some customization that OSGi specification allows. P2 repos- itory descriptors can contain list of update update sites that can be used to download artifacts required by plugins being installed. This feature allow users an easy installation by entering just one update site. Tycho doesn’t support modification of repository descriptors, so it has to be hacked in some way. In case of CDI Inspector combination of Maven AntRun Plugin12 and XSLT13 is used. e4 project, even though it is used in Eclipse releases, is still pretty unsta- ble. For example receiving events using UIEventTopic14 stopped work- ing after upgrade from Eclipse 4.2 to 4.3. The issue was reported15 and it turned out that this issue is a consequence of change in API and it will never work again. Eclipse IDE 4.3 internally uses e4 architecture. However almost all plu- gins that make up an IDE uses Eclipse 3 API and run in compatibility layer. In order to integrate CDI Inspector with these plugins, some parts of CDI Inspector, like the definition of main window, has to use Eclipse 3 API. Debugging presents a of weak spots of Tycho integration with Eclipse. If a plugin or set of plugins is developed using standard compilation, the environment allows user to start new instance of Eclipse to debug devel- oped components by one click and in less then 15 second (on my laptop). To debug Tycho compiled set of plugins means to compile it in a standard way into form of a repository (it takes about 90 seconds), then run update procedure in testing Eclipse instance, restart this instance and attach an debugger. Thus Tycho can significantly slow down debugging.

12http://maven.apache.org/plugins/maven-antrun-plugin/ 13Extensible Stylesheet Language Transformations 14org.eclipse.e4.ui.di.UIEventTopic 15https://bugs.eclipse.org/412554

50 8. DESIGN AND IMPLEMENTATION

8.8 Possible extensions

There are number of possible extensions of CDI Inspector:

• The analysis of CDI project can by naturally extended to other bean attributes like interceptor bindings, stereotypes and others.

• The Inspector can try to allow to jump from bean nodes to bean im- plementation code even for remote projects provided the source code of such projects is opened in IDE.

• Visualized selected node can have highlighted its neighbours.

• The address suffix that is used to make JSON description available can be configurable in order to prevent clashes with addresses of de- ployed application resources.

• JSON description of applications running in server can be also made available by WildFly management interface16.

• The CDI Inspector project can provide a HTML application allow- ing inspection of running applications without dependency of Eclipse IDE.

16https://docs.jboss.org/author/display/WFLY8/Management+ Interface

51 Chapter 9 Conclusion

This thesis has following goals:

• To get familiar with CDI technology and its API.

• To get familiar with JBoss Tools project for support of CDI and its API.

• To design and implement a library that obtains selected information about running CDI application using BeanManager API and makes them available via REST protocol.

• To design and implement a component that obtains similar informa- tion about applications in form of source code.

• To design and implement a tool that creates a dynamic navigable graph based on information retrieved in previous two points.

Chapter3 deals with CDI technology and its API, features used for further implementation are described in detail. The JBoss Tools part related to CDI is described in 6.1. Description of design, implementation is described in chapter8. The result tool, CDI Inspector, consists of two components. A WildFly exten- sion that provides information about running CDI applications over HTTP protocol in JSON format. Thus, it can be used not only by created Eclipse visualizer, but also for other possible alternative visualizers. Eclipse plugin features an integration with the IDE. Besides basic re- quirements fulfillment it provides easy navigation form a visualized nodes to source code and integration with Eclipse Servers management. The tool is hosted on GitHub1 site under GNU/GPL v3 license. The page also contains links to binaries for easy installation.

1https://github.com/jakub-n/CDI-inspector

52 Bibliography

[1] DESHPANDE, Amit and REIHLE, Dirk. The Total Growth of Open Source [online]. 3. 14. 2008 [retrieved 21. 5. 2014]. Available from: .

[2] FOWLER, Martin. Inversion of Control Containers and the Dependency Injection pattern [online]. 12. 3. 2004 [retrieved 21. 5. 2014]. Available from: .

[3] Oracle and/or its affiliates. About Beans. The Java EE 7 Tutorial [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[4] KING, Gavin; MUIR, Pete. Weld - JSR-299 Reference Implementation [online]. 21. 10. 2010 [retrieved 21. 5. 2014]. Available from: .

[5] Oracle and/or its affiliates. Beans as Injectable Objects. The Java EE 7 Tutorial [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[6] Oracle and/or its affiliates. Configuring a CDI Application. The Java EE 7 Tutorial [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[7] Red Hat, Inc. Contexts and Dependency Injection for the Java EE platform [online]. 2013 [retrieved 21. 5. 2014]. Available from: .

53 9. CONCLUSION

[8] Oracle and/or its affiliates. Using Scopes. The Java EE 7 Tutorial [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[9] Oracle and/or its affiliates. Annotation Type Default. Java(TM) EE 7 Specification [online]. 2013 [retrieved 21. 5. 2014]. Available from: .

[10] Oracle and/or its affiliates. Annotation Type Any. Java(TM) EE 7 Specification APIs [online]. 2013 [retrieved 21. 5. 2014]. Available from: .

[11] Red Hat, Inc. Weld: Home [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[12] Red Hat, Inc. About · WildFly [online]. 2013 [retrieved 21. 5. 2014]. Available from: .

[13] Red Hat, Inc. Admin guide [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[14] Red Hat, Inc. Developer Guide [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[15] Red Hat, Inc. Extending WildFly 8 [online]. 2013 [retrieved 21. 5. 2014]. Available from: .

[16] Red Hat, Inc. Undertow [online]. [retrieved 21. 5. 2014]. Available from: .

[17] Red Hat, Inc. Architecture Overview [online]. [retrieved 21. 5. 2014]. Available from: .

[18] HARTINGER, Jozef. Get BeanManager instance form WildFly extension [online]. 13. 3. 2014 [retrieved 21. 5. 2014]. Available from: .

54 9. CONCLUSION

[19] VOGEL, Lars. Eclipse 4 Application Development: The complete guide to Eclipse 4 RCP development. 2012. ISBN 13: 978-3943747034.

[20] The Eclipse Foundation. Eclipse Project [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[21] OSGi™ Alliance. The OSGi Architecture [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[22] The Eclipse Foundation. Equinox [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[23] The Eclipse Foundation. e4 Project [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[24] Eclipse 4 (e4) Tutorial Part 4- Dependency Injection Basics [online]. 14. 8. 2013 [retrieved 21. 5. 2014]. Available from: .

[25] The Eclipse Foundation. PDE [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[26] The Eclipse Foundation. Eclipse Java development tools (JDT) [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[27] The Eclipse Foundation. Web Tools Platform (WTP) Project [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[28] The Eclipse Foundation. Zest [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[29] The Eclipse Foundation. Draw2d [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[30] Red Hat, Inc. JBoss Tools - Frequently Asked Questions [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

55 9. CONCLUSION

[31] JBoss by Red Hat. CDI Tools Reference Guide [online]. 2012 [retrieved 21. 5. 2014]. Available from: .

[32] Red Hat, Inc. JBoss Tools - Server tooling [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

[33] TinkerPop. TinkerPop [online]. 2013 [retrieved 21. 5. 2014]. Available from: .

[34] HORNE, Christopher. Glossary of Big Data Terminology [online]. 5. 8. 2013 [retrieved 21. 5. 2014]. Available from: .

[35] NEUBAUER, Peter. Graph Databases, NOSQL and Neo4j [online]. 12. 5. 2010 [retrieved 21. 5. 2014]. Available from: .

[36] RODRIGUEZ, Marko A. Blueprints [online]. 14. 4. 2014 [retrieved 21. 5. 2014]. Available from: .

[37] Mallette, Stephen. Furnace [online]. 16. 4. 2013 [retrieved 21. 5. 2014]. Available from: .

[38] Mallette, Stephen. Rexster [online]. 25. 4. 2014 [retrieved 21. 5. 2014]. Available from: .

[39] Mallette, Stephen. TinkerGraph [online]. 26. 6. 2013 [retrieved 21. 5. 2014]. Available from: .

[40] RODRIGUEZ, Marko A. Property Graph Model [online]. 12. 6. 2012 [retrieved 21. 5. 2014]. Available from: .

[41] RODRIGUEZ, Marko A. Graph Morphisms [online]. 12. 6. 2012 [retrieved 21. 5. 2014]. Available from: .

56 9. CONCLUSION

[42] RODRIGUEZ, Marko A. Pipes [online]. 14. 4. 2014 [retrieved 21. 5. 2014]. Available from: .

[43] RODRIGUEZ, Marko A. Gremlin [online]. 14. 4. 2014 [retrieved 21. 5. 2014]. Available from: .

[44] RODRIGUEZ, Marko A. Frames [online]. 14. 4. 2012 [retrieved 21. 5. 2014]. Available from: .

[45] The Eclipse Foundation. Graphical Editor Framework (GEF) project repository (zest) [online]. 2012 [retrieved 21. 5. 2014]. Available from: .

[46] The Eclipse Foundation. Graphical Editing Framework (GEF) project repository (gef4) [online]. 2014 [retrieved 21. 5. 2014]. Available from: .

57 Appendix A Content of electronic attachment

An electronic attachment of this thesis hat following structure:

source-code Complete code base of all created projects.

binaries Binaries for installation.

eclipse-p2-repository Directory contains a p2 repository of CDI Inspector. wildfly-extension Directory contains a WildFly extension.

58