+ All Categories
Home > Documents > Skyway Builder 6.3 Recipes

Skyway Builder 6.3 Recipes

Date post: 03-Feb-2022
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
113
Skyway Builder 6.3 Recipes 6.3.0.0 - 10/23/09 Skyway Software
Transcript

Skyway Builder 6.3 Recipes

6.3.0.0 - 10/23/09

Skyway Software

Skyway Builder Recipes: 6.3.0.0 - 10/23/09Skyway Software

PublishedCopyright © 2009 Skyway Software

Abstract

The most recent version of all Skyway Builder documentation can be found online at www.skywayperspectives.org2.

2 http://www.skywayperspectives.org

iv

Table of Contents1. Spring Generation ........................................................................................................... 1

1. Generating Spring applications using meta-data programming and code generation ............. 12. Web Layer Recipes .......................................................................................................... 5

1. Creating the Controller using Spring MVC .................................................................... 52. Creating the Controller using Spring Web Flow ............................................................. 73. Creating the Model for Spring MVC .......................................................................... 104. Creating the Model for Spring Web Flow ................................................................... 145. Creating Model Packages ........................................................................................ 166. Creating Spring Components .................................................................................... 167. Creating the View for Spring MVC ............................................................................ 178. Scaffolding a Spring MVC application from domain object ............................................. 189. Scaffolding Spring Security ...................................................................................... 1910. Mapping URLs to Operations and Views ................................................................... 2011. Creating Helper Methods using Operations ............................................................... 2312. Reusing Operations in Different Contexts ................................................................. 2313. Hiding the Implementation Technology .................................................................... 2414. Implementing Post/Redirect/Get (PRG) Pattern .......................................................... 2515. Restricting Direct Access to JSP Pages ...................................................................... 2616. Implementing Controller Methods using Actions and Steps .......................................... 2717. Blending Actions with non-generated Java Code ........................................................ 3118. Blending Actions with non-generated Spring Beans .................................................... 3419. Implementing an HTML Form in JSP using standard HTML elements .............................. 3620. Implementing an HTML Form in JSP using Spring Form Tag Library ................................ 3821. Implementing an HTML Form in JSP using Skyway Tag Library ....................................... 4022. Using Third-Party Tag Libraries ............................................................................... 4223. Accessing Request and Session Parameters ............................................................... 4324. Defining the Scope of Components, Controllers and Services ........................................ 4425. Managing User Session Data .................................................................................. 4526. Responding to User-Generated Events (Events and Commands) .................................... 4527. Using Absolute Paths for Images, CSS and Javascript ................................................... 4928. Using CSS ........................................................................................................... 5029. Using Javascript ................................................................................................... 5130. Securing Applications - Authentication ..................................................................... 5231. Securing Applications - Authorization ....................................................................... 5532. Validating End-User Input on Server using Spring Validator .......................................... 5533. Implementing Client-side Validation using Javascript ................................................... 5934. Implementing File Upload for Spring MVC ................................................................ 6035. Implementing File Upload for Spring Web Flow ......................................................... 6336. Streaming binary content ...................................................................................... 64

3. Service Layer Recipes ..................................................................................................... 671. Creating a Service or Business Facade ....................................................................... 672. Creating an Operation ............................................................................................ 673. Implementing an Operation using Actions and Steps .................................................... 694. Creating a Contract-First JAX-WS Web service (SOAP) ................................................... 705. Publishing a JAX-WS Web service (SOAP) ................................................................... 716. Publishing a AJAX service using DWR ........................................................................ 727. Consuming a SOAP Web service ............................................................................... 748. Consuming a REST Web Service ............................................................................... 759. Using Java Code, Spring Beans and Groovy with Services .............................................. 7610. Using Groovy in Actions ........................................................................................ 7711. Accessing Data using Groovy .................................................................................. 78

Skyway Builder 6.3 Recipes

v

4. Data Layer Recipes ......................................................................................................... 801. Creating a Domain Object / POJO / JavaBean .............................................................. 802. Creating a Domain Model ....................................................................................... 823. Defining relationships ............................................................................................. 834. Creating a Data Access Object (DAO) ......................................................................... 855. Table and Field Mapping ......................................................................................... 866. Relationship Mapping ............................................................................................. 877. Implementing DAO using JPA ................................................................................... 888. Generating Domain Model from an existing database ................................................... 899. Performing Basic CRUD Operations ........................................................................... 8910. Performing Complex Queries using JPQL .................................................................. 9111. Deciding between Defined versus Derived Data Models .............................................. 9212. Working with Related Data .................................................................................... 9313. Migrating to a Different DBMS ............................................................................... 93

5. Project Recipes ............................................................................................................. 951. Creating Project-level Variables and Constants ............................................................ 952. Changing JPA Providers ........................................................................................... 953. Changing JTA Providers ........................................................................................... 964. JSP Aliases ............................................................................................................ 965. Adding Spring Contexts ........................................................................................... 976. Creating Eclipse-based Skyway Projects ..................................................................... 987. Creating Maven-based Skyway Projects ..................................................................... 998. Setup an Eclipse Dynamic Web Project for Skyway Builder ........................................... 1009. Manage project classpath dependencies manually ..................................................... 101

6. Customizing Code Generation Recipes ............................................................................. 1021. Customizing Code Generation Configuration ............................................................. 1022. Customizing Code Generation Templates .................................................................. 1033. Extending the Code Generation Framework .............................................................. 104

vi

List of Figures1.1. Spring DSL Model ......................................................................................................... 22.1. Model - View - Controller ............................................................................................... 52.2. Controller (MVC) .......................................................................................................... 62.3. Controller (MVC) .......................................................................................................... 92.4. Spring Web Flow - Sample Diagram ................................................................................ 102.5. Model (MVC) .............................................................................................................. 112.6. Spring MVC Model (Example 1) - Operation Inputs/Outputs ................................................ 122.7. Spring MVC Model (Example 2) - Operation Inputs/Outputs ................................................ 132.8. Model (MVC) .............................................................................................................. 152.9. Spring Web Flow Model (Example 1) - Model Config .......................................................... 152.10. View (MVC) .............................................................................................................. 172.11. Action Editor ............................................................................................................ 282.12. Step Palette .............................................................................................................. 292.13. Creating an instance of MyJavaClass using Variables ........................................................ 332.14. Web Events and Commands ........................................................................................ 462.15. Events and Commands - Properties Panel ...................................................................... 472.16. Events and Commands - 1 Event .................................................................................. 482.17. Events and Commands - 2 Events ................................................................................. 482.18. Security Settings using Spring Security .......................................................................... 532.19. Security Settings - Configured Views ............................................................................. 542.20. Security Settings - Security Information Source ............................................................... 542.21. Validation ................................................................................................................. 582.22. Event and Commands ................................................................................................ 593.1. DWR Service - Index Page ............................................................................................. 733.2. DWR Service - Service Details Page ................................................................................ 743.3. Accessing Variables using Groovy ................................................................................... 784.1. Creating a domain object using Domain Object Editor ........................................................ 814.2. Book domain object with relationship to Authors .............................................................. 844.3. Author domain object with reverse relationship to Book .................................................... 854.4. Persistence Mapping .................................................................................................... 874.5. Relationship Mapping .................................................................................................. 884.6. CRUD - Modify Data Access Object Examples ................................................................... 905.1. JSP Alias .................................................................................................................... 975.2. Adding Spring Contexts to Project .................................................................................. 98

vii

List of Tables1.1. Spring/Java, Spring DSL, and UML Stereotype Cross Reference .............................................. 32.1. URL Mapping Parameters ............................................................................................. 212.2. Binding HTML Form Controls ......................................................................................... 372.3. Event Descriptions ....................................................................................................... 462.4. Skyway Commands ...................................................................................................... 462.5. File Upload Suffixes ..................................................................................................... 612.6. URL parameters for streamedBinaryContentView .............................................................. 653.1. Web Service WSDL to Skyway Mappings ......................................................................... 704.1. Skyway Basic Data Types .............................................................................................. 804.2. Relationship Types ....................................................................................................... 834.3. JPA Query Examples .................................................................................................... 924.4. Comparison of Native and External Data Models .............................................................. 924.5. Scenarios for using external data models ......................................................................... 93

viii

List of Examples2.1. Annotated Spring Controller (Generated) .......................................................................... 72.2. Spring MVC Model (Example 1) - Operation Inputs/Outputs (Generated) ............................... 132.3. Spring MVC Model (Example 2) - Operation Inputs/Outputs (Generated) ............................... 142.4. URL Mapping - Examples .............................................................................................. 222.5. URL Mapping - Reusing Actions ..................................................................................... 242.6. URL Mapping - Hiding Implementation Technology ............................................................ 252.7. URL Mapping - Post/Redirect/Get (PRG) .......................................................................... 262.8. Action (Generated) ...................................................................................................... 302.9. Blending Java Code with Actions - MyJavaClass.java .......................................................... 322.10. Invoke Java Step - Variable Invocation (Generated Code) ................................................... 332.11. Invoke Java Step - Instance Invocation (Generated Code) .................................................. 332.12. Invoke Java Step - Static Invocation (Generated Code) ...................................................... 342.13. Blending Spring Beans with Actions - MyBean.java .......................................................... 352.14. Spring Context File - mycontext.xml .............................................................................. 352.15. Invoke Spring Step - Static Invocation (Generated Code) ................................................... 362.16. Invoke Spring Step - Dynamic Invocation (Generated Code) ............................................... 362.17. HTML Form using Standard HTML Controls .................................................................... 372.18. JSP Directive for using Spring Form Tag Library ............................................................... 382.19. HTML Form using Spring Form Tag Library ..................................................................... 392.20. HTML Form using <spring:bind> tag .............................................................................. 392.21. JSP Directive to include Skyway JSP Tag Library ............................................................... 402.22. HTML Form using Skyway Builder Tag Library ................................................................. 422.23. JSP Directive for using Third-Party Tag Library ................................................................. 432.24. Using Third-Party Tags ................................................................................................ 432.25. Invoke Java (inline) - accessing Request Parameters ......................................................... 442.26. Model Scope (Generated) ........................................................................................... 442.27. JSP Directive for using Skyway Tab Library ...................................................................... 462.28. Event and Command - JSP Fragment ............................................................................. 482.29. JSP Fragment using pageContext.request.contextPath variable for absolute pathing ............... 492.30. HTML fragment with absolute pathing - deployed to http://localhost/myapp ........................ 492.31. HTML fragment with absolute pathing - deployed to http://www.myapp.com ....................... 502.32. Linking to external CSS files ......................................................................................... 512.33. Inline javascript ......................................................................................................... 512.34. Linking to javascript libraries ....................................................................................... 522.35. Validation Class ......................................................................................................... 572.36. Using errors tag of the Spring Form Tag Library (edit.jsp) .................................................. 582.37. Sample client-side validation using javascript .................................................................. 592.38. File Upload - HTML .................................................................................................... 612.39. File Upload - Upload Web Control (Skyway TagLib) .......................................................... 622.40. File Upload - HTML .................................................................................................... 632.41. Spring Web Flow Configuration .................................................................................... 642.42. Accessing MultipartFile ............................................................................................... 642.43. Spring Context file - projectName-generated-web-context.xml ........................................... 652.44. Image Streaming Example - output only ........................................................................ 652.45. Image Streaming Example - with inputs ......................................................................... 662.46. Document Streaming Example - with inputs ................................................................... 663.1. Sample java code invoking REST services ......................................................................... 763.2. Sample Groovy code invoking REST services ..................................................................... 763.3. Using Groovy Code using Invoke Groovy Step ................................................................... 773.4. Accessing data using Groovy ......................................................................................... 794.1. Domain Object - POJO (Generated) ................................................................................ 82

Skyway Builder 6.3 Recipes

ix

4.2. Domain Object - Primary Key Class (Generated) ................................................................ 824.3. Code generated for domain object relationships ............................................................... 85

1

Chapter 1. Spring Generation

1. Generating Spring applications using meta-dataprogramming and code generation

PROBLEM

The Spring Framework is one of the most popular JAVA frameworks. While the Spring Framework andassociated Spring technologes reduce complexity, developing Spring applications requires familiarity withSpring development concepts and configuration.

SOLUTION

The solution is to provide an abstraction layer on top of Spring that generates Spring-based artifactsand configuration files, and additionaly use modelling to implement parts of your solution. SkywayBuilder is an Eclipse-based, code generation tool for accelerating the development of Spring applications,specifically Rich Internet Applications (RIAs) and Web Services. Spring provides a framework that abstractsthe complexities of enterprise software, and Skyway Builder adds an even higher layer of abstraction (aSpring DSL) to provide a generation framework for Spring.

HOW IT WORKS

The abstraction is accomplished by employing a metadata model to capture the specifications fromthe developer, which in turn drives the code generation process. For defining the specifications,Skyway Builder provides Eclipse-based tooling which includes the use of editors, wizards, and modelingartifacts. The Skyway Generation Framework then converts the metadata into generated code and Springapplication artifacts.

Skyway Builder implements a DSL for Spring that describes all the major components of a Springapplication. This is the metadata model:

Spring Generation

2

Figure 1.1. Spring DSL Model

Application development using Skyway Builder is accomplished by using (assembling and configuring)Spring DSL artifacts:

Within Skyway Builder, there are graphical (and abstract) representations of application components.These components have direct correlations to Java, Spring, JPA, and JEE artifacts.

Summary of Spring DSL Artifacts

• Projects are the top level artifact within the developer's workspace. All other Spring DSL artifacts mustbe made within a Skyway modeling project.

• A Model Package is a Spring DSL artifact for namespacing and grouping related Spring DSL components.A model package can contain any top-level Spring DSL elements, including other model packages.Model packages correlate directly to java packages (and UML packages), and Spring DSL artifactscreated in a model package will be generated into a matching Java package.

• A Domain Object is a Spring DSL artifact that defines the domain model of the application. By defaulta domain object is generated into a plain old java object (POJO). If a domain object is associated witha data access object, then the domain object is annotated as an @Entity (JPA) annotated class, andit's associated with a primary key class (@IdClass). Fields can be added to domain objects by using thebasic data types, and a domain object can have relationships to other domain objects.

• A Data Access Object (DAO) is a Spring DSL artifact used to separate data access logic from applicationlogic. A DAO manages the persistence of domain objects, and it is generated into @Repositoryannotated Spring components, a specialized stereotype for data access layer components. A DAO canalso contain predefined queries called Named Queries.

• A Named Query is a Spring DSL artifact creating predefined queries for the data access objects (DAOs).Named queries are defined using either SQL or JPQL (Java Persistence Query Language), and Named

Spring Generation

3

Queries are generated into @NamedQueries and @NamedQuery annotations in Spring @Repositorycomponents.

• A Service is a Spring DSL artifact that defines a service layer component, and it gets generated intoa @Service annotated Spring component, a specialized stereotype for service layer components. AService contains a set of Operations which are generated into Service methods.

• A Web Controller is a Spring DSL artifact that defines the web layer of an application using SpringMVC. Web Controllers get generated into a @Controller annotated Spring component, a specializedstereotype for web layer components. A Web Controller contains a set of Operations which aregenerated into methods for handling web requests.

• An Operation is a Spring DSL artifact that defines methods for both Services and Controllers. Operationsrepresent application logic, and they use inputs and outputs for exchanging data. Operations aregenerated directly in the respective Service and Controller classes, and they are generated slightlydifferently to account for the different implementations needed for the Spring stereotypes.

• An Actions is a Spring DSL artifact for implementing operations using model-driven development.They are used to implement service and controller operations in Java using drag-n-drop steps that aresequenced together into functionality.

• A Component is a Spring DSL artifact that defines a generic container for data. A componentgets generated into an @Component annotated Spring component, a generic stereotype for Springmanaged components with configurable scope. Components are typically used as data transfer objects(DTO) and form backing objects.

• A Flow is used to implement the web layer of an application using Spring Web Flow.

• Java Server Pages (JSP) are used to implement the Presentation layer of an applicaiton. JSPs are usedfor both Spring MVC and Spring Web Flow applications.

• An Exception is a Spring DSL artifact that defines custom exceptions. Exceptions are generated intoexception classes in Java.

The follow table shows the relationship between the Spring UML stereotypes, Spring DSL, Spring/JPAcomponents.

Table 1.1. Spring/Java, Spring DSL, and UML Stereotype Cross Reference

Web Layer Service Layer Data Layer

Spring Stereotypes,Annotations andInterfaces

@Controller

@Component

@RequestMapping

@RequestParm

@ModelAttribute

Spring Validation

@Service

@Transactional

@Repository

Java Annotations andInterfaces

@WebService (JAX-WS) @Entity (JPA)

Spring Generation

4

Web Layer Service Layer Data Layer

@WebMethod (JAX-WS)

@WebParm (JAX-WS)

Direct Web Remoting -DWR

Exceptions

@Id / @IdClass (JPA)

@NamedQueries (JPA)

@NamedQuery (JPA)

@XMLType (JAXB)

@XMLElement (JAXB)

Spring DSL Web Controller

Component

URL Mapping

Service

Exception

Domain Object

Data Access Object

Named Query

UML Stereotype forSpring

<<WebController>>

<<Component>>

<<RequestMapping>>

<<ModelAttribute>>

<<Validator>>

<<BusinessService>>

<<TransactionalOperation>>

<<Exception>>

<<DomainObject>>

<<Id>>

<<DataAccessObject>>

<<NamedQuery>>

5

Chapter 2. Web Layer Recipes

The web layer is also referred to as the UI layer. The web layer is primarily concerned with presentingthe user interface and the behavior of the application (handling user interactions/events). While the weblayer can also contain logic, core application logic is usually located in the services layer.

Figure 2.1. Model - View - Controller

The Spring DSL artifacts for implementing the web layer of a Spring MVC application are the Controller,Operation, Component, Action, Steps and JSP pages. The Spring DSL artifacts for implementing the weblayer of a Spring Web Flow application are the Flows and JSP pages. These artifacts will be described indetail in a following chapter.

1. Creating the Controller using Spring MVCPROBLEM

In the context of a Spring MVC application, the controller is responsible for receiving requests from aweb client (typically from end-user generated events) and invoking a request handler called an Operation,which orchestrates all the server logic necessary for processing the request. Spring MVC supports thegrouping of Operations related to an application task into a Controller. In order to gain the benefits ofSpring MVC, a developer needs to have a pretty in-depth knowledge of Spring MVC. Creating a SpringController is tedious, and identifying the relationship between Spring Controllers, Model and Views isdifficult because there's no easy way to identify them without digging through source code or codeconfiguration files.

SOLUTION

The Spring DSL lets you define your controllers using meta-data. To create a controller a developermust only define a controller and provide it a common name, and Skyway Builder will generate all thesupporting code and Spring configurations needed. Every operation that is added to the controller willresult in a handler method being generated into the Spring controller.

Web Layer Recipes

6

HOW IT WORKS

Controllers are used along with the Operations, Models and Views to implement an application usingSpring MVC. The Web Controller has essentially two functions: group related Operations and map URLsto Operations, which orchestrate the task and support the user events associated with the task.

Figure 2.2. Controller (MVC)

Steps for creating a Controller:

1. Right click the on a Model Package, and select New-->Controller

2. From the New Controller Wizard, enter a common name for the controller. The common name is forreferencing the controller from other artifacts. Click Finish

The following figures shows an abbreviated version of the code that is generated from a Controller artifact.To see the fully generated code, see the PAM tutorial.

Web Layer Recipes

7

Example 2.1. Annotated Spring Controller (Generated)

package com.pam.web;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.InitBinder;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;import org.springframework.web.servlet.ModelAndView;

// Imports for Spring framework classes, including annotation, stereotypes, binding, // validation, and transation etc......full list omitted for brevity

// Imports statements for generated classes from referenced data types, services, and DAOs...full list omitted for brevity

/** * Request dispatcher for the <code>AppraisalEntryController</code> controller. * * @generated */@Scope("singleton")@Controller("AppraisalEntryController")@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, noRollbackForClassName = "java.lang.Exception", rollbackForClassName = "org.skyway.execution.exception.RollbackException")public class BlogController {

/** * Wire in the project level variables that can span both controllers and services. * * @generated */ @Resource(name = "SkywayBlog") private SkywayBlog project;

// Annotation-based code to wire in ModelAttributes ...

// Controller Variables, including Getters and Setters ...

// Initialize Bindings ...

// Request Mapping Logic ...

}

RELATED RECIPES

1. Creating the Model for Spring MVC

2. Creating the View for Spring MVC

3. Mapping URLs to Operations and Views

2. Creating the Controller using Spring Web FlowPROBLEM

Web Layer Recipes

8

An alternative to Spring MVC is Spring Web Flow, a project from Spring for simplifying the developmentof web applications. While Spring Web Flow is compatible with Spring MVC, Spring Web Flow uses flowsinstead of controllers for implementing the web layer of an application. Since Spring Web Flow hasfunctionality for managing application state, it is best suited for implementing the functionality wherethe activity being performed by the end-user spans multiple page requests.

For example, an online commerce application typically has checkout functionality which spans multiplepages. One page may require that you confirm the items in your order, with the option to add/removeitems and change quantities. The next page may solicit shipping information, including picking shippingoptions and providing a shipping address. The next page is used for entering billing info. The bottom lineis that the checkout process is a unit of work, and there are many intermediate steps to complete thecheckout process.

With Spring Web Flow the group of related steps to accomplish a task are referred to as a Flow. Whilethis functionality can be implemented with Spring MVC, Spring Web Flow has features that make itconsiderably easier. However in order to gain the benefits of Spring Web Flow, a developer needs tohave a pretty in-depth knowledge of Spring and Spring Web Flow, and Spring Web Flow adds additionalconfiguration requirements to your web application. While authoring the flow of an application usingXML is elegant, implementing flows using XML can be difficult and tedious because it’s hard to visualizethe application flow from the xml.

SOLUTION

Skyway Builder reduces the complexity of adding Spring Web Flow support by automaticallybootstrapping the project for you. The moment you add the first flow to your project, Skyway Builder willadd the necessary Spring configuration and libraries. That by itself is a significant time saver, but SkywayBuilder goes one step further in regards to Spring Web Flow

In addition to configuring your application, Skyway builder also provides a custom Spring Web Flow editorfor authoring flows. The flow editor is very similar to Skyway Builder’s action editor, except that youimplement flows instead of operations.

You start with an empty canvas which represents a single flow, and you drop different web flow states(i.e. view, decision, action, subflow and stop) onto the canvas. State transitions are defined by drawinglines between the states and specifying the event associated with the transition. Actions can be addedto flows and states.

HOW IT WORKS

Flows are a group of related steps for accomplishing a task in an application. Some of the benefits ofusing Spring Web Flow are

1. XML-based flow definitions - The flow of the application is defined in XML. No custom Java is neededto implement a flow

2. Expression language support - An expression language let’s you leverage logic from the other layersof the web application. Logic that a developer would typically put into a controller, that isn’t handledby Spring Web Flow, can beexpressed in XML using the expression language

3. State management - Variables can be scoped (many scopes are supported), and Spring Web Flow willautomatically handle the cleanup of those variables when they are out-of-scope.

4. Modularization of flow logic - Flows can be re-used from other flows.

A Flow is responsible for orchestrating the task (steps) and supporting the user events associatedwith the task. Instead of the MVC-based approach of creating a controller and multiple operations for

Web Layer Recipes

9

implementing a conversation, with Spring Web Flow you define a flow with states and expressions. Insteadof the MVC-based approach of defining URL mappings, with Spring Web Flow you define events. SpringWeb Flow also let's you easily separate your logic for handling a user event (on event id) from the pre-load logic (on entry) for a particular state.

Figure 2.3. Controller (MVC)

Steps for creating a Flow:

1. Right click the on a Model Package, and select New-->Flow

2. From the New Web Flow Wizard, enter a common name for the flow. The common name is forreferencing the controller from other artifacts. Click Next

3. From the Create Webflow Domain Model panel, specify the name and location of the domain model.As you make changes to the web flow diagram, the flow domain model will be updated with Spring WebFlow specific content. The domain model is what's deployed with your application and interprettedby the Spring Web Flow framework. The domain model must be located in a folder withing WEB-INF.Click Finish.

4. Implement the flow using the flow diagram,

The following figures shows a sample flow diagram.

Web Layer Recipes

10

Figure 2.4. Spring Web Flow - Sample Diagram

RELATED RECIPES

1. Creating the Controller using Spring Web Flow

2. Creating the Model for Spring Web Flow

3. Creating the View for Spring MVC

3. Creating the Model for Spring MVCPROBLEM

In the context of Spring MVC, a model generally represents the data that will be passed to and from anoperation (defined in a web controller) and the view. Spring MVC supports various options and patternsfor defining the data that can be passed back and forth, and a typical Spring MVC application may usea combination of these options. The flexibility of Spring MVC to have fine-grained control for definingmodels is very powerfull, however along with the flexibility comes considerable variability and complexityin the implemenation using Spring.

SOLUTION

Through the use of code generation in Skyway Builder, the complexity of Spring models can be abstractedto makes things simpler for the developer.

A controller method in Spring can support zero-to-many input parameters, and the principal mechanismsin Spring for specifying input parameters are the @RequestParam and the @ModelAttribute annotations.The @RequestParam annotation is used to bind individual request parameters, like string and integers, tomethod parameters in the controller. The @ModelAttribute annotation is used to bind complex objects,like domain objects, data transfer objects and/or form backing objects, to method parameters in acontroller.

In Skyway Builder operations are used to define request handlers (controller methods), and operationparameters are simply configured using Input variables. Since these variables are available to beprocessed by the operation, the developer using Skyway Builder doesn't really need to be concerned withthe details of Spring.

Web Layer Recipes

11

Nevertheless here's an overview of what gets generated for input variables added to an operation::

• the input variable is emitted as a annotated method parameter

• the annotaton is determined by the variable type

• primitive variables will be annotated with @RequestParam

• complex variables will be annotated with @ModelAttribute

• the annotation name is derived from the variable name

A controller method in Spring can also output model data, and the principal mechanism in Spring forspecifying output model data is the ModelAndView object. In the event that there isn't any data to bereturned by the method, the controller method can simply return a String that represents the view thatshould be rendered. If the controller method does return data, then a ModalAndView object needs to beinstantiated and each output variable is added as a model attribute to the ModelAndView object.

In Skyway Builder you simply need to define output parameters on the Operation, and Skyway Builderwill handle all the details regarding how the model data should be emitted.

Here's an overview of what occurs regarding output variables added to an operation:

• If you don't have any output variables, the method return type will be String, and the last line of theoperation will return the corresponding view that should be rendered (as defined in URL mappings).

• If you have one or more output variables, the method will return a ModelAndView object, andeach output variable will added to the ModelView. The output variable name will be used as theModelAttribute name, and the ModalAndView will be set with the view that should rendered (asdefined in URL mappings).

HOW IT WORKS

Once again a model generally refers to the data that is pased to and from a controller method (SkywayOperation).

Figure 2.5. Model (MVC)

Web Layer Recipes

12

Controller methods parameters are defined using Operation Input and Variables.

Steps for defining operation input and output variables:

1. From the Skyway Navigator, double-click on the Operation to configure, and switch to the Inputs/Outputs tab.

2. Add input variables by clicking on the Add... button in the Inputs block, and specify the output variablename. Assign (assignment) the variable name to either an input variable or operation variable. Thetype and collection parameters will be automatically configured based on the selected assignmentvariable.

Let's examine a few scenarios to see exactly what gets generated based on the configuration of theoperation inputs and outputs.

Example 1

In this first example, an operation was defined with two input variables and no output variables.

Figure 2.6. Spring MVC Model (Example 1) - Operation Inputs/Outputs

The following figures shows an abbreviated version of the full controlller method that is generated fromthe operation configuration.

Web Layer Recipes

13

Example 2.2. Spring MVC Model (Example 1) - Operation Inputs/Outputs (Generated)

@RequestMapping(value = "/OrderCheckoutController/AddBillingAddress.action")

public String addBillingAddress(@RequestParam("orderId") String orderId ,

@ModelAttribute("billingAddress") Address billingAddress ) throws java.lang.Exception {

//method implementation either hand-coded or generated from action model

return "/billingoverview.jsp";}

The operation didn't have any defined output variables. Therefore the return type for the controllermethod is String.The orderId input variable is of type Text. Since Text is a primitive data type, the method parametercorresponding to this variable is annotated with the @RequestParam annotation. The variablename (orderID) is used as the name.The billingAddress input variable is of type Address. Since Address is a complex type, the methodparameter corresponding to this variable is annotated with the @ModelAttribute annotation. Thevariable name (billingAddress) is used as the name.The output of the controller method is set to the path of the view that should be used for renderingthe results.

Example 2

In this second example, an operation was defined with one input variable and an output variable. Theoutput variable is mapped to an operation variable (shippingOptions) that is defined in the Variables tab(not shown).

Figure 2.7. Spring MVC Model (Example 2) - Operation Inputs/Outputs

The following figures shows an abbreviated version of the full controlller method that is generated fromthe operation configuration.

Web Layer Recipes

14

Example 2.3. Spring MVC Model (Example 2) - Operation Inputs/Outputs (Generated)@RequestMapping(value = "/OrderCheckoutController/LoadShippingOptions.action")

public ModelAndView loadShippingOptions(@RequestParam("zipcode") String zipcode ) throws java.lang.Exception {

ModelAndView mav = new ModelAndView(); Set<ShippingOption> shippingOptions = null;

//method implementation either hand-coded or generated from action model

mav.addObject("shipoptions", shippingOptions);

mav.setViewName("/success.jsp"); return mav;}

The operation has atleast one output variable. Therefore the return type for the controller methodis ModelAndView.The zipcode input variable is of type Text. Since Text is a primitive data type, the method parametercorresponding to this variable is annotated with the @RequestParam annotation. The variablename (zipcode) is used as the name.Since the return type of the controller method is a ModelAndView object, a ModelAndView objectis instantiated.The operation output variables are added to the ModelAndView object. The variable name is usedas the model attribute name, and the object (shippingOptions) that was assigned to the output isused as the model.The view is set on the ModelAndView object to the path of the view that should be used forrendering the results.

Data Transfer Objects vs. Form Backing Objects vs. Domain Objects

In MVC the model is the contract between the View and the Controller. While you can use basicdata types, more often than not you'll want to use complex objects for the model. There are severaloptions available to the developer. You can use your domain objects for the model, but this onlyworks if there's a very close correlation between your domain object and your views. If that's notthe case, then you can create a data transfer object that is not tied to your domain model, andthe request handlers in the controller would be responsible for mapping data between the datatransfer object and the domain model. A data transfer object is a general term for a data objectthat isn't part of the domain model and isn't intended to be persisted. A form backing object isa specific reference to data object that is used to capture input from an end-user, and it can beimplemented using a domain object or a data transfer object.

You can create domain objects and data transfer objects in the Spring DSL using Domain Objectsand Component artifacts, respectively. If you prefer, you can also use a custom Java class.

RELATED RECIPES

1. Creating a Controller for Spring MVC

2. Creating the View for Spring MVC

4. Creating the Model for Spring Web FlowPROBLEM

In the context of Spring Web Flow, a model serves the same function as a model in Spring MVC. The modelgenerally represents the data that will be passed to and from a View State (instead of an Operation) andthe view. Spring Web Flow supports various options and patterns for defining the data that can be passed

Web Layer Recipes

15

back and forth, and a typical Spring Web Flow application may use a combination of these options. Theflexibility of Spring Web Flow to have fine-grained control for defining models is very powerfull, howeverthe definition of the models can be difficult because the models are defined and used in xml (flow).

SOLUTION

Through the use of the Skyway Web Flow editor, defining models is much simpler because the flow isrepresented in a diagram. This is very effective for defining models and to understand the use of modelsin a Spring web Flow implementation.

HOW IT WORKS

Once again a model generally refers to the data that is pased to and from a web flow View State.

Figure 2.8. Model (MVC)

Steps for defining a Model for a Spring Web Flow view state:

1. In a flow diagram, identify a View State for configuring a model.

2. For the model parameter, specify the variable that should be used for the model. The model will be thecommandObject that can be used in the JSP to display data to and/or solicit data from the end-user.

Figure 2.9. Spring Web Flow Model (Example 1) - Model Config

RELATED RECIPES

Web Layer Recipes

16

1. Creating the Controller using Spring Web Flow

2. Creating the View for Spring MVC

5. Creating Model PackagesPROBLEM

In Java application development it is common to use packages for organizing and namespacing Javaresources according to their functionality. The Spring DSL abstracts the development of many differenttypes of Java resources, but there still needs to be a mechanism for the developer to group related SpringDSL artifacts. Furthermore the developer often wants to control the package names that are ultimatelyemitted in the generated code.

SOLUTION

A Model Package is a Spring DSL artifact for namespacing and grouping related Spring DSL components.A model package can contain any top-level Spring DSL elements, including other model packages. Modelpackages correlate directly to java packages (and UML packages), and Spring DSL artifacts created in amodel package will be generated into a matching Java package.

HOW IT WORKS

Steps for creating a Model Package:

1. Right-click on the Spring DSL folder of a Skyway Project, and select New --> Model Package

2. For the New Model Package window, specify the name of the model package. The name can be partiallyfilled-in by selecting a pre-existing model package in the project.

6. Creating Spring ComponentsPROBLEM

In the course of developing web applications there is often a need to create data objects that aren't apart of the domain model. The data objects are referred to as data transfer objects (DTO), and they canbe used throughout the application for passing data. When there isn't a close correlation between thedomain objects and the views of the application, DTOs can be used for creating form backing objects.

SOLUTION

A Component is a Spring DSL artifact that defines a generic container for data. A component getsgenerated into an @Component annotated Spring component, a generic stereotype for Spring managedcomponents with configurable scope. Components are typically used as data transfer objects (DTO) andform backing objects.

HOW IT WORKS

Steps for creating a Component:

1. Right click the on a Model Package, and select New-->Component

2. From the New Component Wizard, enter a common name for the component. The common name isfor referencing the component from other artifacts. Click Finish

Web Layer Recipes

17

7. Creating the View for Spring MVCPROBLEM

In the context of Spring MVC, a view generates the user interface based on model data. There a varietyof JAVA-based technologies for implementing views, but Java ServerPages (JSP) are the predominanttechnology for defining Views. JSPs are designed to be implemented in a manner that is optimized forweb designers. An abstraction layer like Skyway Builder must allow for the continued use of JSP pagesfor implementing views.

SOLUTION

Skyway Builder lets you define your user interface using any view technology, including Java ServerPages(JSP). This allows developers very fine grained control of how the user interface renders in modernweb browsers, including desktop and mobile browsers. The UI developer can leverage JSP tag libraries,including Java Standard Tag Library (JSTL).

HOW IT WORKS

Figure 2.10. View (MVC)

Steps for creating a JSP:

1. Right click on WebContent folder, and select New-->JSP. This will open the New JavaServer PageWizard.

2. From the wizard specify the filename for jsp (i.e. index.jsp) and click the Next button.

3. Select Skyway JSP File (html) as the template, and click the Finish button.

Note

If a JSP page is specified directly in the WebContent folder, it will be accessible as a web resourceand through any defined URL Mappings. A best practice is to put the JSP pages in the WEB-INFfolder so that the JSP is only accessible through a URL mapping.

RELATED RECIPES

Web Layer Recipes

18

1. Mapping URLs to Operations and Views

2. Hiding the Implementation Technology

3. Implementing Post/Redirect/Get (PRG) Pattern

4. Implementing an HTML Form in JSP using standard HTML elements

5. Implementing an HTML Form in JSP using Spring Form Tag Library

6. Implementing an HTML Form in JSP using Skyway Tag Library

7. Using Third-Party Tag Libraries

8. Scaffolding a Spring MVC application from domainobject

PROBLEM

There are several layers to a Spring MVC application, and there are many Spring, JPA, and Java artifactsneeded to implement those layers. The Skyway Builder Spring DSL simplifies the development ofthese artifacts through the use of code generation, but there is also an opportunity to generate fullapplications. Other development platforms, including RAILS and GRAILS, have popularized this approachto application development. Scaffolding consists of generating full applications by applying standardapplication patterns from a minimal set of inputs provided by the developer. Whether these scaffoldedapplications are used as-is or as the starting point for additional developer customization, scaffolding isvery effective at jump-starting application development.

SOLUTION

Spring MVC scaffolding consists of generating a full Spring MVC application based on the CRUDapplication pattern. By only defining the domain model, which can consist of one or more related domainobjects, the Spring MVC scaffolding engine will create all the web, service, and data layer componentsfor managing the domain objects, including create, read, update and delete.

Starting with a domain object, here's what gets created by Spring MVC scaffolding:

Spring MVC Scaffolding

1. a model package for the data access object layer

2. a data access object (DAO)

3. a set of named queries (JPQL) for the domain object

4. a model package for the service layer

5. a Service with CRUD operations

6. a model package for the controller layer

7. a Controller with fully implemented CRUD operations

8. Junits for controllers and

9. layout managed user interface using Sitemesh

Web Layer Recipes

19

10.CRUD JSP pages using Spring Form tag library and JSTL

11.client-side validation implemented Spring JS with DOJO

12.integration with Spring Security, including a default DB implementation of users and authorities

Scaffolding Note

While the Spring MVC scaffolding generates a fully wired and ready-to-run Spring MVC applicationbased on the CRUD application pattern, the Spring MVC scaffolding accomplishes this by generatingthe appropriate Spring DSL artifacts. This enables an application developer to continue to refinethe scaffolded application, if needed, using the Spring DSL abstraction layer.

HOW IT WORKS

Before scaffolding an application the developer must create or import the domain model using the SpringDSL, and the domain model must be contained within a Model Pacakge.

Here are the steps for using the Spring MVC scaffolding:

Steps for scaffolding a domain object:

1. Right-click on a domain object, and select Scaffolding --> Generate CRUD

Scaffolding Note

The Spring MVC scaffolding will automatically create the model packages for the other layers of theapplication, and the Spring DSL artifacts will be generated into the appropriate model packages.If the model package for the domain object ends with ".domain", then the Spring DSL will create".dao", ".service" and ".web" model packages at the same level as the ".domain" model package.This is a fairly typical convention for package names in a Spring MVC application, but the developercan of course move the artifacts to other packages if needed.

RELATED RECIPES

1. Scaffolding Spring Security

9. Scaffolding Spring SecurityPROBLEM

Security is an important part of a web application, and Spring Security provides a set of security servicesthat integrate with Spring-based applications. Spring Security offers a lot of options, but it can be difficultto quickly get a project bootstrapped with Spring Security.

SOLUTION

Skyway Builder Standard Edition1 has a development accelerator for bootstrapping a project with SpringSecurity.

HOW IT WORKS

Here are the steps for using the Spring Security scaffolding:

1 http://www.skywayperspectives.org/portal/web/guest/products/builder/standard-edition

Web Layer Recipes

20

Steps for scaffolding Spring Security:

1. Right-click on the Spring DSL project, and select Scaffolding --> Scaffold Spring Security

2. Select a model package to store the Spring Security artifacts

Skyway Builder will configure the application for Spring Security, which includes:

Spring Security scaffolding:

1. Create a User domain object and UserDAO for storing user credentials. These artifacts can be furthercustomized using Spring DSL if needed.

2. Create a Authorities domain object and AuthoritiesDAO for storing authorization data. These artifactscan be further customized using Spring DSL if needed.

3. Enable Spring security in the Security Settings section of the Enterprise Configuration tab.

4. Configure Secured URLs in the Security Settings section of the Enterprise Configuration tab.

5. Configure Secured Services in the Security Settings section of the Enterprise Configuration tab.

6. Configure Secured Data Access Objects in the Security Settings section of the Enterprise Configurationtab.

7. Configure Security Views in the Security Settings section of the Enterprise Configuration tab, includinglogin, login success, login failure, logout success, and access denied views.

8. Configure Security Information Sources in the Security Settings section of the Enterprise Configurationtab, including database configuration with queries for AuthoritiesDAO and UserDAO.

9. Create dedicated Spring Security context files: project-security-context.xml, generated-project-security-context.xml

While Skyway Builder can fully setup Spring Security in a project with a few seconds, the configuration issetup to enable further customization using Spring DSL. See Securing Applications - Authentication andSecuring Applications - Authorization.

RELATED RECIPES

1. Securing Applications - Authentication

2. Securing Applications - Authorization

10. Mapping URLs to Operations and ViewsPROBLEM

In the context of Spring MVC there are request handlers, called Operations in the Spring DSL, that areimplemented in the controller for defining the behavior of the application and handling user-generatedevents. There needs to be a strategy for a Controller to identify (a) which Operations are available to webclients, (b) what URL will be used to address the Operation, and (c) which View should be used to renderthe response.

SOLUTION

In addition to serving as the container for Operations, a Controller defines URL Mappings, which associateURLs to Operations and Views. URL Mappings are the mechanism for specifying which Operations are

Web Layer Recipes

21

going to be accessible to web clients. This is accomplished by defining one or more URL Mappings in theController.

HOW IT WORKS

A URL Mapping is responsible for defining the url(s) that will trigger an action. When the defined URL isrequested from a web control, javascript or web client, the operation associated with (mapped to) theurl will handle the request. The URL mapping will also specify the jsp that will render the response to therequest. Every request will have a response, and the URL mapping specifies both the operation that willhandle the request and the jsp that will render the response

Code Generation Note

The configuration of a URL mapping is manifested in several places in the generated Spring MVCapplication. Here's a summary of the effects of a URL mapping::

1. an servlet mapping entry (mapping to Spring servlet) will be added to the web.xml

2. an @RequestMapping entry will be added to the controller method(s) representing theoperation, and the value will be the configured URL.

3. the view is automatically emitted into the request handler

Each mapping has several parameters:

Table 2.1. URL Mapping Parameters

Parameter Description

URL The URL being mapped, or intercepted by the MVC framework. Thecontroller that the URL Mapping is being added to will handle allrequests for the specified URL.

Request Handler The operation that will handle the request or variable that data willbe bound to.

When an Operation is specified as the request handler, theconfigured URL is being mapped to the functionality correspondingto the selected Operation.

When an Variable is specified as the request handler, theconfigured URL can be used for mapping data to the selectedVariable. (This is primarily an AJAX scenario.)

While a request handler is typically specified, it's not required.If the request handler is omitted, then the URL will essentiallyfunction as an alias to the View.

View The view that should be rendered following the invocation of theOperation; the configuration choices are:

• A JSP page

• View alias (defined at project level)

Web Layer Recipes

22

Parameter Description

• Controller or Operation variable

For a specific URL mapping the view cannot be the same asURL because you would end-up with a circular reference. Whileyou can workaround this by using an alias to the URL, thisapproach is generally not recommended because it exposes theimplementation technology to end-users and potential hackers. SeeHide the Implementation recipse for the best practice approach.

Redirect: By default the request will be forwarded to the view onthe server. The redirect option will instead send the browser aredirect command to the specified View.

Error View The Error View functions very similarly to the View, except that itspecifies the view that should be rendered following a binding orvalidation error. The configuration choices are the same as View.

Data Validation The Spring validation class and method that should be used tovalidate the request.

The configurations needed to achieve the desired page flow pattern are represented in the followingdiagram:

Example 2.4. URL Mapping - Examples

URL OPERATION VIEW ---------------------------------- -------------------------------- ---------------------------------

/OrderController/LoadHistory.action --> LoadHistory --> history.jsp

/index.jsp --> LoadPreferences --> layout.jsp

/preferences --> LoadPreferences --> preferencesummary.jsp

/OrderController/SaveHistory.action --> SaveHistory --> page<operation variable>

/index.htm --> LoadCatalog --> index.jsp

Web client calls to /OrderController/LoadHistory.action will invoke theLoadHistory operation and the response will be rendered by history.jsp. A conventionused by Skyway Builder is to automatically create a URL for new operations using the model packagefor namespacing the URL (i.e."/org/myapp/web//ControllerName/OperationName.action"). Thiscan be overridden from the operation wizard when the operation is created, and it can also beoverriden after the fact in the URL mapping tab.Web client calls to /index.jsp will invoke the LoadPreferences operation and the responsewill be rendered by layout.jsp.Web client calls to /preferences will invoke the LoadPreferences operation and theresponse will be rendered by preferencesummary.jsp. The point of this example is that youcan have multiple URLs mapped to the same operation, and the same or separate View can bespecified.Web client calls to /OrderController/SaveHistory.action will invoke theSaveHistory operation and the response will be rendered by the view specified in the operationvariable called page. The developer can dynamically specify the page based on the result of theoperation.Web client calls to /index.htm will invoke the LoadCatalogy operation and the response willbe rendered by index.jsp. See Hiding the Implementation Technology for more details on thisBEST PRACTICE

RELATED RECIPES

Web Layer Recipes

23

1. Creating Helper Methods using Operations

2. Reusing Operations in Different Contexts

3. Hiding the Implementation Technology

4. Implementing Post/Redirect/Get (PRG) Pattern

11. Creating Helper Methods using OperationsPROBLEM

There are occasions where you want to create operations that are shared by other operations forperforming common tasks. The Helper Operations are typically not intended to be accessible from a webclient, and there needs to be strategy for preventing web clients from accessing these Operations.

SOLUTION

Create an Operation that doesn't have a defined URL Mapping. This will result in an Operation that isn'tdirectly accessible to web clients and is only accessible from other Operations using the Invoke Operationstep. An Operation can have multiple mappings defined in the Web Controller. If an Operation has atleast one mapping, the Operation is considered public. If a URL Mapping doesn't exist for Operation, theOperation is considered private.

It's also possible to define helper operations in the Service layer of the application, and service operationscan called from the web layer using the Invoke Operation step.

HOW IT WORKS

Since a URL Mapping is responsible for defining the url(s) that will trigger an operation. Omitting orremoving a URL Mapping for a specified operation will result in the operation only being available to otheroperations in the same controller.

Code Generation Note

When an operation is excluded from all URL mappings, the method generated from the operationwon't have the @RequestMapping annotation, the input parameters won't be annotated with@RequestParm or @ModelAttribute, and the method won't make use of a ModelAndView object.

RELATED RECIPES

1. Mapping URLs to Operations and Views

2. Reusing Operations in Different Contexts

3. Hiding the Implementation Technology

4. Implementing Post/Redirect/Get (PRG) Pattern

12. Reusing Operations in Different ContextsPROBLEM

An operation is a specific set of logic that handles a user-generated event. There are occasions where anOperation may be reused in different contexts. There needs to be a strategy for reusing an Operation ina different context and associating it with a different View.

Web Layer Recipes

24

SOLUTION

A controller allows for multipe URL mapping entries to the same Operation. As the long as the URL isunique, addition URL mappings can be added to the controller and configured to the same Operation. Inthis scenario the developer mat also want to specify a different View for the Action.

HOW IT WORKS

The following two URL mappings are configured for the same operation but different views.

Example 2.5. URL Mapping - Reusing ActionsURL OPERATION VIEW ---------------------------------- -------------------------------- ---------------------------------

/OrderController/LoadHistory/detailed --> LoadHistory --> detailview.jsp

/OrderController/LoadHistory/summary --> LoadHistory --> summaryview.jsp

Web client calls to /OrderController/LoadHistory/detailed will invoke theLoadHistory operation and the response will be rendered by detailview.jsp.Web client calls to /OrderController/LoadHistory/summary will invoke theLoadHistory operation and the response will be rendered by summaryview.jsp.

In both cases the LoadHistory operation is being invoked, however a different URL and View are specifiedin the URL Mapping.

Code Generation Note

When two or more URL mappings are configured to the same operation, the operation logic willbe generated to a separate implementation method, and each controller methods generated fromthe URL mappings will call the single implementation method and specify it's own view.

RELATED RECIPES

1. Mapping URLs to Operations and Views

2. Creating Helper Methods using Operations

3. Hiding the Implementation Technology

4. Implementing Post/Redirect/Get (PRG) Pattern

13. Hiding the Implementation TechnologyPROBLEM

One of the best practices in web development is to avoid directly revealing the implementationtechnology. This prevents hackers from identifying the implementation technology, thus reducing ahackers ability to potentially interfere with the running application. This practice also makes it easier tochange the implementation technology without impacting end-users of an application (i.e. bookmarks).There needs to be a strategy to hide the implementation technology in Spring applications generated bySkyway.

SOLUTION

In the context of JAVA and Spring, implementing this best practice consists of hiding the fact that youare using JSPs. Don't use JSP extensions (.jsp) in URLs, and refrain from letting the JSP extension show up

Web Layer Recipes

25

in the browser's address bar. That doesn't mean you can't use JSPs for rendering the view. It just meansthat you hide it from the end-user. This is accomplished by mapping some other URL with a differentextension to the actual JSP. Since a web application is typically emitting HTML, the generally preferredextension is .htm or .html.

HOW IT WORKS

The only server resources that a web client can access are the resources that are exposed by the developerusing a URL mapping. As part of a URL mapping, the developer specifies the URL, Operation, and View.For the URL, the developer can name the URL whatever they'd like. Instead of specifying a URL with a JSPextension, the URL should have a .html extension.

For each web client request (using a URL with a .html extension), a JSP page (View configuration from theURL mapping) will generate the response. However the user's address bar will show the mapped URL,not the JSP.

Example 2.6. URL Mapping - Hiding Implementation TechnologyURL OPERATION VIEW ---------------------- -------------------------------- ---------------------------------

/index.html --> LoadData --> index.jsp

/edit.html --> InitEdit --> edit.jsp

Web client calls to index.html will invoke the LoadData operation and index.jsp willrender the response. The end-user's browser bar will show the requested url (/index.html).Web client calls to edit.html will invoke the InitEdit operation and edit.jsp will renderthe response. The end-user's browser bar will show the requested url (/edit.html).

RELATED RECIPES

1. Mapping URLs to Operations and Views

2. Creating Helper Methods using Operations

3. Reusing Operations in Different Contexts

4. Implementing Post/Redirect/Get (PRG) Pattern

14. Implementing Post/Redirect/Get (PRG) PatternPROBLEM

Post/Redirect/Get (PRG) is a common design pattern for web applications, to help avoid duplicate formsubmissions and allow web applications to behave more intuitively with browser bookmarks and thereload button. After a web user submits a form to a server, the server typically generates an HTML pageas a response. To the user, this looks like an ordinary web page, but because it was generated by anHTTP POST request, it cannot be bookmarked, and attempting to reload/refresh the page in the browsercould cause the form information to be resubmitted, possibly with unexpected results (such as a duplicatepurchase). Wikipedia2

SOLUTION

To avoid this problem, many web applications use the PRG pattern — instead of returning an HTMLpage directly, the POST operation returns a redirection command (using the HTTP 303 response code

2 http://en.wikipedia.org/wiki/Post/Redirect/Get

Web Layer Recipes

26

(sometimes 302) together with the HTTP "Location" response header), instructing the browser to load adifferent page using an HTTP GET request. The result page can then safely be bookmarked or reloadedwithout unexpected side effects. Wikipedia3

HOW IT WORKS

When a post is made to a Skyway Operation, the View is configured to send a redirect command to thebrowser to a second URL, using the URL mapping's redirect option. The redirect results in a second request(get) being automatically made by the end-user's browser to another URL. The second URL is mapped toan operation for loading the model data before being directed to a JSP page for rendering the view. Theredirect results in the second URL being listed in the browser's address bar. If the end-user refreshes thepage, the original data won't be resubmitted because only the second URL will be reloaded. If the secondURL is configured with an Operation that loads data, a bookmarked page can be reconstituted.

The following fragment shows two URL mappings working in tandem to implement the PRG pattern.

Example 2.7. URL Mapping - Post/Redirect/Get (PRG)URL OPERATION VIEW ---------------------- ---------------------------- ---------------------------------

/MyController/SaveOperation.action --> SaveOperation --> edit.html (w/ REDIRECT)

/edit.html --> LoadOperation --> edit.jsp

When data is posted to the server, the form is configured to post to the /MyController/SaveOperation.action URL.The URL mapping for /MyController/SaveOperation.action is configured to invokeSaveOperation, which presumably processes the user input.Rather than emitting the view directly using a JSP, the View is configured to redirect to a secondURL, specified as edit.html.The edit.html URL has it's own URL mapping entry (get).The URL mapping for /edit.html is configured to invoke LoadOperation to load data.The view for edit.html is rendered using the configured JSP page (edit.jsp)

As far as the end-user is concerned, they submitted data to the application and they received a response,and they are generally unaware that two http requests were used to accomplish it.

RELATED RECIPES

1. Mapping URLs to Operations and Views

2. Creating Helper Methods using Operations

3. Reusing Operations in Different Contexts

4. Hiding the Implementation Technology

15. Restricting Direct Access to JSP PagesPROBLEM

For many modern MVC framework, there is an expectation that all web client requests will go through afront controller. In the context of Spring MVC, the front controller is the Spring Dispatcher Servlet. Webresources, such as JSP pages, that are typically accessible as web resources must not be directly accessibleto web clients..

3 http://en.wikipedia.org/wiki/Post/Redirect/Get

Web Layer Recipes

27

SOLUTION

A common approach for disallowing direct access to JSP pages is to putting JSP pages in the WEB-INFfolder. Any resources located in WEB-INF folder, including JSP pages, aren't URL addressible.

The supporting web application resources (css, javascript, images) need to be directly accessible, andthey should not be located in the WEB-INF folder. Only the JSP pages, which are intended to be accessedthrough a URL mapping, should be contained in the WEB-INF folder.

HOW IT WORKS

By placing JSP pages in the WEB-INF folder, web clients can't directly access the JSP pages. However thedeveloper can use JSP pages in the WEB-INF folder when specifying the View for URL Mappings.

RELATED RECIPES

1. Hiding the Implementation Technology

16. Implementing Controller Methods using Actionsand Steps

PROBLEM

A controller is responsible for orchestrating the server logic necessary for processing a request from a webclient. The logic associated with a controller is contained within one or more related controller methods,that must be implemented to define the behaviour of the application. There needs to be a mechanismfor leveraging automation for defining and implementing controller methods.

SOLUTION

The Skyway Generation Framework has generators for the different layers of a Spring application, andthe framework also supports fine-grained specification of the application logic. The metadata modelencompasses an extensible toolbox of pre-built functionality (Skyway Steps) that can be used to specifythe application logic. Skyway Steps introduce automation to the application development process. Usingsteps to implement logic (instead of custom code) is very appealing to developers and architects. Firstof all it reduces the redundancy of application development. Rather than continuously having to writethe same code over and over with only minor differences, steps automate the generation of code for thedeveloper. By using steps there is also more uniformity in the code because all the code was generatedin the same consistent manner (using a customizable step template). There will also be less deviation incode as attributed by different developer styles, conventions or preferences. Enterprise architects lovesteps because they are easy to create, and it ensures that developers are accessing enterprise resourcesin a prescribed and controlled manner.

To achieve the desired application behavior, a developer will

1. define a Skyway Operation for each controller method

2. define the signature of the operation using inputs/outputs

3. define at least one action for each Skyway Operation

4. add one or more steps from the Step Pallette (toolbox) to the Action

5. configure the steps according to application requirements

6. sequence the steps into a flow

Web Layer Recipes

28

The Skyway Generation Framework then converts the Operation and Action into a controller method andthe sequence of steps into well-formed java code.

HOW IT WORKS

Operations define web controller methods for handling user-generated events, and Actions are used tomodel the operation logic. Skyway Builder enables a Operation to be implemented using a model-basedapproach, that defines the logic to be performed by configuring and sequencing one or more SkywaySteps together.

Steps for creating an Action:

1. Right click the on an operation, and select New-->Action to open the New Action Wizard.

2. From the New Action panel enter a common name for the Action. The common name is for referencingthe Action from other Actions in the same operation. Click Finish. The Action Editor will be opened.

Steps for implementing an Action:

1. Click on a desired step from the step palette. The steps are grouped by related functionality intodrawers.

2. Next click on the location on action canvas that you want to place the step..

3. Configure the step using the properties in the properties panel.

4. Repeat the process until all steps are located on the canvas and configured.

5. Next draw a connector (available from the palette) between steps. The steps should connected in theorder that they must execute.

6. When done, right-click on the step that you desire to be the first step to run, and mark it as the StartStep using the menu option.

Figure 2.11. Action Editor

The Step Palette contains all the available steps. The steps are divided into functional groups, and theyare separated by each other using drawers.

Web Layer Recipes

29

Figure 2.12. Step Palette

In order to accomplish more complex tasks the application logic may be implemented using severalActions. A operation is configured to call a specific Action (entry point action), which will orchestrate callsto other Actions (using Invoke Action step) or Operations (using Invoke Operation step) in the Servicelayer of the application.

The following figures shows an abbreviated version of the code that is generated from an Action artifact.To see the fully generated code, see the SkywayBlog sample project.

Web Layer Recipes

30

Example 2.8. Action (Generated)

package skywayblog.web.blogcontroller.browsemodel;

import javax.annotation.Resource;import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Component;

// Additional imports to support Action logic

/** * SelectPost - Action * * @generated */@Scope("prototype")@Component("BlogController.BrowseModel.selectPost")public class SelectPost implements IVariableContextProvider {

/** * The SLF4J logging class. * @generated */ private transient Logger logger = LoggerFactory.getLogger(getClass());

/** * @generated */ private transient ApplicationContext applicationContext;

/** * Reference to Model used by Action * @generated */ @Resource(name = "BlogController.BrowseModel") private BrowseModel variableStorage;

// Constructor ...

/** * @generated */ public void doInvoke() throws Exception {

GENERATATED APPLICATION LOGIC GOES HERE }

}

Code Generation Note

The code that is generated by a Skyway step is contributed by Eclipse plugins. Skyway BuilderCommunity Edition (CE)4 contains a core set of steps for code generation, and the other editionsof Skyway Builder5 add additional steps. Using the Eclipse plugin architecture, new steps can bedeveloped to automate the generation of any java logic. If you are interested in building your ownsteps, the Skyway Builder community site6 has a tutorial. While Skyway Builder includes a defaultset of code generation options and templates, Skyway Builder also supports code generationcustomization.

4 http://www.skywayperspectives.org/portal/web/guest/builderce5 http://www.skywayperspectives.org/portal/web/guest/builder6 http://www.skywayperspectives.org/

Web Layer Recipes

31

RELATED RECIPES

1. Blending Actions with non-generated Java Code

2. Blending Actions with non-generated Spring Beans

3. Accessing Request and Session Parameters

4. Using Groovy in Actions

17. Blending Actions with non-generated Java CodePROBLEM

As described in the Implementing Controller Methods using Actions and Steps recipe, augmentingthe application development process with modeling-based automation can significantly improvedevelopment productivity and application quality. However it's important to recognize that modeling-based automation should not be an all or nothing proposition. Model-based automation must becomplimentary to traditional code-based development. There are occasions where java code may bebetter suited to implement a portion of an Action. Therefore there needs to be a seemless way of blendingjava code with generated code.

SOLUTION

Skyway Builder excels at blending models and code. Skyway Builder let's you drop code into your projectsthat can be used along-side the model-based components. In the event that your functionality cannot beeffectively expressed using models (perhaps due to lacking model-based representations of functionalityor efficiency/performance considerations), you can use regular java code and java libraries along withyour models.

While using java code in conjunction with models is a powerful feature in itself, Skyway Builder goesthe extra step of adapting (blending) code-based resources to appear as model-based resources in themodeling environment. For example, if you define POJO's in your project, they can be used just like POJO'sderived from models.

Another capability afforded by the Skyway Builder application generation engine is that the generatedlogic/code can be used directly from the developer's custom code. The code generated by Skyway isconcise and human-readable, and it's organized and packaged according to the developers preference.This makes it very easy for developers to find and use the generated functionality from within their customcode.

The bottom line is that Skyway Builder makes it easy for your model-based and code-based artifacts to co-exist and interact. Java developers can now implement the data, service, and web layers of their solutionentirely in models or through the blending of models and java code. Custom Java code can be authoredalong side models, and both can be fully leveraged by one another.

The Invoke Java step lets you invoke pre-written JAVA code from your Action. (For Spring integration seeBlending Actions with non-generated Spring Beans) As a developer is sequencing various Skyway steps toimplement an Action, the developer can incorporate pre-existing JAVA logic into the flow. The JAVA codemay be contained in JAVA libraries (jar) or a source files within the project.

HOW IT WORKS

In order for a JAVA class to be used by the Invoke Java step, the class must have a PUBLIC constructor thatdoesn't require any arguments. The following figure shows a very basic JAVA class that will be leveragedfrom an Action.

Web Layer Recipes

32

Example 2.9. Blending Java Code with Actions - MyJavaClass.java

package example.web.mycontroller.mymodel;

public class MyJavaClass {

public MyJavaClass(){ }

public String doThis(String x, Integer y){ //... return x; }

public void doThat(String z){ //... return; }

}

Steps for calling JAVA code using Invoke Java Step:

1. From an Action, open the Java drawer in the Skyway Step Palette.

2. Click on the Invoke Java step in the palette and click on the Action Canvas. The step will be placed atthe location you click.

3. Switch to the Java panel on the Steps properties.

4. Select an invocation type

• Inline - this invocation type is for invoking java source code that is embedded directly into the step(Source)

• Variable - this invocation type is for invoking methods on variables defined in either the Model orProject

• Instance - this invocation type is for creating an instance of a specified class prior to invoking a javamethod

• Static - this invocation type is for invoking static methods without creating an instance of a class

5. After the invocation type is selected, the Java panel will show the fields that need to be configured.Configure the remaining fields to invoke the MyJavaClass.

6. Based on the method signature, the Parameters panel will list any input parameters. The inputparameters must be mapped to variables

The following examples will show the generated code for the various invocation types.

Inline Invocation

In order to use inline invocation, you must specify the code in the source window of the Invoke Java Stepusing the Inline invocation option. The code will be generated verbatim into the operation method.

Variable Invocation

In order to use variable invocation, you must create an instance of the class using an Operation variable.Next configure the Invoke Java step using the Variable invocation option and specify the variable, methodname and return variable.

Web Layer Recipes

33

Figure 2.13. Creating an instance of MyJavaClass using Variables

Example 2.10. Invoke Java Step - Variable Invocation (Generated Code)

// InvokeJavaStep: Invoke Java

MyJavaClass instanceVariable = getVariableStorage().getMyclassVar();

String inputString = ((String) getVariableContext().get("inputString")); Integer inputInteger = ((Integer) getVariableContext().get("inputInteger"));

String result_1 = instanceVariable.doThis(inputString, inputInteger);

getVariableContext().set("outputString", result_1);

A reference to MyJavaClass is being obtained from model variables.Input parameters are being obtained from model variables.The doThis() method is being called, and input parameters are being passed.The return parameter is being assigned to model variable.

Instance Invocation

In order to use instance invocation, configure the Invoke Java step using the Instance invocation optionand specify the class name, method name and return variable.

Example 2.11. Invoke Java Step - Instance Invocation (Generated Code)

// InvokeJavaStep: Invoke Java

MyJavaClass instanceVariable = new MyJavaClass();

String inputString = ((String) getVariableContext().get("inputString")); Integer inputInteger = ((Integer) getVariableContext().get("inputInteger"));

String result_1 = instanceVariable.doThis(inputString, inputInteger);

getVariableContext().set("outbean", result_1);

A new reference to MyJavaClass is being instantiated.Input parameters are being obtained from model variables.The doThis() method is being called, and input parameters are being passed.The return parameter is being assigned to model variable.

Static Invocation

In order to use static invocation, configure the Invoke Java step using the Static invocation option andspecify the class name, method name and return variable.

Web Layer Recipes

34

Example 2.12. Invoke Java Step - Static Invocation (Generated Code)

// InvokeJavaStep: Invoke Java

String inputString = ((String) getVariableContext().get("inputString"));

void result_1 = MyJavaClass.doFoo(inputString);

getVariableContext().set("outputString", result);

Input parameters are being obtained from model variables.The doFoo() method is being statically invoked, and input parameters are being passed.The return parameter is being assigned to model variable.

RELATED RECIPES

1. Implementing Controller Methods using Actions and Steps

2. Blending Actions with non-generated Spring Beans

18. Blending Actions with non-generated Spring BeansPROBLEM

The Blending Actions with Custom Java Code recipe described how to use custom java from within Actions,and it was accomplished by creating an instance to the JAVA classes that contain the code. As furtherdescribed in the recipe, there are various options for creating those instances. However the Invoke Javastep doesn't support having instances of a java class be acquired through Spring.

SOLUTION

The Invoke Spring step lets you invoke Spring beans from an Action. By adding one or more beans to aSpring context file and registering the Spring context file in the Skyway modelling project, the applicationdeveloper lets Spring handle instantiating the bean. Using the Invoke Spring step, the developer canleverage the logic contained in the bean.

HOW IT WORKS

In order for a Spring bean to be used by the Invoke Spring step, the class must have a PUBLIC constructorthat doesn't require any arguments. The following figure shows a very basic Spring Bean (MyBean) thatwill be leveraged from an Action.

Web Layer Recipes

35

Example 2.13. Blending Spring Beans with Actions - MyBean.javapackage example.web.mycontroller.mymodel;

public class MyBean {

private String country;

public String getCountry() { return country; }

public void setCountry(String country) { this.country = country; }

public MyBean(){ System.out.println("I have been instantiated"); } public String doThis(String x){ System.out.println(country); return x+"DONE"; }}

The following Spring context defines a bean call MyBean.

Example 2.14. Spring Context File - mycontext.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">

<bean id="MyBean" class="example.web.mycontroller.mymodel.MyBean"> <property name="country" value="Ecuador"/> </bean>

</beans>

Steps for calling Spring Beans using Invoke Spring Step:

1. Copy mycontext.xml to the source folder of the same project (i.e. example-Web/src) thatMyBean.java is defined in.

2. From the Spring Configuration tab on the Model project (i.e. example) add mycontext.xml toproject Spring contexts. Note that the context file can be added to the web layer and/or servicelayer. Make sure you add it to the correct layer based on the project you added MyBean.java andmycontext.xml to.

3. From an Action, open the Java drawer in the Skyway Step Palette.

4. Click on the Invoke Spring step in the palette and click on the Action Canvas. The step will be placedat the location you click.

5. Switch to the Bean panel on the Steps properties.

Web Layer Recipes

36

6. Select an invocation type

• Static - the bean will be looked-up by bean id

• Dynamic - the bean will be looked-up by bean class

7. After the invocation type is selected, the Bean panel will show the fields that need to be configured.Configure the remaining fields to invoke MyBean.

8. Based on the method signature, the Parameters panel will list any input parameters. The inputparameters must be mapped to variables

The following examples will show the generated code for the various invocation types.

Static Invocation

Example 2.15. Invoke Spring Step - Static Invocation (Generated Code) // InvokeSpringStep: Invoke Spring

MyBean bean = (MyBean) doBeanLookup("MyBean");

String inputSting = ((String) getVariableContext().get("inputString"));

String result = bean.doThis(inputString);

getVariableContext().set("outputString", result);

Spring is providing an instance of MyBean.Input parameters are being obtained from model variables.The doThis() method is being called, and input parameters are being passed.The return parameter is being assigned to model variable.

Dynamic Invocation

Example 2.16. Invoke Spring Step - Dynamic Invocation (Generated Code) // InvokeSpringStep: Invoke Spring

MyBean bean = (MyBean) doBeanLookup(example.web.mycontroller.mymodel.MyBean.class);

String inbean = ((String) getVariableContext().get("inbean"));

String result = bean.doThis(inbean);

getVariableContext().set("outbean", result);

Spring is providing an instance of example.web.mycontroller.mymodel.MyBean.Input parameters are being obtained from model variables.The doThis() method is being called, and input parameters are being passed.The return parameter is being assigned to model variable.

RELATED RECIPES

1. Implementing Controller Methods using Actions and Steps

2. Blending Actions with non-generated Java Code

19. Implementing an HTML Form in JSP using standardHTML elements

PROBLEM

Web Layer Recipes

37

HTML is the predominant markup language for web applications. While there are a variety of webtechnologies for simplifying the definition of html-based user interfaces and facilitating the integrationof the UI with server logic (see Spring Tag Library and Skyway Tag Library), a UI developer should notbe forced to use other technologies for doing standard HTML, like an HTML form. As long as the UIdeveloper understands how to interact with the server logic, the developer should be able to implementuser interfaces using standard HTML.

SOLUTION

Skyway Builder provides a JSP tag library to make it easier to implement HTML forms, but a developer isn'trequired to use it. A developer can implement a form using the standard form tags, like <form>, <input>,<textarea>, <radio>, <select>, <button>, etc... This enables a UI developer compose user interfaces usingany HTML editor of their choice.

HOW IT WORKS

The following table describes the key attribute configurations for various standard HTML controls in orderinteract with a Spring MVC application generated by Skyway Builder.

Table 2.2. Binding HTML Form Controls

HTML Form Control Attribute Configuration

<form> action: The URL that the form should be posted to. The URL composed of adefined URL Mapping that is prefixed with the application context. The URLMapping must be set to bind request variable. Otherwise the form data willbe discarded.

<input>,<textarea><select>,<option>

name: The model variable that the HTML control should be bound to. Whenthe form is posted, the value of the web control will assigned to the variablespecified.

The following HTML fragment shows how you can implement an HTML form using standard HTMLcontrols.

Example 2.17. HTML Form using Standard HTML Controls<!-- The labels and ids have been omitted for brevity. -->

<form id="MyModel" name="myForm"

action="${pageContext.request.contextPath}/MyController/saveModel.action" method="post">

<input name="name" type="text" value=""/> <textarea name="description" rows="3" cols="20"></textarea> <input name="validated" type="checkbox" value="true"/> <select name="country"> <option value="-">--Please Select</option> <option value="USA">USA</option> <option value="Canada">Canada</option> </select> <input name="country" type="radio" value="Blue"/> <input name="country" type="radio" value="Green"/>

<input type="submit" value="OK" /></form>

The form id attribute is configured with the name of the Model that contains the variables that willbe set by this form. In this example the Controller contains a model called "MyModel".The form action attribute is configured with the URL that will handle the form submission. The URLshould be a configured URL mapping with the "Bind Request Values" enabled.The form element name attribute is configured with the model variable that form element will bebound to..

Web Layer Recipes

38

The user interface in Skyway applications is implemented using JSP which offers a lot of inherentfunctionality to help web developers build web applications. JSP functionality is fully leveragable forSkyway applications, and Skwyay Builder adds some additional functionality make building user interfaceseven easier.

Note

The Skyway Builder tag library emits standard HTML. If you need to figure out to specify theHTML for passing data to the server but you don't want to use the Skyway tag library, you can usethe HTML emitted by the web controls defined in the Skyway Builder tag library as a template.

RELATED RECIPES

1. Implementing an HTML Form in JSP using Spring Form Tag Library

2. Implementing an HTML Form in JSP using Skyway Tag Library

3. Using Third-Party Tag Libraries

20. Implementing an HTML Form in JSP using SpringForm Tag Library

PROBLEM

Spring MVC provides a JSP tag library (Spring Form) for making it easier to bind form elements to Modeldata. Skyway Builder's tag library extends the Spring Form tag library, but there may be occasions that theUI developer prefers to use the Spring Form tag library directly or needs to access server-side functionalitygenerated by Skyway Builder from pre-existing JSP pages implemented with the Spring Form library.

SOLUTION

Skyway Builder supports the use of the Spring Form tag library for implementing JSP-based userinterfaces.

HOW IT WORKS

In order to use the Spring Form tag library, standard JSP tag library conventions apply. You will need toadd the following JSP directive to the JSP page that will use the Spring Form tag libary.

Example 2.18. JSP Directive for using Spring Form Tag Library

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

The Spring Form tag library can then be used to implement the user interface. The following HTMLfragment shows how you can implement an HTML form using the Spring Form tag library.

Web Layer Recipes

39

Example 2.19. HTML Form using Spring Form Tag Library

<!-- The labels and ids have been omitted for brevity. -->

<form:form commandName="MyModel" name="myForm"

action="${pageContext.request.contextPath}/MyController/saveModel.action" method="post">

<form:input path="name"/> <form:textarea path="description" rows="3" cols="20" /> <form:checkbox path="validated" value="Magic"/> <form:select path="country"> <form:option value="-" label="--Select Country"/>

<form:options items="${countries}"/> </form:select>

<form:radiobuttons path="color" items="${colors}" />

<input type="submit" value="OK" /></form:form>

The commandName attribute is configured with the name of the Model that contains the variablesthat will be set by this form. In this example the Controller contains a model called "MyModel".The action attribute is configured with the URL that will handle the form submission. The URL shouldbe a configured URL mapping with the "Bind Request Values" enabled.The Spring Form path attribute is configured with the model variable that form element will bebound to.In order to populate a dropdown with a list of items stored in variable, the items attribute shouldbe configured with a Model variable. The variable can be a list, map, or collection of objects.Populating radio button options is very similar to dropdown options. For the items attribute youcan use a list, map, or collection of objects.A standard html submit button will submit the form to the specified action.

The user interface in Skyway applications is implemented using JSP, which offers a lot of inherentfunctionality to help web developers build web applications. In addition to using the Spring Form taglibrary, standard JSP functionality (i.e. JSTL) is fully leveragable for Skyway applications

Note

While the Spring tag library is the easiest way to bind form controls to Spring command objects,the <spring:bind> tag can also be used. When using the <spring:bind> tag, the bind path shouldreference the command object. Following the previous example:

Example 2.20. HTML Form using <spring:bind> tag

<form action="${pageContext.request.contextPath}/MyController/saveModel.action"> <spring:bind path="MyModelname"> <input name="${status.expression}" value="${status.value}"/><br/> </spring:bind> .... <input type="submit" value="OK" /></form>

Scaffolding Note

The Spring MVC scaffolding functionality generates JSP pages using the Spring Form tag library andthe JavaServer Pages Standard Tag Library (JSTL).

RELATED RECIPES

Web Layer Recipes

40

1. Implementing an HTML Form in JSP using standard HTML elements

2. Implementing an HTML Form in JSP using Skyway Tag Library

3. Using Third-Party Tag Libraries

21. Implementing an HTML Form in JSP using SkywayTag Library

PROBLEM

Implementing user interfaces can be tedious. Skyway provides a JSP tag library for making it easier to bindform elements to Model data. Skyway Builder's tag library extends the Spring Form tag library.

SOLUTION

Spring MVC provides a JSP tag library (Spring Form) for making it easier to bind form elements to Modeldata. Skyway Builder's tag library extends the Spring Form tag library, but there may be occasions that theUI developer prefers to use the Spring Form tag library directly or needs to access server-side functionalitygenerated by Skyway Builder from pre-existing JSP pages implemented with the Spring Form library.

The Skyway tag library was created to address some of the difficulties of using the Spring Form tag library.For one thing in order to configure the Spring Form tags, you need to revert to the model/view artifactsand mapping configuration. This is tedious and error-proned. The Skyway tags extends the Spring tagsand adds a custom property editor for each web control. Furthermore Skyway Builder provides wizardsfor configuring model variables and url mappings.

HOW IT WORKS

In order to use the Skyway tag library, standard JSP tag library conventions apply. You will need to add thefollowing JSP directive to the JSP page that will use the Skyway tag libary.

Example 2.21. JSP Directive to include Skyway JSP Tag Library

<%@taglib uri="http://www.skywaysoftware.com/taglibs/core" prefix="skyway"%>

Here is a list of the form-related web controls that are available in the Skyway JSP. Refer to the SkywayWeb Control reference guide for more detailed information.

• Button.

• Checkbox

• Dropdown

• Form

• Input Field

• Iterator

• Layer

Web Layer Recipes

41

• Radio Button

• Radio Button Group

• Text Area

• Upload

Web Layer Recipes

42

Example 2.22. HTML Form using Skyway Builder Tag Library<!-- The labels and ids have been omitted for brevity. --><skyway:form name="myForm"

commandName="MyModel"

action="${pageContext.request.contextPath}/MyController/saveModel.action">

<skyway:input type="text" controller="MyController" path="name"></skyway:input> <skyway:textarea controller="MyController" path="description"></skyway:textarea> <skyway:checkbox controller="MyController" path="validated"></skyway:checkbox> <skyway:dropdown size="1"

items="${countries}" controller="MyController" path="country"> </skyway:dropdown> <skyway:radiobuttons controller="MyController"

items="${paises}" path="color"> </skyway:radiobuttons>

<skyway:button type="submit" label="ok"></skyway:button></skyway:form></body></html>

The commandName attribute is configured with the name of the Model that contains the variablesthat will be set by this form. In this example the Controller contains a model called "MyModel".The action attribute is configured with the URL that will handle the form submission.The skyway:input controller attribute is configured with the controller that will be used to processthis form. The skyway:input path attribute is configured with the model variable that the formelement will be bound to. In this example, name is a variable defined in "MyModel".In order to populate a dropdown with a list of items stored in variable, the items attribute shouldbe configured with a Model variable. The variable can be a list, map, or collection of objects.Populating radio button options is very similar to dropdown options. For the items attribute youcan use a list, map, or collection of objects.A Skyway button will submit the form to the specified action.

RELATED RECIPES

1. Implementing an HTML Form in JSP using standard HTML elements

2. Implementing an HTML Form in JSP using Spring Form Tag Library

3. Using Third-Party Tag Libraries

22. Using Third-Party Tag LibrariesPROBLEM

Java EE provides the Java Standard Tag Library (JSTL) for handling the common JSP development tasks.There are also many third-party tag libraries that provide additional functionality to web developers,including the Spring Form tag library and Skyway Builder tag library.

SOLUTION

Since Skyway Builder is used to develop standard Spring MVC applications, there aren't aren't any specialconsiderations for using third-party tag libraries. A developer can leverage other tag libraries as theynormally would.

HOW IT WORKS

The steps for using a third-party tag library are:

1. Add the tab library jar file to the WEB-INF/lib folder of the Web project

Web Layer Recipes

43

2. Add the JSP directive to the top of the JSP page that will use the library

3. Add the JSP tags to the JSP page

In the following example JSON-taglib7 will be added to a Skyway project. Download the jar file (json-taglib-0.4.1.jar) and copy to WEB-INF/lib folder of the web project. If you copy the project outside ofEclipse, be sure to refresh the project in Eclipse.

Add the JSP directive for JSON-taglib to the top of the JSP page. You will need to add the JSP directive toall the pages where you want to use the tags from the tag library.

Example 2.23. JSP Directive for using Third-Party Tag Library<%@ taglib prefix="json" uri="http://www.atg.com/taglibs/json" %>

Next you can use the JSP tags from within your JSP page.

Example 2.24. Using Third-Party Tags<json:object> <json:array name="items" var="item" items="${MyModel.contacts}"> <json:object> <json:property name="type" value="${item.type}"/> <json:property name="name" value="${item.name}"/> <json:property name="summary" value="${item.summary}"/> </json:object> </json:array></json:object>

When the JSP page is rendered, the output of JSP tag(s) will be emitted into the page.

RELATED RECIPES

1. Implementing an HTML Form in JSP using standard HTML elements

2. Implementing an HTML Form in JSP using Spring Form Tag Library

3. Implementing an HTML Form in JSP using Skyway Tag Library

23. Accessing Request and Session ParametersPROBLEM

HTML data is typically bound to command objects (domain objects or data transfer objects), howeverthere are occasions where you want to access data directly from the request, response or session objects.

SOLUTION

Spring supports adding parameters to a controller method for accessing various objects8. If you add areference to these objects in a method parameter, Spring will automatically pass these objects to themethod at runtime.

HOW IT WORKS

To access the request object, add a input variable of type javax.servlet.http.HttpServletRequest to a weboperation. Use the input variable name to reference the request object from within the operation.

The following example shows a URL parameter that assigns a value ("John") to a variable called name.

http://www.myapplication.com/index.html?name=John

7 http://json-taglib.sourceforge.net/8 http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann-requestmapping-arguments

Web Layer Recipes

44

The following java snippet (that can be used using the Invoke Java step with inline option) showshow the URL parameter is retrieved and assigned to an operation variable. This example assumes youhave an operation variable called username and and operation input variable called request (of typejavax.servlet.http.HttpServletRequest).

Example 2.25. Invoke Java (inline) - accessing Request Parametersusername = request.getParameter("name")

RELATED RECIPES

1. Creating a Controller for Spring MVC

24. Defining the Scope of Components, Controllersand Services

PROBLEM

The HTTP protocol is a stateless protocol, and session management is the technique for making thestateless HTTP protocol support session state. There needs to be a mechanisn for the developer to specifysession managed data.

SOLUTION

A developer can specify the scope of a Component, Controller and Service to any scope supported bySpring9, which includes session and request. Session will scope the Spring component to the request tothe http session, and Request will scope the Spring component to the http request..

HOW IT WORKS

The scope of a component is specified in scope configuration in the Spring Configuration tab.

The following figures shows an abbreviated version of the code that is generated from a Component. Tosee the fully generated code, see the SkywayBlog sample project.

Example 2.26. Model Scope (Generated)package skywayblog.web.blogcontroller.postmodel;

import javax.annotation.Resource;import javax.servlet.ServletRequest;import org.springframework.context.annotation.Scope;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import skywayblog.domain.SkywayBlog;import skywayblog.domain.dataservice.Post;

/** * PostModelImpl - Conversation - Provides access to all public and private variables. * * @generated */

@Scope("session")public class PostModelImpl implements PostModel {

// Constructors, Getters, Setters, Etc... ....

}

The @Scope anottation is reconfigured based on the configured scope.

9 http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes

Web Layer Recipes

45

RELATED RECIPES

1. Managing User Session Data

25. Managing User Session DataPROBLEM

If session-scoped components aren't managed properly, there is a potential for a lot of user session databeing maintained by an application server, putting a strain on application server resources and limitingthe scalability of a web application. Therefore there needs to be a strategy managing session scopedvariables. While Servlet specification has a mechanism for clearing a user's session, it doesn't allow youto selectively discard session data. For example you may want to remove certain components from theuser session while retaining other components.

SOLUTION

The Clear Component step lets a developer discard a model from a session. This allows a developer to usesession-scoped components when needed and selectively discarding the model when no longer needed.

HOW IT WORKS

In navigating the functionality of an application, an end-user may interact with a variety of differentsession-scoped Components. If the session isn't properly managed by an application, all component datawould stored in the session, even component data that is no longer needed. A developer can selectivelydiscard components from a session using the Clear Component step.

RELATED RECIPES

1. Defining the Scope of Components

26. Responding to User-Generated Events (Events andCommands)

PROBLEM

Web applications respond to events, and events typically happen as a result of human interaction withthe an application running in their browser. Some examples of end-user generated events are clicking ona submit button or hyperlink, hovering over a hyperlink, or entering text into a textbox. The interactionmodel of a web application is supported by standard HTML event handlers that allow an applicationdeveloper to control what happens in response to a user generated event. The events need to be wiredto either client-side logic or server-side logic.

SOLUTION

A UI developer can use standard HTML conventions for programming web applications, but SkywayBuilder provides a JSP tag library that provides additional functionality for wiring events to client-side orserver-side logic. The JSP tag library is supported by tooling in Skyway Builder that makes it easier for adeveloper to the configure the tags to achieve the desired functionality.

HOW IT WORKS

In order to use the Skyway tag library a declaration must be added to the top of the JSP page. When usingthe Skyway JSP template (New-->JSP), the Skyway JSP tag is automatically added.

Web Layer Recipes

46

Example 2.27. JSP Directive for using Skyway Tab Library

<%@taglib uri="http://www.skywaysoftware.com/taglibs/core" prefix="skyway"%>

The Skyway Web controls are emitted as standard HTML elements, which can be configured to executelogic (Commands) in response to Events. An HTML element can be configure to respond to multipleevents, and an Event can be configured to execute one or more commands.

Figure 2.14. Web Events and Commands

The following table lists the most common events used in web applicatons. Per the HTML and javascriptspecifications, not all events are supported by all web controls.

Table 2.3. Event Descriptions

Event Description

onblur Web control loses focus

onchange Web control value has changed due to user action

onclick Web control clicked

ondbclick Web control double-clicked

onfocus Web control receives focus

onkeydown Keyboard key pressed in web control

onkeypress Combination of keydown and keyuppressed in web control

onkeyup Keyboard key released in web control

onmousedown Mouse button is pressed over a web control

onmouseout Mouse pointer is moved off a web control

onmouseover Mouse pointer is hovered over a web control

onmouseup Mouse button is released over a web control

Note

Refer to the Skyway Web Control Reference guide for detailed explanation of Skyway webcontrols, events and commands.

Once an event is specified, it can be configured with the logic to be performed in response to the event.The logic is implemented as one or more Skyway Commands, and there are various Skyway Commandsavailable to the web developer.

Table 2.4. Skyway Commands

Command Description

Change CSS Class applies or removes a CSS class to/from a page element

Web Layer Recipes

47

Command Description

Change Style applies a style to a page element

Change Visibility show and/or hides a page element

Custom Script invokes a javascript

Load URL this command can load a full page or load content into a section of thecurrent page

Move Element this command moves a page element to a coordinate on the page

Reload this command reloads the page or elements of a page

Set Variable this command sets one or more conversation variables

Submit Form this command submits the specified form

Swap Image this command changes one image to another image

Toggle CSS Classes this command toggles css classes for an element

Toggle Visibility this command toggles visibility of an element

Note

Refer to the Skyway Web Control Reference guide for detailed explanation of Skyway webcontrols, events and commands.

The easiest way to configure a Skyway web control with events and commands is to use the toolingprovided in Skyway Builder. The Events properties panel makes it very easy for a developer to wire eventsto client-side or server-side logic. The Events panel will only show events that are supported by the specificweb control being configured.

Figure 2.15. Events and Commands - Properties Panel

Alternatively you can use the Skyway JSP tags manually. The Skyway tag library descriptor (TLD)10 specifiesall the available tags and their attributes. This fragment of JSP code is intended to show the layering webcontrols, events and commands. The implementation details have been intentionally excluded.

10 http://www.skywayperspectives.org/fisheye/browse/~raw,r=1.1/CVS_OpenSource/skyway/common/execution/org.skyway.execution.web/src/META-INF/skyway.tld

Web Layer Recipes

48

Example 2.28. Event and Command - JSP Fragment

<skyway:button label="Click Here" type="submit">

<skyway:event event="onclick">

<skyway:submitform /> <skyway:loadurl /> </skyway:event></skyway:button>

<skyway:button> is the JSP tag for emitting a button web control. Events and commands are definedwithin the tag will be associated with the web control.<skyway:event> specifies that an event is being wired, and the specific event (onclick) is configuredusing the event attribute.<skyway:submitform> and <skyway:loadurl> are commands that are being wired to the event.

EXAMPLES

Here are some examples of using Events and Commands.

Figure 2.16. Events and Commands - 1 Event

In the first example, a Button is configured to invoke two commands in response to an onClick event. Thecommands will be executed sequentially from top-to-bottom.

Figure 2.17. Events and Commands - 2 Events

In this example, a Hyperlink is configured to respond to two events. The Change CSS Class commandwill be invoked in response to the onMouseOver event. The Load URL and Toggle Visibilitycommands will be invoked in response to the Hyperlink's onClick event.

RELATED RECIPES

1. Creating the View for Spring MVC

Web Layer Recipes

49

2. Using Javascript

3. Implementing Client-side Validation using Javascript

4. Publishing a AJAX service using DWR

27. Using Absolute Paths for Images, CSS andJavascript

PROBLEM

When referencing web application resources (URLs, images, css, javascript libraries, etc...) in a JSP page,the URL resources can be specified using absolute paths or relative paths. Absolute paths are fully-qualified URLs (i.e. http://www.myapp.com/context/js/myscript.js), and relative pathschange based on the location of the JSP that the URLs are included in. While relative paths are convenient,they can be difficult to manage when a JSP page can be accessed from different URLs. Relative pathspresume that a web application has a very flat or consistent url structure. While this might be the caseduring the initial stages of an application, this is rarely the case in later stages of an application. Skyway'sJSP tags automatically handle pathing issues, however this doesn't address the loading of auxilliaryresources, such as images, css, and javascript. Absolute paths are usually favored for referencing theseresources, but a developer may not necessarily know the path at design-time. Furthermore the path maychange as the application is deployed to different environments. A UI developer needs a way of specifyingan absolute path at design-time that will resolve to the appropriate URL at runtime

SOLUTION

JSP EL provides a variable (${pageContext.request.contextPath}) that can be used by UI developers atdesign-time to help resolve to the proper path at runtime.

HOW IT WORKS

The following JSP fragment shows the use of the variable for including a css library, including a javascriptlibrary, and including a image from image library.

Example 2.29. JSP Fragment using pageContext.request.contextPath variable forabsolute pathing

<link rel="STYLESHEET" type="text/css" href="${webContextRoot}/style.css"><script src="${pageContext.request.contextPath}/js/scriptaculous.js"></script><img src="${pageContext.request.contextPath}/images/logo.jpg">

The first HTML fragment shows how the pageContext.request.contextPath from JSP fragment is resolvedinto an absolute path. In this example, the application is deployed by an application developer to a localtomcat instance (http://localhost:8080/myapp/).

Example 2.30. HTML fragment with absolute pathing - deployed to http://localhost/myapp

<link rel="STYLESHEET" type="text/css" href="http://localhost:8080/myapp/style.css"><script src="localhost:8080/myapp/js/scriptaculous.js"></script><img src="localhost:8080/myapp/images/logo.jpg">

The second HTML fragment also shows how the pageContext.request.contextPath from JSP fragmentis resolved into an absolute path. In this example, the application is deployed to a production server(http://www.myapp.com/).

Web Layer Recipes

50

Example 2.31. HTML fragment with absolute pathing - deployed to http://www.myapp.com<link rel="STYLESHEET" type="text/css" href="http://www.myapp.com/style.css"><script src="http://www.myapp.com/js/scriptaculous.js"></script><img src="http://www.myapp.com/images/logo.jpg">

Regardless of where an application is deployed to, the pageContext.request.contextPath variable willresolve to a proper absolute URL. It can be used to prefex any URL that references external resources.

RELATED RECIPES

1. Using CSS

2. Using Javascript

3. Implementing Client-side Validation using Javascript

28. Using CSSPROBLEM

Cascading Style Sheets (CSS) is a language for describing how an application should formatted. Whilethere are a variety of options for formatting web pages, CSS is the pre-dominant choice because it's astandard supported by all modern web browsers, and it facilitates the separation of the structure of thepage and the presentation (or style) of the page.

SOLUTION

There isn't really any special considerations regarding using CSS with Skyway applications. CSS can beused in exactly that same manner as classic web development. Some approaches to using CSS include:

• Adding inline CSS to broadly format a web application or format specific sections of a web application.

• Defining CSS in separate stylesheet files (.css) that are linked into the JSP page

• Configuring web controls with a CSS class that will inherit the style defined elsewhere (inline CSS orstylesheet)

HOW IT WORKS

Most Skyway web controls have style properties panel that can be used to specify a CSS class and/orspecify an inline style. In the case of inline styles, at runtime the visual rendering of the web control willbe influenced by the embedded style.  In the case of class attributes, the visual rendering of the webcontrol (once again at runtime) will be influenced by a class definition.

When defining the inline style, you can specify the style information directly into the Inline Style sectionof the style panel. Alternatively you can click on the Style Editor button to configure the style using aspecialized CSS editor.

Web Layer Recipes

51

The following JSP fragment shows how external CSS files can be linked into a web application.

Example 2.32. Linking to external CSS files

<head><link href="${pageContext.request.contextPath}/css/styles.css" rel="stylesheet" type="text/css" /></head>

The link tag ( <link> ) is a standard html tag for linking a stylesheet to a source HTML document. Thehref attribute specifies the location of the stylesheet. Typically the stylesheet of a web application willbe located in the web application, and in the case of a Skyway project, the stylesheet will be addedsomewhere in the web content folder. The ${pageContext.request.contextPath} variable is a convenientway to reference at runtime the root context of the web applicaiton. Since in this example the css file wasadded to a "css" folder in the web content folder, the reference to the css folder is appended to the urlalong with the name of the css file.

Almost all of the sample projects on the Skyway Community site make use of CSS. Those projects wouldbe a good reference for best practices in using CSS within a web application.

Scaffolding Note

The Spring MVC scaffolding functionality uses CSS to control the layout and decorate of theapplication. If you want to see an example of using CSS in a Spring MVC application, it isrecommended that you explore an application created using Spring MVC scaffolding.

RELATED RECIPES

1. Using Absolute Paths for Images, CSS and Javascript

29. Using JavascriptPROBLEM

Most web applications make some use of javascript. Whether doing AJAX-based development, client-sidevalidation, or some other capability powered by javascript, a web application will more than likely needto include some third-party and custom javascript libraries.

SOLUTION

Javascript is added to Spring-based applications generated by Skyway Builder in the same manner as theyare added to any web application.

HOW IT WORKS

The javascript can be added inline, in which case it will be contained in the JSP files wrapped by the<script> tag.

Example 2.33. Inline javascript

<script type="text/javascript"><!--function helloWorld() { alert('Hello World!') ;}// --></script>

Web Layer Recipes

52

Third-party or custom Javascript libraries can be added to the web project, and they will be automaticallyincluded in the packaged/deployed application. It's up to the UI developer to reference (include) thejavascript libraries in the JSP page.

The steps for using a javascript library from within a JSP is:

1. Copy the files into the web project. The files can organized using whatever folder structure is desire.

2. Reference the files within the user interface by URL.

One of the web project folders that is automatically created with a new project is the "js" folder. Thisfolder is used to store the javascript files used by Skyway's web controls. In the folder there are threejavascript files. The prototype.js file is used to support Skyway's AJAX functionality, and the other twolibraries are light-weight javascript libraries from Skyway for bridging the prototype library with Skyway'sweb controls. If you have some additional 3rd party or custom javascript libraries that you want to includein the web application, you can add them to the js folder (or any folder for that matter) and load themfrom your web application.

For example if you add the script.aculo.us javascript library (scriptaculous.js) to the js folder in the webproject, the javascript library can be loaded into a JSP page using one of the following references:

Example 2.34. Linking to javascript libraries<script src="${pageContext.request.contextPath}/js/scriptaculous.js" type="text/javascript"/></script>

-or-

<skyway:javascript src="scriptaculous.js"></skyway:javascript>

The first example uses the standard html <script> tag, and the src is specified using the${pageContext.request.contextPath} variable along with the a reference to the "js" folder and thefilename. The second example uses the <skyway:javascript> JSP tag. The advantage of the JSP tag is thatyou only need to specify the name of the javascript file. The tag will automatically derive the URL fromthe context root (so there's no need to specify the ${pageContext.request.contextPath} variable), and itwill automatically look in the js folder.

RELATED RECIPES

1. Using Absolute Paths for Images, CSS and Javascript

2. Publishing a AJAX service using DWR

30. Securing Applications - AuthenticationPROBLEM

Web applications may provide services that need to be protected. To access protected services, a webapplication needs to verify the identity of the end-user.

SOLUTION

Authentication is the process of determining the identity of an end-user using authentication factors.For web applications authentication is typically done using a login process. Using a login form the end-user provides some credentials, such as a user name and password (two-factor authentication). Thecredentials are verified against a directory service, like LDAP. If the credentials are verified, the end-useris considered authenticated.

Web Layer Recipes

53

HOW IT WORKS

Skyway Builder Standard Edition11 enables developers to easily add security to an application. Security isimplemented using Spring's security module, appropriately named Spring Security.

Securing Project Resources

From the Enterprise Configuration tab on the Project Editor (Skyway Builder Standard Edition12) adeveloper can configure the URL patterns, services and data access objects that must be secured. Atruntime, whenever a requested URL matches one of the configured URL patterns, runtime componentsverify if a user has been authenticated, and if not, forwards the request to a view to collect the user'scredentials. Once the user has been authenticated, it proceeds to the original URL.

Figure 2.18. Security Settings using Spring Security

The views used for security functions, which are implemented as JSPs, can be customized or replacedaltogether. The security functions for which views can be configured include login, logout, and accessdenied.

11 http://www.skywayperspectives.org/portal/web/guest/products/builder/standard-edition12 http://www.skywayperspectives.org/portal/web/guest/products/builder/standard-edition

Web Layer Recipes

54

Figure 2.19. Security Settings - Configured Views

- Skyway security allows out-of-the-box configuration of the two most common security informationproviders: database and LDAP. In addition, it lets developers plug other security providers included inSpring Security, or their own custom providers by implementing a single method.

Figure 2.20. Security Settings - Security Information Source

Securing Services

Skyway operations can be invoked externally as Web services or native operations. External invocationson operations of a secured service are intercepted to ensure that the request contains authenticatedcredentials. If it does, the request is allowed to reach the operation. The authenticated credentials arepropagated transparently to external invocations during the operations execution chain within the sameproject. It is important to note that a service is secured only for external invocation; operation invocationswithin a project are not intercepted, since it's assumed that the developer secured the entry point.

Web Layer Recipes

55

Scaffolding Note

The Spring MVC scaffolding functionality in Skyway Builder Standard Edition13 will scaffold asecured application using Spring Security. If you want to see an example of implementing SpringSecurity in a Spring MVC application, it is recommended that you explore an application createdusing Spring MVC scaffolding.

RELATED RECIPES

1. Securing Applications - Authorization

31. Securing Applications - AuthorizationPROBLEM

Authentication is used to determine the identify of the user, however identifying the user isn't the onlyaspect of security. There needs to be a strategy for verifying that the user is authorized to access anapplication or perform a specific application function.

SOLUTION

Another aspect of security is authorization. Authorization is the process of verifying that an authenticateduser has the authority to perform certain functions. Skyway supports role-based authorization -- anauthenticated user has a set of roles that define which functions may perform. In Skyway, the applicationis responsible for authorizing. The alternative would be for the developer to declaratively designate whichroles can invoke certain operation. Letting the application authorize provides the maximum flexibility,since often times a function may not coincide with an operation. To support this kind of authorizationmodel, Skyway Builder provides the following functions that are callable from the Variable Editor stepand Groovy step:

Authorization Functions

• currentUser() - returns the name of the user currently authenticated, if any

• isAuthenticated() - returns whether a user is currently authenticated

• isInRole() -- returns whether the user currently authenticated, if any, has the given role

HOW IT WORKS

RELATED RECIPES

1. Securing Applications - Authentication

32. Validating End-User Input on Server using SpringValidator

PROBLEM

13 http://www.skywayperspectives.org/portal/web/guest/products/builder/standard-edition

Web Layer Recipes

56

Validation is a common part of a web application. As an end-user interacts with an application and submitsdata, the data needs to be verified that it conforms to pre-defined rules. While validation logic can be co-located with application logic, this limits the re-usability of application logic and pollutes the applicationlogic.

SOLUTION

There are multiple solutions to validation, and this solution is focussed on using Spring Validation. SpringValidation let's you define your validation logic in a java class that implements the Spring Validatorinterface. The class will contain one or more validation methods, and a particular method will specifythe validation logic for the set of data provided by the web client. Any identified validation errors will bereported back to the end-user.

The steps for configuring validation are:

1. Implement a validation class then extends org.springframework.validation.Validator(see example below)

2. Configure the URL Mapping to use the validation class and method (Data Validation) that should beused for the URL. Specify the page (Error View) that should be used if validation fails.

3. Add an input variable of type org.springframework.validation.BindingResult to theoperation that was configured for validation (see URL mapping from step 2)

HOW IT WORKS

When validation is configured using the steps above, Skyway Builder will emit the code into the controllermethod that calls the validation class. If the validation passes, the remainder of the operation logic willbe executed and the view specified in the URL mapping will be rendered. If the validation fails, the errorview specified in the URL mapping will be rendered.

The following validation example shows the implementation of a Spring validation class and method.

Web Layer Recipes

57

Example 2.35. Validation Class

package com.pam.web;

import org.springframework.validation.Errors;

import org.springframework.validation.ValidationUtils;import org.springframework.validation.Validator;

import com.pam.domain.Appraisal;

public class ValidateAppraisal implements Validator{

public boolean supports(Class clazz) { return clazz.equals(Appraisal.class); }

public void validate(Object command, Errors errors) {

Appraisal xyz = (Appraisal) command; ValidationUtils.rejectIfEmpty(errors, "employeeNo", "required.employeeNo",

"Employee number must not be empty."); }}

This Spring class stores validation errorsThis Spring helper class provides methods for rejecting empty fields.The class is the model object that incoming data is being bound to.A validator class must implement the Validator interface. To use this validator, you must specify thisclass name as a binding option in the Bind tab of URL Mapping editor.You can specify one or more validatation methods that perform validation logic. To use thisvalidation method, you must specify this method name as a binding option in the Bind tab of URLMapping editor.The command object must be cast to the model object.In addition to specifying validation logic through code, you can use some of the helper methodsthat are available in the ValidationUtils class.

Once the validation logic has been coded, the validation class can be used for a URL Mapping in the DataValidation tab of a URL Mapping.

Web Layer Recipes

58

Figure 2.21. Validation

The Spring Form tag library provides an errors tag to render the errors that were created in the validatorclass. The following block shows a partial listing of the edit.jsp page from the PAM tutorial.

Example 2.36. Using errors tag of the Spring Form Tag Library (edit.jsp)<%@ page language="java" isELIgnored="false" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><%@taglib uri="http://www.skywaysoftware.com/taglibs/core" prefix="skyway"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title><skyway:javascript src="prototype.js"/><skyway:javascript src="skyway-internal.js"/><skyway:javascript src="skyway.js"/></head><body><skyway:form action="${pageContext.request.contextPath}/AppraisalEntryController/ValidateAppraisal.action"

commandName="appraisal"> Employee No <skyway:input type="text" id="input_RVkXsl" designPath="PAM.AppraisalEntryController.ValidateAppraisal" path="employeeNo"></skyway:input>

<form:errors path="employeeNo" cssClass="error"/>

...full listing omitted for brevity

<skyway:button type="submit" label="Next" ></skyway:button> </skyway:form></body></html>

This is the JSP directive to include the Spring Form tag library.This is the URL that will be called when the form is submitted. The URL mapping associated withthis URL is configured to invoke a Validation class during data binding.The <form:errors> tag will display any validation errors.

Web Layer Recipes

59

RELATED RECIPES

1. Implementing Client-side Validation using Javascript

33. Implementing Client-side Validation usingJavascript

PROBLEM

Sometimes it is desirable to validate the end-users input on the browser using javascript.

SOLUTION

The solution is the same for any JSP web application. Embed or Include the javascript validation logic andconfigure a web control to invoke the validation javascript based on an end-user event.

HOW IT WORKS

Here's an example of a javascript function that can be added to a JSP. The JSP contains a form that needsto be validated. Rather than having a button that submits the form, the form can contain a button thatinvokes the javascript function, which implements the validation logic. Depending on the results of thevalidation logic, either the end-user will get an alert of the error or the form will be submitted to theserver.

Example 2.37. Sample client-side validation using javascript

<script type="text/javascript" language="javascript"> function validateMyForm() { if (document.forms[0].idfield.value == "") { alert('ID must not be blank'); return false; }

document.forms[0].submit(); } </script>

If you are using the form tags of the Skyway Builder tag library, you can use the Custom Script commandon the onclick event of a Skyway button.

Figure 2.22. Event and Commands

Web Layer Recipes

60

Scaffolding Note

The Spring MVC scaffolding functionality will scaffold an application that implements client-sidevalidation using Spring Javascript library with DOJO toolkit14 widgets. If you want to see an exampleof implementing client-side validation in a Spring MVC application, it is recommended that youexplore an application created using Spring MVC scaffolding.

RELATED RECIPES

1. Validating End-User Input on Server using Spring Validator

2. Publishing a AJAX service using DWR

34. Implementing File Upload for Spring MVCPROBLEM

Some Spring MVC applications have requirements to store file-based resources in a database, and oftenthese application needs a facility for uploading resources (i.e. images and documents) from a web-baseduser interface.

SOLUTION

The HTML FORM and INPUT elements are used to implement the user interface for uploading files. In anHTML form the ENCTYPE parameter determines how the form data is encoded, and for uploading filesthe value "multipart/form-data" should be used. For the INPUT element the type should be set to "file".While standard HTML works just fine, the Skyway tag library (Open Source: Apache License) includes aspecialized file upload web control.

With the user interface addressed by HTML and/or the Skyway tag library, the next component to addressis the backend logic. The Spring MVC application needs to be setup to handle the multipart data that isbeing sent from the UI. Fortunately Spring MVC has support for this in the form of MultiPartResolver andByteArrayMultipartFileEditor. In addition to bootstrapping a lof of the necessary Spring configuration tosupport file uploading, Skyway Builder also includes a custom resolver (Open Source: Apache License)that makes it easier to bind the file attributes (filename, file size, content type) to your domain model.

HOW IT WORKS

As mentioned earlier the first step is to implement the user interface for uploading content, and thefollowing list describe the details.

Implementing the file upload user interface

1. Update the ENCTYPE of the form to "multipart/form-data". This can be done in a form implementedusing the standard HTML FORM tag, the Spring Form tag, or the Skyway Form tag. [REQUIRED]

2. Add an HTML INPUT element with the TYPE attribute set to "file", and set the NAME attribute to thefield on your domain object (ModelAttribute) where the uploaded file should be stored. Please notethat the domain object itself is specified by the ModelAttribute parameter on the Spring Form orSkyway Builder form tags. [REQUIRED]

14 http://www.dojotoolkit.org/

Web Layer Recipes

61

3. Add one or more hidden form elements directing the backend MultiPartResolver to store the filename,the content type, and/or the file size in the domain object. The NAME must configured with a referenceto the name of the HTML INPUT element in step #2 and a suffix corresponding to the file attribute.The VALUE must be configured with the field on the domain object that should be set. Please notethat this step is only required if you also want to store the filename, the content type, and/or the filesize in your domain model. [OPTIONAL]

Table 2.5. File Upload Suffixes

Suffix Description

_contentTypeVar Reference to the file content type

_fileNameVar Reference to the filename

_sizeVar Reference to the file size

This following JSP fragment shows a typical file upload implementation using standard HTML, and itincludes the binding of file attributes to the domain model.

Example 2.38. File Upload - HTML

<form:form action="${pageContext.request.contextPath}/savePhoto.html"

method="POST" enctype="multipart/form-data" modelAttribute="photo" >

<input id="content" name="content" type="file"/>

<input type="hidden" name="content_contentTypeVar" value="contentType"/>

<input type="hidden" name="content_fileNameVar" value="filename"/>

<input type="hidden" name="content_sizeVar" value="contentSize"/> <input type="submit"/></form:form>

The encoding type is set to "multipart/form-data"The ModelAttribute is set to "photo". This is the object that will contain the file (byte array),filename, file size and content type for the uploaded file.This input html element will let the end-user select a file from their filesystem to upload. The file isbound to the content field (photo.content). In Skyway Builder this field is defined as a Large DataStorage type.This input html element will bind the content type to the contentType field (photo.contentType). InSkyway Builder this field is defined as a Text (String) type.This input html element will bind the file name to the filename field (photo.filename). In SkywayBuilder this field is defined as a Text (String) type.This input html element will bind the file size to the contentSize field (photo.contentSize). In SkywayBuilder this field is defined as a Integer type.

The following JSP fragment shows a file upload implementation using the File Upload web control fromthe Skyway TagLib. The html rendered the file upload web control will render the HTML describedpreviously.

Web Layer Recipes

62

Example 2.39. File Upload - Upload Web Control (Skyway TagLib)

<form:form action="${pageContext.request.contextPath}/savePhoto.html"

method="POST" enctype="multipart/form-data" modelAttribute="photo" > <skyway:binaryUpload controller="" designPath="" path="content" contentTypeBinding="contentType" fileNameBinding="filename"

sizeBinding="contentSize"> </skyway:binaryUpload> <input type="submit"/></form:form>

The encoding type is set to "multipart/form-data"The ModelAttribute is set to "photo". This is the object that will contain the file, filename, file sizeand content type for the uploaded file.The JSP tag will emit the html for storing the file, filename, file size and content type into therespective fields on the photo modelAttribute.

Skyway Builder already bootstraps the Spring MVC application to support file uploads, so there is zeroconfiguration required by the developer. The following list describes the relevant configurations that areautomatically bootstrapped by Skyway Builder.

Bootstrapping of File Upload Support

1. A multiPartResolver is registered. See the generated web context file (projectName-generated-web-context.xml).

2. A ByteArrayMultipartFileEditor property editor is registered. See the initBinder() method in ascaffolded or generated controller.

The only responsibility of the developer is to implement a request handler (Controller Operation) thataccepts the domain object as an input. The input variable should match the ModelAttribute parameterthat was specified in the Spring or Skyway Form tag. Typically you will implement the backend first, andthen develop the UI that binds data to the backend. When the end-user of the application posts a form tothe request handler, the file is stored in the domain object field specified by the html (i.e. photo.content).The size, type, and filename are optionally stored in the domain object fields specified by the html, if theoptional hidden form fields are included.

Data Storage Note

Here are the recommended data types that should be used for storing the file contents andattributes:

1. File content - Large Data Storage (byte array)

2. Filename - Text (String)

3. File Size - Integer (Integer)

4. Content Type - Text (String)

RELATED RECIPES

1. Implementing File Upload for Spring Web Flow

2. Streaming binary content

Web Layer Recipes

63

35. Implementing File Upload for Spring Web FlowPROBLEM

In the event that an application is implemented using Spring Web Flow, there needs be a way toimplement file uploads that doesn't resort to using Spring MVC.

SOLUTION

The HTML FORM and INPUT elements are used to implement the user interface for uploading files. Inan HTML form the ENCTYPE determines how the form data is encoded, and for uploading files the value"multipart/form-data" should be used. For the INPUT element the type should be set to "file".

With the user interface addressed by HTML, the next component to address is the backend logic. TheSpring Web Flow application needs to be setup to handle the multipart data that is being sent fromthe UI. Spring supports this with a MultiPartResolver, and Skyway Builder projects are automaticallybootstrapped to with the MultiPartResolver configured.

HOW IT WORKS

As mentioned earlier the first step is to implement the user interface for uploading content, and thefollowing list describe the details.

Implementing the file upload user interface

1. Update the ENCTYPE of the form to "multipart/form-data". This can be done in a form implementedusing the standard HTML FORM tag, the Spring Form tag, or the Skyway Form tag. [REQUIRED]

2. Add an HTML INPUT element with the TYPE attribute set to "file", and set the NAME attribute to thevariable where the uploaded file should be stored. [REQUIRED]

This following JSP fragment shows a typical file upload implementation using using the Spring Form tagand standard HTML elements.

Example 2.40. File Upload - HTML

<form:form modelAttribute="photo" enctype="multipart/form-data" >

<input id="multipartFileUpload" name="multipartFileUpload" type="file" value="" /> <input name="_eventId_save" type="submit" id="save" value="Save" align="right"> <input type="submit" id="cancel" name="_eventId_cancel" value="Cancel"></form:form>

The ModelAttribute is set to "photo". While you may ultimately want to store the file (and it's relatedattributes) in this variable, this won't occur automatically. On the server you will need to individuallyset the variable attributes using the file data from the "multipartFileUpload" request parameter.The encoding type is set to "multipart/form-data"This input html element will let the end-user select a file from their filesystem to upload. The file isbound to a request parameter called "multipartFileUpload".

Skyway Builder already bootstraps the Spring Web Flow application to support file uploads, so there iszero configuration required by the developer. The following list describes the relevant configurations thatare automatically bootstrapped by Skyway Builder.

Bootstrapping of File Upload Support

1. A multiPartResolver is registered. See the generated web context file (projectName-generated-web-context.xml).

Web Layer Recipes

64

Below is the snippet from the Spring Web Flow XML document. This snippet sets up the flow andprocesses the save request.

Example 2.41. Spring Web Flow Configuration

<view-state id="EditImage" model="photo" > <transition on="save" to="ListImages">

<evaluate expression="ImageService.saveImage(photo, requestParameters.multipartFileUpload)" result="" result-type=""/> </transition> <transition on="cancel" to="ListImages"/> </view-state>

The model variable for the view state is set to photo.The evaluate expression is passing the photo variable and multipartFileUpload request parameterto a service.

The only responsibility of the developer is to implement the service operation (i.e.ImageService.saveImage()) that accepts both the domain object (photo) and multipartFileUpload(org.springframework.web.multipart.MultipartFile) as input parameters. In the implementation ofoperation you can extract set the domain object with the individual properties from the file(MultipartFile).

Example 2.42. Accessing MultipartFile

photo.setContent(multipartFile.getBytes());photo.setContentSize(new Long(multipartFile.getSize()).intValue());photo.setContentType(multipartFile.getContentType());photo.setFilename(multipartFile.getOriginalFilename());

Data Storage Note

Here are the recommended data types that should be used for storing the file contents andattributes:

1. File content - Large Data Storage (byte array)

2. Filename - Text (String)

3. File Size - Integer (Integer)

4. Content Type - Text (String)

RELATED RECIPES

1. Implementing File Upload for Spring MVC

2. Streaming binary content

36. Streaming binary contentPROBLEM

Many web applications need to stream binary content that is either stored in a database or generateddynamically. As demonstrated in the Implementing File Upload for Spring MVC and Implementing File

Web Layer Recipes

65

Upload for Spring Web Flow recipes, binary content can be uploaded to a web application. The binarycontent will typically also need to be displayed or be downloaded. For example if you are uploadingpictures to store them in a database, then you will likely need to render the photos in the web applicationusing the img tag. If you are uploading documents to store them in a database, you will likely need todownload the documents using an html anchor. In both cases you need a way to stream binary content.

SOLUTION

In order to facilitate the streaming of binary content in a Spring web application, Skyway Builderautomatically registers a view that contains logic for streaming binary content to a browser.

HOW IT WORKS

The view is automatically registered under the id of streamedBinaryContentView with the class oforg.execution.web.binary.ModelAttributeStreamer (open source: Apache license) in the web contextfile.

Example 2.43. Spring Context file - projectName-generated-web-context.xml

<bean id="streamedBinaryContentView" class="org.execution.web.binary.ModelAttributeStreamer" />

Setting the view for a URL mapping to streamedBinaryContentView will enable the output of theoperation (domain object) to be streamed to the web browser. When accessing a URL that is mapped tothe streamedBinaryContentView, there are some URL parameters that will dictate which attributes of theoutput domain object should be interpretted as the content, filename, and content type.

Table 2.6. URL parameters for streamedBinaryContentView

Parameter Description

__varpath Reference to the field that contains the actual byte array that should bestreamed (i.e. __varpath=photo.content)

__filename Reference to the field that contains the filename (i.e.__filename=photo.filename)

__contenttype Reference to the field that contains the content type (i.e.__contenttype=photo.contentType)

Here's an example of streaming an image.

Example 2.44. Image Streaming Example - output only

<img src="${pageContext.request.contextPath}/getImage.html ?id=$__varpath=photo.content

&__filename=photo.filename

&__contenttype=photo.contentType">

The URL (/getImage.html) is mapped to a controller method that outputs a domain object calledphoto. The view for the URL mapping is configured to streamedBinaryContentView.The URL parameter __varpath specifies that the content field contains the byte array that shouldbe streamed.The URL parameter __filename specifies that the filename field contains the filename.The URL parameter __contenttype specifies that the contentType field contains the content type.

If your controller method (operation) has an input variable that's needed for loading or generating thebinary content, you can specify additional URL parameters corresponding to the input parameters. Forexample the operation may contain an input variable called id (type=text) that is used as the key forloading a photo from the database that should be streamed to the browser.

Web Layer Recipes

66

Example 2.45. Image Streaming Example - with inputs

<img src="${pageContext.request.contextPath}/getImage.html?id=${photo.id} &__varpath=photo.content &__filename=photo.filename &__contenttype=photo.contentType">

If your application is generating documents or storing documents in a database, you may want to let theend-user download the documents. The following example shows how you can link to streamed binarycontent by specifying a streaming URL for the href of an html anchor.

Example 2.46. Document Streaming Example - with inputs

<a href="${pageContext.request.contextPath}/getDocument.html?id=${doc.id} &__varpath=doc.content &__filename=doc.filename &__contenttype=doc.contentType">Download</a>

Scaffolding Note

If you scaffolded a domain object that contains a field for storing binary content (Large DataStorage), the select controller operation (i.e. SelectDocument) can be used for streaming binarycontent. Just add a another URL mapping that points to the same operation, but set the view forthe new URL mapping to streamedBinaryContentView.

RELATED RECIPES

1. Implementing File Upload for Spring Web Flow

2. Implementing File Upload for Spring MVC

67

Chapter 3. Service Layer RecipesThe service layer, also referred to as the business layer, encapsulates the course-grained functionality ofthe application being built. The web layer is the primary consumer of the service layer, and the artifactsfor defining the service layer in Skyway Builder are the Services, Operations, Actions, and Steps.

1. Creating a Service or Business FacadePROBLEM

The logic found in a typical web application is associated with either (a) the behaviour of the applicationor (b) the business logic. While a Controller and associated Actions can be used to implement the boththe behavior and business logic, the MVC pattern prescribes that the controller layer should be focussedon implementing the behaviour of the application, and the service layer focusses on implementing thebusiness logic.

SOLUTION

The Service layer represents the core functionality of the application being built, and the functionalityrepresented by this layer is accessed in an API type manner using structured inputs and outputs. A SkywayService is an artifact that defines a set of functions. Functions are application logic that use structuredinputs and outputs for exchanging data. In Skyway development the functions are defined as Operations,and the logic is implemented using Actions.

HOW IT WORKS

Skyway Builder has adopted the SOAP lexicon (services and operations) for describing and implementingthe Service layer of an application. This doesn't mean that web services are being used for invocation.Skyway will use java invocation by default. However Skyway Services can also be exposed as web servicesby configuration, in which case the Skyway Service concepts map exactly to the equivalent web serviceconcepts.

Steps for creating a Service:

1. Right click on a Model Package, and select New-->Service.

2. From the New Skyway Service Wizard, enter a common name for the service. The common name isused to reference the service from other artifacts.

3. When done, click Finish to open the Service Editor.

RELATED RECIPES

1. Creating a Service Operation

2. Creating an OperationPROBLEM

A service defines a set of related functions, called Operations that define the specific functions of a Serviceand the implementation.

SOLUTION

Service Layer Recipes

68

Service functions are specified as Operations, which represent stateless application logic. In additionto a name and description, the operation definition consists of an operation interface and operationresources. The application logic of an operation is implemented using a sequence of Actions, whichrepresent a single thread of execution.

The operation interface defines the formal contract between the operation and the consumers of theoperation, which consists of an operation name, inputs, outputs, and exceptions.

Operation resources are the set of resources needed in an operation to implement the desiredfunctionality. Operation resources are not part of the operation interface, and the consumers of theoperation don't have any visibility into the operation resources.

HOW IT WORKS

Operation Interface

The operation name is the name that consumers use to refer to the operation; a general guideline isto define Operations using a functional verb and noun expression. This usually is a great starting pointfor determining the appropriate level of granularity, and the consumers of the Operation more easilyunderstand the specific functionality provided by the Operation.

Inputs are a mechanism for exchanging data with the consumer of the operation, and they define partof the operation contract. When a consumer calls an operation, they must provide all the input variablesdefined by the operation. Input variables are exactly like operation variables, which means any actionsteps may access the input variable the same way they access operation variables.

Outputs are another mechanism for exchanging data with the consumer of the operation, and theyalso define part of the operation contract. When a consumer calls an operation, they must accept allthe output variables defined by the operation. Output Variables cannot be manipulated directly by theOperation steps. The output variables are assigned their value by selecting the Assigned To value on theOutput sub-tab. Any variable from either the Variables tab or Inputs tab can be assigned to the outputvariables.

Exceptions defines exceptions that can be exposed by the operation. If any exception occurs and it is notlisted in the operation interface, the exception will be ignored.

Operation Resources

The variables defined in an Operation are available to all actions in the operation. These variables areused to store data needed by the Operation. Operations are stateless, so the scope of operation variablesis limited to operation invocation. Operation variables aren't maintained across calls.

Operation variables are declared to hold:

• Scalar data; basic data types (i.e. Integer, Text, Boolean, etc...)

• Collection of scalar data

• Domain Objects (i.e. domain objects created in Skyway, java beans, etc...)

• Collection of domain objects

An operation constant is a fixed variable whose value is defined at design-time. An operation constantfunctions like Project constants and Model constants, except the operation constants are only accessibleto operation actions. This is a great place to keep constants that are only needed in the operation.

Service Layer Recipes

69

The application logic for an operation is implemented using Actions. The Entry Point Action representsthe starting point of the operation. An operation will consist of at least one or more Actions, and theoperation must be configured with the Action that should be called first upon invocation of the operation.

Steps for creating an operation:

1. Right click the on a Service, and select New-->Operation.

2. From the New Operation Wizard, enter a common name for the operation. The common name is forreferencing the operation from other artifacts.

3. Click Next to configure the Entry Point Action. From here you can specify whether an entry pointaction should be created to implement the operation. If so, you can also specify the action name(default: Default Action).

4. When done, click Finish to open the Operation Editor

5. From the Operation Editor you can add Inputs, Outputs, Variables and Constants to the Operation.

RELATED RECIPES

1. Creating a Service or Business Facade

2. Implementing an Operation using Actions and Steps

3. Using Java Code, Spring Beans and Groovy with Services

3. Implementing an Operation using Actions and StepsPROBLEM

An operation defines an operation interface (inputs and outputs) and operation resources (variablesand constances) for implementing a Service function. The Spring annotated code and configurationsfor the operation are generated by Skyway Builder according to it's definition, but the logic still needsto be implemented. At this point the developer has benefited greatly from code generation, but codegeneration shouldn't stop short of implementing the real business logic.

SOLUTION

A developer can implement the logic of an operation using a sequence of Actions, which represent asingle thread of execution.

HOW IT WORKS

Actions implement the logic of an operation, and Skyway Builder enables a Action to be implementedusing a model-based approach, that defines the logic to be performed by configuring and sequencing oneor more Skyway Steps together.

Operation actions are implemented just like Actions in the web layer.

RELATED RECIPES

1. Implementing Controller Methods using Actions and Steps

Service Layer Recipes

70

2. Using Java Code, Spring Beans and Groovy with Services

3. Using Java Code, Spring Beans and Groovy with Services

4. Using Groovy in Actions

4. Creating a Contract-First JAX-WS Web service(SOAP)

PROBLEM

When designing a system that consists of multiple applications communicating with each other usingweb services, it is common to use contract-first development as way of defining the messages that willbe handled between systems. This includes identifying the operations themselves, including the inputand output parameters. This is cummulatively referred to as the contract, and it's defined as a WSDLdocument. When it comes time to build the systems, the applications must produce services accordingthe predefined contract.

SOLUTION

Skyway Builder Web Services Edition1 can be used to implement a web service contract. Skyway Builderwould discover the WSDL for the purposes of implementing the service. This is of course different thandiscovering the web services for the purposed of consuming the services as described in the ConsumeWeb Services.

HOW IT WORKS

There are four steps to contract-first JAX-WS service development.

Steps for creating a contract-first JAX-WS service:

1. Define the contract using WSDL (beyond the scope of this recipe)

2. Import the WSDL. Upon completion of the import process, Skyway Builder will have generated SpringDSL artifacts corresponding to the imported WSDL.

3. implement the Spring DSL services (see service implementation options)

4. Publish the service as a JAX-WS service.

The second step is the only step that is unique to contract-first development. The following table showsthe correlation between WSDL components and Spring DSL artifacts.

Table 3.1. Web Service WSDL to Skyway Mappings

WSDL Component Spring DSL Artifact Description

WSDL Document Service The entire WSDL document represents a Service,and a Skyway Service will be created to representthe imported service.

1 http://www.skywayperspectives.org/portal/web/guest/products/builder/web-services-edition

Service Layer Recipes

71

WSDL Component Spring DSL Artifact Description

WSDL Complex Types Domain Objects Skyway domain objects will be automaticallycreated for any complex types defined in theWSDL that are needed to interact with the service.

WSDL Operations Operations A Skyway operation will automatically be createdfor each operation defined in the WSDL. Theseoperations are what a Skyway Builder applicationwill use to invoke the functionality of the service.

Here are the steps for importing a WSDL.

Steps for importing a WSDL:

1. Open the Project editor and click on the Import Web Service under Activities.

2. From the Import WSDL Document wizard, specify the Model Package that should be used as the TargetPackage. The Spring DSL artifacts derived from the WSDL will be created in the selected package.

3. Specify the location of the WSDL (WSDL Location) that contains the specifications (contract) of theservices and operations that need to be implemented. You can specify the WSDL URL or select theWSDL from the file system.

4. Click Finish.

RELATED RECIPES

1. Publishing a JAX-WS Web service (SOAP)

2. Consuming a SOAP Web service

3. Consuming a REST Web Service

5. Publishing a JAX-WS Web service (SOAP)PROBLEM

A Spring DSL service may need to be JAX-WS enabled.

SOLUTION

Skyway Builder Web Services Edition2 has some accelerators for exposing the Spring DSL Services andOperations as JAX-WS web services. This makes it very easy to make the functionality of Spring Servicesaccessible to other systems.

In the context of contract-first and contract-last development, in both cases there's a WSDL that definesthe contract of the service. The only difference in contract-first development is that the WSDL was createdfirst and the development artifacts were generated from them. Regardless of whether you implementedyour service using a predefined service contract or not, the process for web service enabling the serviceis the same.

HOW IT WORKS

2 http://www.skywayperspectives.org/portal/web/guest/products/builder/web-services-edition

Service Layer Recipes

72

The Spring DSL has adopted the SOAP lexicon of services and operations, but that doesn't mean that theservices are automatically exposed as SOAP services for invocation. The decision of exposing applicationlogic as SOAP web services is left to the developer to decide based on their requirements.

Steps for publishing a JAX-WS service:

1. Open the Service editor for the Spring DSL Service that needs to web service enabled and switch tothe JAX-WS tab.

2. Click on the Synchronize button to refresh the web service meta-data from the Spring DSL servicemeta-data.

3. Under Web Service Details, check the Publish Web Service option.

4. Deploy your application, and the service will be available as a SOAP service using JAX-WS.

The web service is preconfigured using common web service conventions for the service, operations andparameters, but the JAX-WS tab allows every option to be reconfigured. By default all the Operationsin the Service are web service enabled. If you want to exclude certain operations, you can highlight theoperation in the JAX-WS tab and check the "Exlude" option.

The WSDL for the service is dynamically generated, and the URL for the WSDL is http://server:port//context/jaxws/endpoint?wsdl

• server - the name of the server hosting the web service (i.e. localhost or www.mycompany.com)

• port - the TCP/IP port number of the hosted web service (i.e. 8080)

• context - the context name of the application; the root context for the application hosting the service(i.e. myapp-Web)

• endpoint - the address of the service endpoint (the address is found in the jaxws-web-context.xml)

RELATED RECIPES

1. Creating a Contract-First SOAP Web service

2. Consuming a SOAP Web service

3. Publishing a AJAX service using DWR

4. Consuming a REST Web Service

6. Publishing a AJAX service using DWRPROBLEM

Rich Internet Applications (RIA) are applications that resemble desktop applications, and there area variety of technologies for implementing RIAs. Independent of the framework or toolkit used forimplementing the front-end of an RIA, all RIA applications need to access logic and/or databases thatreside on the server. There needs to be mechanism to easily publish a Spring DSL service in a format thatcan be consumed by RIAs.

SOLUTION

Service Layer Recipes

73

Skyway Builder Web Services Edition3 has some accelerators for exposing the Spring DSL Services andOperations as DWR services. DWR4 is "a Java library that enables Java on the server and JavaScript in abrowser to interact and call each other as simply as possible". The DWR functionality in Skyway Buildermakes it very easy to make the functionality of Spring Services accessible to RIAs.

HOW IT WORKS

The Spring DSL services aren't automatically exposed as DWR services. The decision of exposingapplication logic as DWR services is left to the developer to decide based on their requirements.

Steps for publishing a DWR service:

1. Open the Service editor for the Spring DSL Service that needs to DWR enabled and switch to the DWRtab.

2. Click on the Synchronize button to refresh the DWR service meta-data from the Spring DSL servicemeta-data.

3. Under DWR Service Details, check the Publish option.

4. Deploy your application, and the service will be available as a DWR service.

The web service is preconfigured using common conventions for the service and operations, but the DWRtab provides some configuration options. By default all the Operations in the Service are published withDWR. If you want to exclude certain operations, you can highlight the operation in the DWR tab and checkthe "Exlude" option.

DWR will automatically generates some pages that can assist in developing with DWR. The DWR Serviceindex page lists all the classes known to DWR. It's usefull for verifying which Spring DSL services are or arenot DWR enabled. The URL for the accessing the index page is http://server:port//context/dwr/index.html

Figure 3.1. DWR Service - Index Page

Each service listed on the index page includes a hyperlink to access the DWR Service details page. Thedetails page lists the script includes needed to use the DWR-enabled service from javascript. The nameof the javascript file is specified by the DWR configuration in the DWR tab. The details page also includea listing of all available javascript methods. There should be a javascript method for every operation inthe DWR-enabled service that wasn't configured to be excluded. Beside each javascript function there isan "Execute" button that can be used for testing client/server communication prior to building the front-end that used javascript functions..

3 http://www.skywayperspectives.org/portal/web/guest/products/builder/web-services-edition4 http://directwebremoting.org/

Service Layer Recipes

74

Figure 3.2. DWR Service - Service Details Page

RELATED RECIPES

1. Creating a Contract-First SOAP Web service

2. Consuming a SOAP Web service

3. Consuming a REST Web Service

7. Consuming a SOAP Web servicePROBLEM

With the adoption of SOA-based solutions and the increase use of cloud-based services, web servicesare becoming a very common way of exposing application functionality to other systems. SOAPis a web services protocol for exchanging XML-based messages between systems. Web ServicesDescription Language (WSDL), a component of SOAP, is used for describing services of the originatingsystem ("producer") in XML format. A WSDL contains everything needed by a web service consumer("consumer") to access the functionality of the service, including the location (URI) of the service, a listof available operations, the required inputs/outputs for each operation, and a definition of any complextypes used by the services.

SOLUTION

There are many ways that applications developed with Skyway Builder can leverage functionality ordata of other systems. If the functionality is available as SOAP-based web services, Skyway Builder WebServices Edition5 can invoke those services as easily as if the functionality had been implemented nativelyusing Skyway Builder. Typically a WSDL document (XML) is used to communicate the availability, contractand location of a system's web services. Skyway Builder will discover (or learn about the existenceof) these services by the developer importing the WSDL document. As part of the discovery process,modelling artifacts corresponding to the web services defined in the WSDL will be added to the project.These modelling artifacts can then be used to access the functionality of the services.

5 http://www.skywayperspectives.org/portal/web/guest/products/builder/web-services-edition

Service Layer Recipes

75

Web services are often used as an integration technology, where the application being produced needsto leverage the functionality of another system. On the other hand, composite applications integratewith services from a variety of systems, as is typically the case in SOA environments. The service layerof a composite application may be entirely implemented by other systems, in which case the compositeapplication only implements the user interface and behavior of the application.

HOW IT WORKS

The process for consuming web services in Skyway Builder Web Services Edition6 is to import the service.From the Overview tab of the Project Editor, click on the Import Service hyperlink. The Import WSDL Filewizzard will prompt you for the WSDL. You can either specify a URL or load a WSDL from the file system,and then click "Finish". Skyway Builder will parse the WSDL and create model based artifacts from theWSDL components.

Steps for consuming a web service:

1. Open the Project editor and click on the Import Web Service under Activities.

2. From the Import WSDL Document wizard, specify the Model Package that should be used as the TargetPackage. The Spring DSL artifacts for accessing the web services defined in the WSDL will be createdin the selected package.

3. Specify the location of the WSDL (WSDL Location) that defines the web services that will be consumingfrom your application. You can specify the WSDL URL or select the WSDL from the file system. ClickFinish.

4. If using MDD, you can call the web service from an Action using the Invoke Web Service step. If not,you can use the service client that was generated.

RELATED RECIPES

1. Consuming a REST Web Service

2. Creating a Contract-First SOAP Web service

3. Publishing a JAX-WS Web service (SOAP)

8. Consuming a REST Web ServicePROBLEM

Representation State Transfer (REST) is a lite-weight approach for communicating with other applicationsusing HTTP and XML. While SOAP let's you define your own operations, with REST services there areessentially only four operations: GET, POST, PUT and DELETE. Given it's simplicity, REST services arebecoming very popular building block on web applications.

SOLUTION

Since REST focusses on HTTP and XML, there isn't a need for any specialized java libraries foraccessing REST services. The JAVA platform already has the basic libraries in place for handling HTTPrequests (java.net.* or org.apache.commons.httpclient.*) and processing XML (JAXP). Therefore nothingadditional is required.

6 http://www.skywayperspectives.org/portal/web/guest/products/builder/web-services-edition

Service Layer Recipes

76

As far as consuming REST services from Spring applications, and in particular applications produced withSkyway Builder, the standard HTTP and XML processing logic available to java developers can be used. Adeveloper can write java code and/or Spring beans for making the REST calls and processing the results.Additionaly a developer can leverage the Groovy support in Skyway.

HOW IT WORKS

Here's an example java class that calls a REST service using Apache commons httpclient library.

Example 3.1. Sample java code invoking REST servicesimport java.io.*;

import org.apache.commons.httpclient.*;import org.apache.commons.httpclient.methods.*;

public class SampleWebServiceGet {

public String callRestService(String request) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(request); // Send GET request int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } InputStream rstream = null; // Get the response body rstream = method.getResponseBodyAsStream(); // Process the response BufferedReader br = new BufferedReader(new InputStreamReader(rstream)); String line; while ((line = br.readLine()) != null) { } br.close(); return line; }

}

The following snippet of Groovy code is used to call a REST service.

Example 3.2. Sample Groovy code invoking REST services"http://www.myapp.com/service/REST/get".toURL().text

RELATED RECIPES

1. Consuming a SOAP Web service

2. Creating a Contract-First SOAP Web service

3. Creating a Model-First SOAP Web service

9. Using Java Code, Spring Beans and Groovy withServices

See Blending Actions with non-generated Java Code and Blending Actions with non-generated SpringBeans.

Service Layer Recipes

77

10. Using Groovy in ActionsPROBLEM

The use of dynamic languages are becoming very popular in Java, and Groovy is becoming thepredominant choice. Besides supporting the dynamic invocation of java code, Groovy also adds additionalfunctionality to makes things easier to do with Java. While Skyway supports the Blending Actions withnon-generated Java Code and Blending Actions with non-generated Spring Beans, the ability to leverageGroovy provides additional options to application developers.

SOLUTION

Skyway Builder offers support for Groovy through the Invoke Groovy Step. Using Spring’s prescribedapproach of dynamic language integration7, the Groovy script is maintained externally from the Java codeand wired-in (injected) using Spring’s <lang:groovy> element.

HOW IT WORKS

The Invoke Groovy Step can be added to an Action to perform Groovy-based processing. Typical uses ofthe Invoke Groovy Step are to

• call java functionality from third-party java libraries

• process the results of web services

• perform mathematical functions

• processing XML using Groovy's special XML processing support (XMLParser, XMLSlurper)

• prototyping functionality that will eventually be moved to a java class or Spring bean

• debugging and logging

Here's an example of some Groovy code that's used in GetFlickrContent operation of the the FlickrViewersample project8. In addition to using standard java code, the Invoke Groovy step also supports theadditional functionality provide by Groovy's. The follow snippet shows the use of Groovy's special XMLprocessing support (XMLParser).

Example 3.3. Using Groovy Code using Invoke Groovy Step

System.out.println("inFeed: "+inFeed);def xmlFeed = new XmlParser().parse(inFeed);def idx = 0;xmlFeed.channel.item.each { item ->idx++;def title = item.title.text()currentEntry = new flickrviewer.domain.Entry();currentEntry.id = idx;currentEntry.flickrlink = item.link.text()currentEntry.imagelink = item.media.'@url'.text()System.out.println("DEBUG: "+item.'media:content'.text());currentEntry.title = item.title.text()currentEntry.content = item.description.text()System.out.println("Title: "+currentEntry.title);System.out.println("Link: "+currentEntry.imagelink);entries.add(currentEntry);}

7 http://static.springframework.org/spring/docs/2.0.x/reference/dynamic-language.html8 http://www.skywayperspectives.org/portal/web/guest/185

Service Layer Recipes

78

RELATED RECIPES

1. Using Groovy in Actions

2. Accessing Data using Groovy

11. Accessing Data using GroovyPROBLEM

There is plenty information regarding the use of Groovy on the Groovy website and in various Groovybooks. In most cases a developer using Groovy with Skyway Builder will want to interact with the data(stored in variables) that exists in the respective component. For example if a developer is using Groovyin the implementation of a Controller, she's likely going to need to access the model variables. If thedeveloper is using Groovy in the implementation of an operation, she's likely going to need access toinput, output, and operation variables.

SOLUTION

Since the Skyway modeling artifacts are being generated to standard java code, there really isn't anythingspecial with accessing data access objectd in variables from the Invoke Groovy Step. Variables within therepsective components are implicitly accessible to the Invoke Groovy Step.

HOW IT WORKS

Here's an example of some Groovy code that's accessing operation variables. There are several variablesdefined in the GetFlickrContent operation of the the FlickrViewer sample project9.

Figure 3.3. Accessing Variables using Groovy

As shown in the following code that's used in the Groovy step, the service variables are natively availableto the Groovy script.

9 http://www.skywayperspectives.org/portal/web/guest/185

Service Layer Recipes

79

Example 3.4. Accessing data using Groovy

System.out.println("inFeed: "+inFeed);

def xmlFeed = new XmlParser().parse(inFeed);def idx = 0;xmlFeed.channel.item.each { item ->idx++;def title = item.title.text()

currentEntry = new flickrviewer.domain.Entry();currentEntry.id = idx;currentEntry.flickrlink = item.link.text()currentEntry.imagelink = item.media.'@url'.text()System.out.println("DEBUG: "+item.'media:content'.text());currentEntry.title = item.title.text()currentEntry.content = item.description.text()System.out.println("Title: "+currentEntry.title);System.out.println("Link: "+currentEntry.imagelink);

entries.add(currentEntry);}

inFeed is an operation input variablecurrentEntry is an operation variable (type = Entry)entries is an operation variable that stores of collection of entry objects (type = Entry)

RELATED RECIPES

1. Implementing Controller Methods using Actions and Steps

2. Using Groovy in Actions

3. Accessing Data using Groovy

80

Chapter 4. Data Layer RecipesThe data layer is also referred to as the persistence layer or domain object layer. The data layer isrepresented by a domain model; a distinct set of inter-related application objects that embody thefunctionality and characteristics of the system being built. This layer also encompasses the persistenceof the domain model to and from a database.

The tools for defining the data layer in the Spring DSL are the Domain Object and Data Access Objectartifacts, and they will be described in detail in a following chapter.

1. Creating a Domain Object / POJO / JavaBeanPROBLEM

For application frameworks like the Spring Framework that utilizes plain old java objects (POJO), thereneeds to be a easy way of creating POJOs.

SOLUTION

A Domain Object is a Spring DSL artifact that defines the domain model of the application. By defaulta domain object is generated into a plain old java object (POJO). If a domain object is associated witha data access object, then the domain object is annotated as an @Entity (JPA) annotated class, and it'sassociated with a primary key class (@IdClass). Fields can be added to domain objects by using the basicdata types, and a domain object can have relationships to other domain objects.

HOW IT WORKS

All applications work with data, and domain objects specify the kind of data that can be stored andmanipulated within a program. Skyway supports a number of fundamental basic data types (scalar datatypes), which are the simplest data types in a Skyway application.

The following table lists the basic data types supported.

Table 4.1. Skyway Basic Data Types

Name Description

ID java.lang.String

Text java.lang.String

Integer java.lang.Integer

Decimal java.math.BigDecimal

Date and Time java.util.Calendar

Boolean java.lang.Boolean

Large Text java.lang.String

Date java.util.Calendar

Map java.util.HashMap

Time java.util.Calendar

Picture Java Byte Array

Data Layer Recipes

81

Name Description

Large Data Storage Java Byte Array

Skyway Domain Objects are used to define objects. As described in the Spring DSL model, domain objectscan be created in model packages.

Steps for creating a Domain Object:

1. Right click on a Model Package, and select New-->Domain Object to open the New Domain ObjectWizard.

2. From the New Domain Object panel, enter a name for the domain objectl. Click Finish to open theDomain Object Editor.

3. From the Domain Object Editor add fields to the domain object. A field consists of a field name andfield type. You can also specify whether the field is a collection and a primary key.

4. You can also relate the current domain object to other domain objects by adding relationships.

This figure shows a domain object being defined in Skyway Builder. Attributes were added as fields. Foreach field you can specify the type (Text, Integer, etc..) and whether it's a collection. You can also specifywhich attribute(s) uniquely identify the object from other objects of the same type.

Figure 4.1. Creating a domain object using Domain Object Editor

This is an example of the code that is generated from the Order domain object defined in the previousfigure.

Data Layer Recipes

82

Example 4.1. Domain Object - POJO (Generated)

package domain.ordermgmt;

public class Order implements Serializable{

/** * * @generated */ private String invoiceId; private Calendar invoiceDate; private Integer lineItemCount;

// Constructors, Getters and Setters ...}

For the fields that were defined as primary keys, Skyway Builder will generate primary key classes.Composite keys are supported.

Example 4.2. Domain Object - Primary Key Class (Generated)

package domain.ordermgmt;

public class OrderPK implements Serializable {

/** * * @generated */ private String invoiceId;

// Constructors, Getters and Setters, Hashcode() and Equals() ...}

By default a field is scalar; it can store one value of the basic type that is specified. If you mark the field asa collection, the field becomes a composite field that can store one or more values of that domain object.

Code Generation Note - POJO and JPA Entity

By default a domain object is generated into a POJO. If a domain object is associated with a dataaccess object (DAO), indicating the intent to persist domain objects a database, then the domainobject is annotated with the @Entity JPA annotation and associated with a primary key class(@IdClass).

2. Creating a Domain ModelPROBLEM

An application typically consists of a distinct set of inter-related application objects (domain objects) thatembody the functionality and characteristics of the system being built. All of the application objects arecumulatively referred to as the domain model.

A development effort usually begins with analysis of the problem domain, and domain modeling isfrequently the first step in designing an application. Domain modeling is the analysis of data objectsthat are used in a business, analysis of the attributes of those objects, and the identification of therelationships between these data objects.

SOLUTION

Data Layer Recipes

83

In a Skyway Project the domain model is defined by creating custom domain objects that encompassthe attributes of the domain objects and relating the domain objects to each other. The domain objectsbecome Domain Objects, and the object attributes become fields in the respective Domain Object.

HOW IT WORKS

Steps for Implementing a Domain Model

1. Create a Domain Object for each domain object

2. Add a field to the domain object for each attribute of the domain object

3. Define relationships between domain objects

3. Defining relationshipsPROBLEM

One of the basic principles of object-oriented development is that objects can be associated with otherobjects. There needs to be a mechanism for defining relationships between domain objects.

SOLUTION

The domain object editor allows you to define relationships to a domain object.

Relationship Type

The Relationship Type defines the cardinality of the relationship from the perspective of the currentDomain Object. The options are:

Table 4.2. Relationship Types

Type Description

One-to-One a domain object is related to a single occurrence of the other domain object

One-to-Many a domain object is related to many occurrences of the other domain object;the opposite side of a Many-to-One relationship

Many-to-One a domain object is related to a single occurrence of the other domain object;the opposite side of a One-to-Many relationship

Many-to-Many a domain object is related to many occurrences of the other domain object,and vice versa

Bidirectional Relationships

When a relationship is added to another domain object, a unidirectional relationship is implied. Twoindependent unidirectional relationships can be linked together to create a bidirectional relationship. Ifyou decide to define a bidirectional relationship, the cardinality and relationship names need to match.

Relationships Names

When defining a relationship between two data objects, the Domain Object editor will prompt you for arelationship name and a reverse name. These names will be used for accessing each other's related data.

Data Layer Recipes

84

The relationship name is used to identify the relationship from the perspective of the current domainobject. The reverse name is used to identify the relationship from the target data object type back tothe current domain object.

Regarding relationship names, the Domain Object editor will default the domain object name as therelationship names, but you can very easily changed the name. It's a good idea to change theserelationship names to something more semantically meaningful. While they have no impact on thefunctionality, these names will be the what you will see as your referencing these relationships in theservices you create. These names should be meaningful, and it's recommended that you name them withthe appropriate plurality for the relationship type.

HOW IT WORKS

The Relationship section of the domain object editor is used for defining relationships between domainobjects. The following Book and Author example shows a many-to-many relationship between Book andAuthor domain objects.

From the perspective of the Book domain object, it has a many relationship with the Author domainobject. The relationship name is authors.

Figure 4.2. Book domain object with relationship to Authors

From the perspective of the Author domain object, it has a many relationship with the Book domainobject. The relationship name is books.

Data Layer Recipes

85

Figure 4.3. Author domain object with reverse relationship to Book

A fragment of the code generated for the Author domain object is shown below. It shows how therelationship to the Books domain object manifested in code.

Example 4.3. Code generated for domain object relationships

package org.bookapp.domain;

public class Author implements Serializable{

/** * * @generated */ private String ID; private String firstName; private String lastName; private String title;

private Set<Book> books;

// Constructors, Getters and Setters ...}

The books relationship defined in the domain object is generated into a Set.

4. Creating a Data Access Object (DAO)PROBLEM

Data Access Objects (DAO) is a pattern for separate data access logic from business logic.

SOLUTION

Data Layer Recipes

86

A Data Access Object (DAO) is a Spring DSL artifact used to separate data access logic from applicationlogic. A DAO manages the persistence of domain objects, and it is generated into @Repository annotatedSpring components, a specialized stereotype for data access layer components. A DAO can also containpredefined queries called Named Queries.

HOW IT WORKS

Data Access Objects are abstract representations of real databases (or persistence mechanisms), andthey manage persistence for a set of domain objects. When designing the models there is no need toknow the detail of the database (vendor, version, IP, etc.), but simply a need to know that one exists formodeling database activity. When models are deployed, the developer late binds each Data Access Objectto a real, physical implementation of a database.

Steps for creating a Data Access Object:

1. Right click on a Model Package, and select New-->Data Access Object to open the New Data AccessObject Wizard.

2. From the New Data Access Object panel, enter a name for the data access object. Click Next.

3. From the Add Domain Objects panel, select the domain objects to be managed by this DAO. ClickFinish to open the Data Access Object Editor.

4. From the Database Configuration tab of the Data Access Object Editor you can configure the DAO fora particular Eclipse datasource.

If you're familiar with JPA, then the configuration settings should look pretty familiar. These settingsare directly related to JPA annotations. As you make changes to the Persistence Mapping panel, theannotations in the code associated with the domain objects will be automatically updated.

5. Table and Field MappingPROBLEM

When a domain object in configured to be persisted to a database, the database name and fields will bederived from the domain object. However there are occasions where a developer may want the tablenames and field names to be different than the object. There needs to be way for a developer to specifythe names to be used.

SOLUTION

When a domain object is created, Skyway Builder will use the following peristence mapping defaults:

1. Table name = domain object name

2. Table field names = domain object field names

This settings can be reviewed in the Persistence Mapping panel of a domain object, and they canalso be modified from the panel. The settings in this panel will drive the configuration of the ORMframework.

HOW IT WORKS

This is how it works.

Data Layer Recipes

87

Figure 4.4. Persistence Mapping

6. Relationship MappingPROBLEM

This is the problem.

SOLUTION

This is the solution.

HOW IT WORKS

This is how it works.

Data Layer Recipes

88

Figure 4.5. Relationship Mapping

7. Implementing DAO using JPAPROBLEM

While the DAO pattern doesn't dictate how the DAO actually handles persistence, object-relationalmapping (ORM) is most often used.

SOLUTION

By default Skyway utilizes JPA. Skyway Builder CE automates the use of Hibernate as the JPA provider. ForSkyway Builder Standard Edition1 the JPA provider is configurable.

HOW IT WORKS

The Domain Object Persistence Mapping panel (in the Domain Object Editor) lets you influence how thea domain object is persisted to a database. When a new domain object is created, Skyway Builder willautomatically create default persistence mapping values based on the definition of the domain object.For example: if the domain object is named Customer, then the table name will be defaulted to customer.However if you want to use a different table name, you can override the auto-generated persistenceconfiguration.

If you're familiar with JPA, then the configuration settings should look pretty familiar. These settingsare directly related to JPA annotations. As you make changes to the Persistence Mapping panel, theannotations in the code associated with the domain objects will be automatically updated.

1 http://www.skywayperspectives.org/portal/web/guest/products/builder/standard-edition

Data Layer Recipes

89

8. Generating Domain Model from an existingdatabase

PROBLEM

There may be occasions where a data model already exists, and you don't want to implement the domainmodel with Skyway. This can occur when the data model was defined by a different group (not usingSkyway Builder) or when building on top of an existing application. In either case, you need a way toleverage the pre-existing data model from Skyway Builder.

SOLUTION

In Skyway Builder there are essentially two ways implement a data model in a Skyway solution: nativelyand externally. Using the native approach, the data model is defined in Skyway Builder, and SkywayBuilder produces the database table definitions for any supported database management system. Usingthe external approach, define the data model in a relational database and import the table definitionsinto Skyway.

HOW IT WORKS

Using externally defined tables is accomplished using the Import Types wizard, which can be accessedfrom the Database Configuration tab in the Data Access Object Editor. Once the domain objects arediscovered, they can be used just like domain objects created in Skyway.

Here are the general steps for importing domain objects:

Steps For Importing Types

1. Create Data Access Object - In a Skyway Project create a data access object that will represent yourexternal database.

2. Configure DB Connection - Switch to the Database Configuration tab of the Data Access Object youcreated, and specify the database connection (in the Database Information section) that contains thetables you want to import. If the a database connection hasn't been defined, you must create thedatabase connection using the Database Explorer, and the specify the connection.

3. Activate the Import Types wizard - Click on the Import Types link from the Activities panel of theDatabase Configuration tab.

4. Select the schema - The schema dropdown will show a list of schemas available from the databaseconnection. Select the schema that contains the tables that should be imported.

5. Select the dialect - The dialect dropdown will show a list of dialects supported by Skyway Builder.Select the dialect that matches your database.

6. Select the tables to import - From the tables grid, select the tables that you want to import into theSkyway Builder project.

7. Click Finish - Skyway Builder will analyze the tables and create the domain objects corresponding thetables that were imported.

9. Performing Basic CRUD OperationsPROBLEM

Data Layer Recipes

90

When a domain object is added to a data access object, it implies that the application intends to persistobjects for that domain object. The most basic persistence functions in Create, Read, Update and Write,and they are cummulatively referred to as CRUD operations

SOLUTION

For every domain object added to a Data Access Object, the developer can perform basic persistencefunctions using the Modify Data Access Object and Search Data Access Object steps. The Modify DataAccess Object step is used for creating, update and deleting objects from a DAO, and the Search DataAccess Object step is for reading object(s) from a DAO.

HOW IT WORKS

Operations - Create / Update / Delete

While the Modify Data Access Object step is very easy to configure, the object oriented concepts can bedifficult to understand initially. While a relational database is ultimately going to be used to persist thedata, an object oriented view of the data is different than a relational view of the data.

The Modify Data Access Object step supports two operations: Update and Remove. These operations arehighly dependent on the primary key(s) defined for a persistable domain object. The key(s) must uniquelyidentify the object, and the ORM framework will use the keys to determine which objects should beremoved, added or updated. For the update operations the ORM framework will determine whether todo an update and an insert based on the keys. If an object with the same keys already exist, then theORM framework will use an update SQL statement. If an object with the same keys doesn't exist, thenthe ORM framework will do an insert SQL statement.

The following examples will demonstrate how the Modify Data Access Object works.

Figure 4.6. CRUD - Modify Data Access Object Examples

• (A) - The data access object being edited has 3 objects (A, B, C). The Modify Data Access Objectoperation being performed is an “Update” operation, and the operation input is a single object (D).

Data Layer Recipes

91

The effect of this operation is that the data access object will have four objects in it, the original threeplus the “D” object.

• (B) - The data access object being edited has 3 objects (A, B, C). The Modify Data Access Objectoperation being performed is an “Update” operation, and the operation input is a single object (A),which has been modified in the application. The effect of this operation is that the data access objectwill have three objects.

• (C) - The data access object being edited has 3 objects (A, B, C). The Modify Data Access Objectoperation being performed is an “Update” operation, and the operation input is a collection with twoobjects, an updated "A" object and new "E" object. The effect of this operation is that the data accessobject will have four objects, the original two unaltered objects (B, C), the updated "A" object, andthe new "E" object.

• (D) - The data access object being edited has 3 objects (A, B, C). The Modify Data Access Objectoperation being performed is a “Remove” operation, and the operation input is a single object (A). Theeffect of this operation is that the data access object will have two objects in it.

• (E) - The data access object being edited has 3 objects (A, B, C). The Modify Data Access Objectoperation being performed is a “Remove” operation, and the operation input is a single object (E).Since the data access object didn't have an "E" object to begin with, the effect of this operation is thatthe data access object is unaltered.

• (F) - The data access object being edited has 3 objects (A, B, C). The Modify Data Access Objectoperation being performed is a “Remove” operation, and the operation input is a collection with twoobjects (A, B). The effect of this operation is that the data access object will have one object (C).

10. Performing Complex Queries using JPQLPROBLEM

The JPA specification defines the Java Persistence Query Language (JPQL) which is a standard mechanismfor accessing data. Applications developed with Skyway Builder are automatically configured to use JPA,and the developer can leverage JPQL for accessing databases.

SOLUTION

A Named Query is a mechanism for predefining queries for the domain objects associated with a DataAccess Object. Named queries are defined using either SQL or JPQL (Java Persistence Query Language).JPQL is the query lanaguage of JPA, that resembles SQL queries. A developer can add Named Queries toa data access object, and then use the Invoke Named Query step to use the queries from Actions.

The benefits of named queries is that the queries are centralized and they can more easily be re-used.Using the Modify Data Access Object and Search Data Access Object steps througout your applicationcan make it more more difficult to manage where and how the data access is occurring because thequeries are contained in the generated code. On the other hand named queries are all located with theirassociated data access object. This makes it a lot easier for developer to find the query for re-using,repurposing or optimizing.

HOW IT WORKS

Inputs and Outputs These define the input and output parameters of a particular named query. Whenthis query is invoked, the consumer of the name query is required to map variables to the input andoutput parameters.

Data Layer Recipes

92

Query TextThis defines the query in either SQL or JPQL.

Table 4.3. JPA Query Examples

Type Query

Select SELECT ln FROM LoanAccountInfo ln WHERE ln.accountNumber = ${inAccountNumber}

Insert insert into NamedQueryTest values(${key}, ${value})

Update UPDATE NamedQueryTest t SET t.field_2 = ${value} WHERE t.field_1 = ${key}

Delete DELETE FROM NamedQueryTest c WHERE c.field_1 = ${inKey}

11. Deciding between Defined versus Derived DataModels

PROBLEM

There are two ways implement a data model using Skyway Builder: natively and externally. While theresult is generally the same, there are some definite pros and cons to each approach. Based on theapplication requirements, a developer needs some guidance on deciding the best approach.

SOLUTION

The following table summarizes the differences between externally defined data models and nativelydefined data models.

Table 4.4. Comparison of Native and External Data Models

Native Approach External Approach

Defined in an object-oriented manner; thepatterns for storing object-oriented data inrelational databases are very well defined andhandled by the ORM framework and JPA provider.

Defined in a relational manner with object-oriented facade; relational schemas don'ttranslate perfectly to objects.

Data model created in same applicationdevelopment environment

Data model must be defined using separate tools;all developers will need access to DBMS clienttools

Data model changes are immediately available inthe Skyway project

Data model must be rediscovered before beingavailable to Skyway project

Data model can easily evolve during applicationdevelopment; the initial definition of the datamodel can be pretty loose

All data model changes must be done externally;extra effort required to import data model;therefore you will probably want data modelto be well defined before commencing withdevelopment

Data model changes are version controlledwith the other application developmentartifacts; easier to identify correct data modelimplementation for earlier versions of application

If data model changes are version controlled at all,it will be done separately from project

DBMS expertise not needed DBMS expertise needed; DBA may need to getinvolved too

Data Layer Recipes

93

Native Approach External Approach

Data model can be deployed to any supportedDBMS for maximum deployment flexibility

The data model is tied to the DBMS that it wasderived from

Sharing project is simply a matter of copyingproject folder

Sharing project requires copying the project folderand providing the ddl for the database

While native data models offer maximum flexibility, there are occasions where external data models arethe only or most suitable option. Here are some comman scenarios where you would use external datamodels:

Table 4.5. Scenarios for using external data models

Scenario Description

Application Migration New front-end to existing application database

Integration Integration with external systems

Applicatoon Interfacetables

To facilitate external applications integrating with Skyway application at DBlevel

DB Centric Development You are philosophically opposed to starting development until the databaseschema has been defined

12. Working with Related DataPROBLEM

When working with domain object that has a relationship to another domain object, there needs to beway of programmaticaly accessing the related data.

SOLUTION

Related data can be programatically read and manipulated using the defined relationship name.Depending on the nature of the relationship (one-to-one, one-to-many, many-to-many), the mechanismfor accessing the data will be slightly different.

• One-to-One - related data is accessed like an attribute of the object using the relationship name. AllSkyway modeling steps that can read or write to single variable instances (i.e. Variable Editor Step,Decision Step) can be used to access one-to-one related data.

• One-to-Many - related data is accessed like a collection using the relationship name. All Skywaymodeling steps that can read or write to collections (i.e. Modify Collection Step, Search Collection Step,Iterate Step) can be used to access one-to-many related data.

• Many-to-Many - Same as One-To-Many.

HOW IT WORKS

In the Author and Book example from the Defining Relationships recipe, an author's set of related bookscan be searched using the Search Collection Step and iterated using the Iterate Step. The related data isaccessed using the relationship (i.e. currentAuthor.books).

13. Migrating to a Different DBMSPROBLEM

Data Layer Recipes

94

There are circumstances where an application needs to be migrated to a different database managementsystem (DBMS). For example:

• a developer may use a different DBMS in development than is used in production

• a disparate development team may have support different DBMS's

• an application is being re-platformed to a different DBMS

SOLUTION

If an application is using standard JPQL and/or SQL, the application can be deployed to a different DBMSby changing the database connection. In the case of Skyway Builder Standard Edition2 you can also changeJPA providers.

HOW IT WORKS

A Skyway data access object determines the database it's going to use by the configured DB connection.The underlying database can be changed by creating a new DB connection and reconfiguring the dataaccess objects to use the new DB connection.

2 http://www.skywayperspectives.org/portal/web/guest/products/builder/standard-edition

95

Chapter 5. Project Recipes

1. Creating Project-level Variables and ConstantsPROBLEM

There are occasions when you need to define one or more variables that are shared with all projectartifacts. In some cases the variable values can be changed, and in other cases the values are fixed atdesign-time.

SOLUTION

The Spring DSL supports Spring components (@Component) for storing a set of variables and constants,and a component has a configurable scope.

HOW IT WORKS

In order to create project level variables, the session scope should be used. Spring will make sure thatany and all references to this component are to the same component instance for the duration of theHTTP session.

Session-scoped components are used:

• sharing data across all project artifacts

• holding configuration data

• other sensitive values that should be protected

Since session-scoped components are maintained in a user session, excessive use of them may adverselyimpact the scalability of your application. Therefore it's generally recommended to use session-scopedcomponents sparingly.

2. Changing JPA ProvidersPROBLEM

The Spring applications generated by Skyway Builder leverage the Java Persistence API (JPA) for simplifyingthe persistence model. By default applications scaffolded or generated with Skyway Builder use Hibernateas the JPA provider, and the Hibernate and JPA libraries are added as dependencies to the project. ManyJEE containers (application servers) include different JPA providers, and there needs to be a way toleverage JPA providers other than Hibernate from your Spring-based application.

SOLUTION

With Skyway Builder Standard Edition1 a developer can choose JPA providers. A developer can selectHibernate or the container's JPA provider, and Skyway Builder will generate the Spring applicationaccordingly.

HOW IT WORKS

1 http://www.skywayperspectives.org/portal/web/guest/products/builder/standard-edition

Project Recipes

96

The Container Settings section of the Enterprise Configuration tab lets you pick the container type. Onceyou pick the container type (JBoss, Websphere, OC4J, Weblogic), you can select Hibernate or Containeras the Persistence Manager configuration.

3. Changing JTA ProvidersPROBLEM

The Spring applications generated by Skyway Builder leverage the Java Transaction API (JTA) for simplifyingtransaction management. By default applications scaffolded or generated with Skyway Builder useAtomikos as the JTA provider, and the Atomikos and JPA libraries are added as dependencies to the project.Many JEE containers (application servers) include different JTA providers, and there needs to be a way toleverage JTA providers other than Atomikos from your Spring-based application.

SOLUTION

With Skyway Builder Standard Edition2 a developer can choose JTA providers. A developer can selectAtomikos or the container's JTA provider, and Skyway Builder will generate the Spring applicationaccordingly.

HOW IT WORKS

The Container Settings section of the Enterprise Configuration tab lets you pick the container type (JBoss,Websphere, OC4J, Weblogic). Once you pick the container type, you can select Atomikos or Container asthe Transaction Manager configuration.

4. JSP AliasesPROBLEM

There are several places in a project where you may reference a JSP page. Rather than hard-codingreferences to the JSP pages, their needs to be a mechanism for defining aliases to the JSP pages.

SOLUTION

Directly referencing Java Server Pages (JSP) can be difficult for team-based development or addmaintenance complexity to larger projects. The JSP Aliases configuration (under the Web Application tabof the Project Editor) provides a way to alias pages so that references to the JSP pages aren't hard-codedin Web Controllers or Components.

The URL (Alias) is the alias used to reference the view resource.

HOW IT WORKS

URL Mappings are used to associate URLs to Actions and Views. There are essentially two configurationoptions for Views. You can specify the views in the URL Mapping, or you can reference a variable that willcontain the View. In both case there it is benefit to using JSP Aliases, particularly if a View is used for morethan one URL Mapping or a View is specified in application logic (i.e. Action).

In the case where a View is used in more than one URL Mapping, a JSP alias can be configured to create analias to a JSP, and the URL Mapping would specify the alias instead. If the at some point in time the actual

2 http://www.skywayperspectives.org/portal/web/guest/products/builder/standard-edition

Project Recipes

97

JSP would change, it would only need to be modified in the JSP Alias. All URL Mappings that reference theJSP alias would automatically be reconfigured. A developer would not need to find all the URL mappingsthat might be reference the JSP.

In the case where a View is conditional specified in application logic, using JSP aliases avoids hard-codingJSP files in your application logic.

Figure 5.1. JSP Alias

5. Adding Spring ContextsPROBLEM

As described in the Blending Actions with non-generated Spring Beans, you can invoke logic in Springbeans using the Invoke Spring Step. By default the list of available beans will be determined by the Springannotated beans and the Spring context configuration files generated by Skyway Builder. There will beoccasions when you want to leverage logic from beans that weren't generated with Skyway Builder.

SOLUTION

There are two strategies for using your own Spring configurations with a Skyway Builder generatedapplication. You have the option of adding to the Spring configurations generated by Skyway, in whichcase it will be available to the Invoke Spring Step. However you can also create your own Spring contextfiles and add them to the project.

HOW IT WORKS

The first strategy is to add your own Spring context files to the project and reference them in the SpringConfiguration tab (located in the Project Editor). With this strategy you must decide whether the beansdefined in the context file should be added to the web layer or service layer. The web.xml file will beupdated differently based on the configuration. Spring context files added to the web layer will be added

Project Recipes

98

as a contextConfigLocation init parameter for the DispatcherServler, and context files added to the servicelayer will be added to the contextConfigLocation context parameter.

Figure 5.2. Adding Spring Contexts to Project

The second strategy is to use the Spring context files that are created by Skyway Builder. Skyway Builderwill generate two Spring context files for each artifact category (web, service, domain, and DAO) in anapplication. One context file is for maintaining the beans and related configurations that are generated bySkyway Builder, and the other context file is for non-generated beans and configurations. The generatedcontext file (i.e. ProjectAlpha-generated-web-context.xml) should not be editted because Skyway Buildermay regenerate this context file. The non-generated file (i.e. ProjectAlpha-web-context.xml) is generatedwhen the project is orginally created, but it's never regenerated. The non-generated file also startsempty, and it's intended for the developer to configure custom non-generated Spring beans. All contextfiles (generated and non-generated) are automatically configured in the web.xml. The developer shouldupdate the appropriate context file based on the particular category that the bean is related to. Forexample the service beans should be added to the xxx-service-context.xml file, and web controllers shouldbe added to the xxx-web-context.xml file.

6. Creating Eclipse-based Skyway ProjectsPROBLEM

How to create projects that can fully leverage Eclipse web development capabilities.

SOLUTION

Skyway Builder supports Eclipse-based projects and Maven-based projects. While in all cases the SkywayBuilder Eclipse plugins are being used for code generation, Eclipse-based Skyway projects can leverageEclipse functions including compiling, packaging, dependency management, and deployment.

HOW IT WORKS

Here are the steps for creating an Eclipse-based Skyway project:

Project Recipes

99

Steps For Creating an Eclipse-based Skyway Project

1. From the file menu select New Project.

2. From the New Project Wizard, select Skyway Project. The Skyway Project option is located in theSkyway folder.

3. From the New Skyway Project Wizard, specify a name for the project. Click Next.

4. From the Folder Names panel specify the folder name for storing the models. The default models.Click Next.

5. From the Artifact Category Mapping panel configure the destination project for each artifact category.Click Finish.

For Eclipse-based Skyway projects all artifact categories must point to the same destination project. Therewill always be atleast two projects created. One project is for storing the models, and the other projectis the Eclipse dynamic web application that the Spring application in generated into (from the models).

The package name can be defined staticly or derived from a package name template. Thepackage template can include several tokens that will be resolved during code generation. The${project.name} token will be replaced with the project name.

7. Creating Maven-based Skyway ProjectsPROBLEM

How to create projects that can fully leverage Eclipse web development capabilities.

SOLUTION

Skyway Builder supports Eclipse-based projects and Maven-based projects. While in all cases the SkywayBuilder Eclipse plugins are being used for code generation, Maven-based Skyway projects can leverageMaven capabilities including compiling, packaging, dependency management, and deployment.

The decision to use Maven can only be made at project creation.

HOW IT WORKS

Here are the steps for creating an Maven-based Skyway project:

Steps For Creating an Maven-based Skyway Project

1. From the file menu select New Project.

2. From the New Project Wizard, select Skyway Project. The Skyway Project option is located in theSkyway folder.

3. From the New Skyway Project Wizard, specify a name for the project. Click Next.

4. From the Folder Names panel specify the folder name for storing the models. The default models.Click Next.

5. From the Artifact Category Mapping panel enable the "Use Maven to create projects for generatedcode" checkbox.

Project Recipes

100

6. Next configure the destination project for each artifact category. You can also configure the Mavenarchetype that will be used to create the destination project for each artifact category. Click Finish

Note: For Eclipse-based Skyway projects all artifact categories must point to the same destination project,and two projects will be created. One project is for storing the models, and the other project is the Eclipsedynamic web application that the Spring application generated from the models will be generated into.

The package name can be defined staticly or derived from a package name template. Thepackage template can include several tokens that will be resolved during code generation. The${project.name} token will be replaced with the project name.

8. Setup an Eclipse Dynamic Web Project for SkywayBuilder

PROBLEM

The New Spring DSL project wizard will automatically create a new Eclipse dynamic web project andconfigure it for code generation, however there may be occasions where you want to create the dynamicweb project manually or generate to a pre-existing dynamic web project.

SOLUTION

A Spring DSL project can be configured to generate to any dynamic web project, but there is someadditional setup related to code generation. The current version of Skyway Builder will always create anew dynamic web project as the target project (to generate code into), but the Spring DSL project can beeasily reconfigured to generate to a different pre-existing dynamic web project.

I created the Dynamic Web Project in Eclipse, and I specified TodoGWT as the name of the project andwar as the Content Directory. While the default content directory name for dynamic web projects isWebContent, the content directory must be changed to war due to a GWT requirement.

HOW IT WORKS

The first step is to setup the pre-existing project for code geneneration. While the developer has alot offlexibility in setting up a project, the default setup consists of:

Setup of pre-existing Eclipse dynamic web project

1. Creating a folder named "generated" (Project –> right-click –> New –> Folder) - the folder whereSkyway will by default generate the Spring and Java code

2. Creating a folder named "resources" (Project –> right-click –> New –> Folder) - the folder where Skywaywill by default generate the Spring context files

3. Configuring the "generated" and "resources" folders as source folders in Eclipse (Project –> right-click–> Build Path –> Configure Build Path -> Source tab)

The next step is to setup the Spring DSL project to generate to the pre-existing dynamic project insteadof the project that was created by default.

Configuring Spring DSL project to generate to pre-existing Eclipse dynamic web project

1. Open Spring DSL editor (double-click on Spring DSL icon in the Spring DSL project)

Project Recipes

101

2. Using Category Mapping tab, reconfigure target project (Project) to the pre-existing project. Pleasenote that changing the target project for one category will change the target project for all of them.

9. Manage project classpath dependencies manuallyPROBLEM

Skyway Builder will automatically manage project dependencies, which includes automatically updatingPOM files with references to dependencies for Maven-based project or automatically adding classpathvariables for dependencies to Eclipse-based projects. There may be occasions where the developer wantsto manage project dependencies manually.

SOLUTION

The automated management of dependencies can be turned off.

HOW IT WORKS

Using Category Mapping tab, select “Disable automatic dependency updates to project”. This option willdisable Skyway Builder from automatically updating the classpath.

When automatic dependency updates is disabled, you will need to manage the dependencies manually,which consists of manually adding all the dependent libraries to the project. For Maven-based projectsyou will need to update the dependencies in the POM file manually. For Eclipse-based projects you willneed to add required Java libraries manually. Skyway Software maintains a list and provides an archive3

of all the required libraries.

3 http://www.skywayperspectives.org/wiki/index.php/Jar_Files

102

Chapter 6. Customizing Code GenerationRecipes

The Spring DSL is a formalized set of EMF models and extensions that represents the building blocks ofan Spring MVC or WebFlow application. The Spring DSL is the language that the application developeruses to specify the implementation of the desired application. The Spring DSL is appropriate for definingcomplete Spring applications, but it is also suitable for defining parts of a Spring application. As thedeveloper defines their application using the Spring DSL, the meta-data backing the DSL serves as theinput into the code generation engine. Ultimately, the meta-data needs to be converted into a concreteSpring application, and there are two aspects related to code generation: configuration and templates.

1. Customizing Code Generation ConfigurationPROBLEM

When it comes to application development, the reality is that there is variation in development standardsand styles. Many code generators advocate (force you to use) the standards and styles from thecode generators authors. Skyway Software feels that development accelerators shouldn't force you tocompromise on your own coding standards. A frequent generalization (and criticism) of code generationhas been the inability for code generators to adapt to company and/or project standards.

SOLUTION

The Skyway Builder approach is to follow the principle of convention over configuration. Skyway Builderwill generate according to a set of conventions, but the developer has the flexibility to reconfigureas needed. The default conventions are derived from large, enterprise-level Spring implementationsand Spring best practices, and they’ve been vetted by Spring developers/architects and certified bySpringSource. If the defaults don’t conform to your project standards, then the Skyway Builder codegeneration engine for Spring can be customized to adapt to different standards.

HOW IT WORKS

Prior to Skyway Builder 6.3 the coding conventions could be customized by developing custom Eclipseplugins which extend the Skyway Builder code generator. Since version 6.3 all editions of Skyway Buildersupport project-level and artifact-level customization, which is simpler than developing EMF-basedEclipse plugins and provides an expanded set of customization options. Project-level and artifact-levelcustomization is accomplished by using the Code Generation tab which is available on all Spring DSLeditors.

Here’s a summary of the code generation customization options:

1. Full code generation configuration – The target file name, package (if applicable), file path, and projectfor primary and secondary code generation artifacts can be configured.

2. Project-level customization – The code generation can be customized at the project-level and appliedto all application artifacts in the project. IDE-level customization (through Eclipse plugins) is stillsupported.

3. Artifact-level customization - A specific application artifact can be customized on an artifact-by-artifactbasis (as opposed to inheriting project-level customizations)

Customizing Code Generation Recipes

103

4. Non-plugin based customization – Eclipse plugin and EMF development experience is not required.There’s no need to develop Eclipse plugins to customize the code generation, however, IDE-levelcustomization is still supported.

5. Customization for all editions – The code generation standards of all editions can be customized,including the Community Edition1 and all commercial editions2.

6. Enable/Disable code generation – The code generation of an individual artifact or type of artifactcan be enabled or disabled. Each application artifact in the Spring DSL has a Code Generation tab forconfiguring the code generation.

2. Customizing Code Generation TemplatesPROBLEM

While Skyway Builder provides you with a fully-implemented set of SpringSource-certified Spring MVCtemplates, there may be occasions where you want to customize the code generation templates to matchcustom requirements.

SOLUTION

The standard Spring templates included with Skyway Builder can be used as-is, or they can be adapted tomeet custom generation requirements. Application development projects will by default use the standardtemplates from the Skyway plugins for Eclipse. All versions of Skyway Builder3 support the customizationof code generation templates by extending the code generation framework using custom Eclipse plugins.Skyway Builder Professional Edition4 also supports the customization of code generation templates usinga Skyway Template Project which doesn't require Eclipse plugin development. A Spring DSL project canbe easily configured to use a Skyway Template Project (in the Eclipse workspace) as the source for thetemplates.

The benefits of using the Skyway Template Project are:

1. Any developer can customize application templates – Eclipse plugin development experience is notrequired. The only skillset required to customize templates is is JET, which is very similar to JSP.

2. Customized templates can be used on a project by project basis – If needed, each project can havea distinct set of templates.

3. Customized templates can be shared across projects – As templates are adapted to conform tocompany standards and desired implementations, they can be shared across development projects.

4. Customizations can be version controlled like standard Eclipse projects – The templates that wereused to generate the code and configurations can be version controlled with the application.

5. Customization of code generation for all Skyway Builder editions – Each edition of Skyway Builderadds additional code generation functionality, and all templates for all versions can be customized.

HOW IT WORKS

The first step is to create a new Skyway Template Project. You will be prompted for a name (i.e.MyCustomSpringGenTemplates) and a template source project. The name is self explanatory, but the

3 http://www.skywayperspectives.org/portal/web/guest/builder4 http://www.skywayperspectives.org/portal/web/guest/products/builder/professional-edition

Customizing Code Generation Recipes

104

template source project needs a little bit of explanation. When you create a template project, it will beseeded with the code generation templates (JET) from whichever project you specify as the templatesource project. You can specify any pre-existing Spring DSL project as the template source project, and allthe templates that were used for generation of the Spring MVC application will be copied into the newSkyway Template Project. Now that you have a template project with a copy of the templates, you cancustomize the templates.

The templates are implemented using JET5, a template engine from the Eclipse M2T project fortransforming meta-data/models to concrete code using an approach similar to JavaServer Pages (JSP). Byusing a standard and easy-to-use template technology, the Spring templates are easy to customize andadapt to different implementation requirements. If you open the MyTemplates project, you will see abunch of JET templates. Just about anything that is generated by Skyway Builder has a JET template or setof JET templates that define the outputs from the Spring DSL. JET templates resemble JSP in many ways,making it very easy to follow the implementation of the templates. JET supports the concept of tags andtag libraries (just like JSP), and the templates use many of the standard JET tags. The JET tag library is veryrich in generation functionality, but you can also use custom tag libraries. Skyway Builder contributes a setof JET tag libraries6 for simplifying many of the recurring generation requirements of Spring applications.

Once you've customized ther templates, the next step is to configure a Spring DSL project to use thetemplates in the new Template Project instead of the default templates. This is done by opening theSpring DSL editor, switching to the Code Generation tab, and configuring the new template project (i.e.MyCustomSpringGenTemplates) for the Location of Customized Templates. Go ahead and delete all of thefolders in the generated folder, and do a clean generation (Project–>Clean). The generated code shouldreflect the updates to the templates.

3. Extending the Code Generation FrameworkPROBLEM

The configuration and templates recipes are usefull for the customizing the out-of-the-box codegeneration capabilities of Skyway Builder, however there may be occasions where you may need to extendor add new code generation capabilities.

SOLUTION

See Extending the Skyway DSL7.

5 http://www.skywayperspectives.org/wiki/index.php/Skyway_JET_Tag_Library_Reference6 http://www.skywayperspectives.org/wiki/index.php/Skyway_JET_Tag_Library_Reference7 http://www.skywayperspectives.org/wiki/index.php/Extending_the_Skyway_DSL


Recommended