Posts Tagged ‘Code Generation’

One of the new web client scaffolding options in MyEclipse for Spring 8.6 (ME4S) is Adobe Flex.  If I had to summarize the capability in one sentence it would go something like:  ME4S 8.6 generates ready-to-run Spring-Flex BlazeDS Hibernate applications using the RemoteObject to communicate with Spring Services that support create, read, update and delete operations for related objects.

Of course, there is so much more… to read about in the full blog post at http://www.genuitec.com/blog/?p=1467

Skyway & Spring Security FAQs

by Dave Meurer on February 15, 2010

We recently answered several questions relating to Skyway’s feature to generate Spring Security 2.0 as well as general questions relating to Spring Security itself.  Here is a FAQ listing of those questions.  To learn more about Skyway’s Spring Security feature in Standard Edition, please take a look at the Security Feature Page.

  1. Before running Scaffolding > Scaffold spring security on the Spring DSL, Skyway requires that the user define a new Model package. Example video shows creating one named pkg.domain.security which Scaffolding then complements by creating a pkg.dao.security. Are there assumptions, limitations, or guidelines to where this domain.secuirty package should be placed (e.g. does the package have to be suffixed with security; does the dao package get created at the same level always)?
    Only assumption is if the package ends with “.domain”.  If so, Security Scaffolding places the DAO in a .dao package, and the Authorities and Users Domain Objects in the .domain package.
  2. After running Scaffold spring security will all newly added and domain objects have their Service and DAO objects added to Secured Resources when they have their CRUD scaffolded?
    Yes, new Services and DAOs will automatically be added to the Secured Resources.
  3. Skyway Project > Enterprise Configuration: What are the other Access values for Secured URLs and Secured Resources?
    Access can be used for Authentication and Authorization:
    Here are the 3 Authentication types:
    http://static.springsource.org/spring-security/site/docs/2.0.x/apidocs/org/springframework/security/vote/AuthenticatedVoter.htmlFor AUTHORIZATION, the Access string needs to be prefixed by “ROLE_” to indicate to  Spring Security that the Access is role based.  If the ROLE_  prefix is left off, deploy errors will occur. See example screenshot below.
  4. Skyway Project > Enterprise Configuration: How does the Secured URLs work in general? Is the default rule /secure/* allow pre-authentication for pages in this URL and then NO access for all others or is the no-access assumed for all other URLs?
    In the “/secure/*” scenario, all access to anything under the /secure/ path will require authentication.  Other URL paths do not require authentication.One note to consider is via the springSecurityFilterChain in the web.xml, all requests, specified by the url-pattern will go through Spring Security.  If a request is not intercepted by the login form, the user will be an anonymous user, and the security context will have something like the following:
    org.springframework.security.providers.anonymous.AnonymousAuthenticationToken@9611881d: Principal: roleAnonymous; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails@fffd148a: RemoteIpAddress: 127.0.0.1; SessionId: 478A01F999A8CD50D40E069428B71306; Granted Authorities: ROLE_ANONYMOUS(Invalid property ‘principal.username’) Errors
    Due to the above paragraph, this error may appear with pages that have not been authenticated, but use the sitemesh decoration because the login.jsp uses <sec:authentication property=principal.username”/> which does not exist when the security context authentication is authenticated with an anonymous user.

    If the desired behavior is to remove Spring Security entirely from certain requests, the springSecurityFileChain url-pattern should match the intercept-url pattern in the security context.

    A good way to see the security context is use the code in the login.jsp page to create a sample page that displays the entire “auth” variable.

  5. Skyway Project > Enterprise Configuration: Configured Views: The Skyway training video describes the out-of-the-box operation as using the spring provide screens for login challenge. Allowing these values to be blank. However there are several default generated pages in a Skyway project that seem to appropriate to wire in here. Can you provide details into what pages become obsolete when security is enabled and provide a general description of how the login URL navigation works? In essence walking through the URL navigation from index.html through the security scenarios would help.
    Security Flow(click to enlarge)

    Files involved in security:
  6. resources/[ProjectName]-generated-security-context.xml Central Spring Security config file. All configurations from the Spring DSL > Enterprise Configuration tab are emitted into this file.
    WebContent/secure/welcome.jsp Welcome page used after someone logs in. Used in the chain of Sign-in link (from login.jsp) to /spring_security_login to welcome.jsp
    WebContent/pages/logout-redirect.jsp Straight redirect to logout-success.jsp
    WebContent/pages/logout-success.jsp Static HTML page that states “You have successfully logged out of the system.”
    WebContent/WEB-INF/sitemesh-common/login.jsp Contains top “Sign-in” tab that changes based on if a user is authenticated.  Not authenticated: sign-in link that goes to the welcome.jsp.  Authenticated: Sign out link that goes to /j_spring_security_logout
    WebContent/WEB-INF/decorators.xml Two URLs are excluded: /j_spring_security_logout, and /pages/logout-redirect.jsp to prevent the sitemesh decoration framework from intercepting these URLs and adding the decorations to them.
    /spring_security_login Default URL path to sign in to Spring Security.  Displays the default Spring Security form.  This can be overridden via the Login View field in the Enterprise Configuration tab. (not an actual file in the project)
    /j_spring_security_logout Default URL path to logout/sign out of Spring Security. By Default this will go back to the /spring_security_login URL.  A logout success/error view can be added via the Enterprise Configuration > Configured Views fields. (not an actual file in the project)
  7. Skyway Project > Enterprise Configuration: Security Information Source: Is there ever a case where the Connection in this section does not match the User & Authorities DAO connection?
    Only if a different connection is required for authentication rather than just CRUD operations.
  8. Are there any required naming conventions for the authority names (e.g. ROLE_<name>)?
    The only recommendation is to avoid using the “ROLE_” prefix in the authority names.  Spring Security adds the “ROLE_ “, for internal purposes as explained in #3 above and #2 below.  For example, if the ROLE prefix is used, Spring Security will add another role prefix resulting in something like “ROLE_ROLE_ADMIN”
  9. How do you apply the authority rules to the application? Is there a standard convention, approach to using them?
    See Question #3 above for URL authorization.
    For view element authorization, e.g. displaying buttons on a page only to ADMIN users, use the spring security tag library.  E.g.

    <sec:authorize ifAllGranted="ROLE_ADMIN">
         <input type="button" value="Save">
    </sec:authorize>
    
  10. Security: What would happen if you had /secure/* secured, but tried to access a Secure Service via /*?
    As noted in the Securing Applications – Authentication recipe, (http://www.skywayperspectives.org/documentation/6.3/chunk/recipes/ch02s30.html), the Service and DAO Secured Resources section controls external access to those services.  It is assumed that the developer secures the entry point in the Web Application via the URL.  For example, if one of your services is a web service (JAX-WS tab on the service), and you have the Service checked in the Secured Resources pane, you will see an entry in the list of the securedServiceEndPointNames element in the resources/jaxws/jaxws-web-context file.
  11. Why is the ROLE_ prefix emitted in the security config when DB is selected?
    From the Spring API docs: “If this is set to a non-empty value, then it is automatically prepended to any roles read in from the db. This may for example be used to add the ROLE_ prefix expected to exist in role names (by default) by some other Spring Security classes, in the case that the prefix is not already present in the db.” In other words, Spring Security expects the role to have “ROLE_” as a prefix, (like in the case for the intercept url authorization) so we generate this by default so developers can create any named role in the database without the need to prefix it with “ROLE_”.

Resources

Some good resources for Spring Security:

We at Skyway have a passionate goal to create a product that resolves all problems associated with code generators today and earlier generation code generators. We’re not afraid to bring these concerns out on the table, because we want all developers to realize the benefits that Skyway can bring to accelerating Spring development. So, we pride ourselves in removing the roadblocks associated with code generation.

To help discuss code generation issues and how Skyway resolves these issues, this blog focuses on the following code generation statements.  These statements comprise a summarized view of our own experience with other code generators as well as what we have heard in talking with folks about Skyway.  Don’t get me wrong, these statements do accurately describe some, if not most, code generators. Unfortunately, these code generators have influenced a mindset encompassing all generation frameworks.  Hence the reason for this blog; an answer to the code generation drawbacks with a product conceived, designed and built by developers.

In six general statements, here are the drawbacks with code generators:

Code Generators …

  1. … lock me down!
  2. … contain runtime proprietary components!
  3. … generate unreadable bad code!
  4. … don’t allow me to customize what’s generated!
  5. … have an added learning curve!

The following table presents a concise view of each perceived drawback, Skyway’s answer to these drawbacks and proof where you can see it for yourself.

Drawback Skyway Solution Proof
lock me down! The generated Eclipse Dynamic Web project is completely decoupled from the Skyway DSL project. A developer can completely ignore or throw away the Skyway visual DSL and continue to hand code the project if so desired. There are also various development approaches to blend hand coding and modeling.
  • Download the Skyway Hotels sample project and remove the SkywayHotels Spring Modeling project.
contain runtime proprietary components! Skyway has no proprietary runtime components. The deployed application is a standard Spring enabled Eclipse Dynamic Web Project. The application you build and deploy is 100% owned by you.
  • Download any sample project or follow any tutorial and inspect the web application.
  • Deploy it to a WAR and inspect the contents.
generate unreadable bad code! Springsource has crawled through Skyway’s generated code and configuration files and certified what is generated. Skyway also uses various Spring Recipes, and has leveraged our strategic partnerships and community feedback to continually improve the code that is generated.
don’t allow me to customize what’s generated! Skyway’s core generation framework is open source and built on the Eclipse plug-in framework providing many extensibility options. Skyway’s newest Project Templates feature also makes it very easy for developers to modify the templates used in code generation.
have an added learning curve! Skyway’s visual Spring DSL sticks to Spring concepts familiar with Spring developers. The visual DSL has also helped new developers to Spring accelerate their learning while not sacrificing project timelines.

If you are interested in learning more about Skyway, please take a look at our features or getting started page.

If you see something that is not listed, please comment on this blog or post a forum thread or JIRA.  Your feedback is more valuable than you think.

If after reading this blog, you still are not convinced, how about a live demo or conversation? Email sales@skywaysoftware.com

Or if you still have beef with Skyway’s Generation?  Why not share it to improve Skyway?

Update 7/9/2010 – MyEclipse for Spring 8.6 now generates full ready-to-run GWT applications based on MVP and UI Binder in minutes.  Just point the scaffolding wizard at your database tables, Java beans, or JPA Entities.  You can learn more about it from the Generating Enterprise Class GWT applications for Spring post that I wrote on Genuitec blog.  Or, you can keep reading my original post…

This blog post is the last post of a series of blog posts related to extending Skyway Builder to enable some code generation support for GWT.  In part one I gave an overview of the Skyway Builder extension in relation to GWT, and in part two I gave an overview of how Skyway Builder will be extended to support GWT development.  In part three I describe the actual implementation of the Spring DSL extension, and in this post I will describe how to download, install, and use the extension.

The GWT extension for Skyway Builder is implemented as an Eclipse plugin.  As such it needs to be installed as an Eclipse plugin.  In the future I may create an update site, but for now you can download the plugin (com.skyway.experimental.integration.gwt_1.0.0.jar) and copy it into the plugin folder for Eclipse.  Just as a reminder this plugin is dependent on having Eclipse 3.4.2 plus Skyway Builder 6.3 (Standard Edition).  If you don’t have Skyway Builder Standard Edition, you can get a copy from here.

When you restart Eclipe the GWT extension for Skyway Builder is ready to go.  For any Spring DSL Services or Components that you have defined in any projects, Skyway Builder will start generating slightly updated or new artifacts (see post two for details).

Here’s an important consideration.  This experimental plugin was designed to toggle the generation of GWT artifacts (using the Code Generation tab), and by default the generation is turned on.  This means that it will affect all Services.  If you have any existing projects that you don’t want to be affected by the GWT extension, you will need to disable the generation of the GWT artifacts by unchecking the GWT entries from the Code Generation tab of the Spring DSL.

A better solution is to add an attribute to the definition of the service that will allow me to specify the Service should be GWT enabled.  That’s exactly the approach taken by the DWR and JAX-WS features in Skyway Builder.  When you check “Publish DWR” or “Publish Web Service” checkboxes, the service will be generated accordingly.  Perhaps I’ll tackle that in a future version of the plugin.

Here’s an example of using the new plugins.  I followed the instructions from a previous blog post (GWT and Spring: Setup of development environment and Create GWT project).  The only difference is that this time I’m using GWT 2.0 instead of GWT 1.7, and I also added the spring4gwt library to my project.  Before I start doing any code generation with Skyway Builder, I want to quickly configure the Spring DSL to generate the correctly generate the new artifacts.

The Code Generation tab of the Spring DSL is used to define the code generation defaults for the project.  You will notice there are some new code generation entries that are contributed by the new plugin.  The first step is to disable “Service Interface” generation.  I recommend sorting the table by Categories in order to see all the Service entries grouped together.  The next step is to configure the “Service Interface“, “GWT Service Interface“, and “GWT Service Async” entries with a different package.  By default they are set to ${model.package}, which means that the artifact will be generated to a java package corresponding to the model package of the Service.  However for GWT we want the interfaces generated into their own package, so we are appending “.interfaces” to the end of the package.  I won’t go into all the details why this needs to be done for GWT, but suffice it to say that it’s a GWT best practice to isolate client-side and server-side Java code so that the GWT compiler will only compiling relevant Java code (source path) to javascript.

To see the GWT extension for Skyway Builder in operation, you can create Spring DSL services by hand or you can quickly scaffold a Spring MVC application.  For this blog post I scaffolded from a domain object.  See step 9 from GWT and Spring (Part 2) – Scaffold Spring back-end for GWT Application for a quick explanation on how to scaffold a Spring MVC application with Skyway Builder.

In my example you can see that the ContactService (in Spring DSL) generated the implementation class, service interface, and asynchronous callback interface (for GWT).  As you add new operations to the service, all the artifacts are regenerated to reflect the changes.

As far as events are concerned, you can just create a model package whose corresponding java package will be listed as a source path in GWT application, which will result in it being compiled into javascript.

This concludes my series.  My hope is that I provided an easy to understand introduction on how to extend Skyway Builder and an extension that may be usefull to GWT developers using Spring as their backend.  If you have any questions or would like me to elaborate on something, please drop me a comment here.

What’s next with this plugin? I’m glad you asked.  I would like to expand the support for GWT development in Skyway Builder.  I had started experimenting with some GWT UI scaffolding, and I’m making some good progress.  However given the new UI Binder feature in GWT 2.0, I will need to re-examine this.  If you have any ideas for enhanced GWT suppport, please let me know.

Happy New Year!!!

Update 7/9/2010 – MyEclipse for Spring 8.6 now generates full ready-to-run GWT applications based on MVP and UI Binder in minutes. Just point the scaffolding wizard at your database tables, Java beans, or JPA Entities. You can learn more about it from the Generating Enterprise Class GWT applications for Spring post that I wrote on Genuitec blog. Or, you can keep reading my original post…

This blog post is the continuation of a series of blog posts related to extending Skyway Builder to enable some code generation support for GWT, including the automated  access of Spring @Services for GWT RPC.  In part one I gave an overview of the Skyway Builder extension in relation to GWT, and in part two I gave an overview of how Skyway Builder will be extended to support GWT development.  In this post I will describe the implementation of the Spring DSL extension in more detail.

If you don’t so much care how the GWT extension for Skyway Builder is implemented and just want to start using the extension, then you will probably just want to skip to part 4 where I will describe how to download, install, and use the extension.

Since the general steps for extending in Skyway Builder are already described on Modifying Artifact Generation in the Skyway Wiki, in the post I’m going to focus specifically on how these steps were applied to create the GWT extension.

Following the setup instructions, first of all I created a Jet Transformation project called com.skyway.experimental.integration.gwt.  I accepted all the defaults in the wizard.  Next I added required dependencies.

I’m going to use JET to implement my code generation templates.  JET templates resemble JSP in many ways, making it very easy to follow the implementation of the templates.  JET supports the concept of tags and tag libraries (just like JSP).  The JET tag library is very rich in generation functionality, but you can also use custom or 3rd party tag libraries (just like JSP).  Skyway Builder contributes a set of JET tag libraries for simplifying many of the recurring generation requirements of Spring applications.  A full reference of the Skyway JET tag library can be found here.  In regards to the GWT extension, the  Skyway JET tag library need to be added as extension.

The next step is to add the artifact definitions for the new artifacts that are going to be generated and register the template overrides for the pre-existing artifact definitions.

This diagram shows the extension entries required to accomplish the functions described in post 2, which includes:

  • adding a new Service artifact definition for the GWT callback interface
  • adding a new Service artifact definition for the service interface (the decision to create new artifact definition instead of overriding existing template will be described in part 4)
  • overriding the JET template for generating the web deployment descriptor (web.xml)
  • overriding the JET template for generating the Spring context file for the service layer
  • adding a new Component artifact definition for generated GWT events

I won’t review each JET template, but the the project contains five new templates.

Here’s a summary of each template:

  • generated-service-context.jet – This template is a copy of the base template and includes additional logic to direct Spring to do a component scan of all annotated Spring components.  By default the component scan is done from the web context file, but GWT front-ends talk will directly to the service layer (and bypass the web layer).  Therefore the component scan needs to be done from service layer, otherwise the dependencies of the Service layer won’t be resolved by Spring.
  • gwtEvent.jet – This new template generates a GWT event Java class from a Spring DSL component.  The component name is used as the event name, and the component variables are use for generating the event payload.
  • gwtServiceAsync.jet - This template is a new template that generates the GWT callback interface, which is a requirement for using GWT RPC.
  • gwtServiceInterface.jet - This template is a copy of the base template and includes additional logic to emit an @RemoteServiceRelativePath annotation for each service operation.
  • web.xml.jet – This template is a copy of the base template and includes additional logic to register the spring4gwt servlet and servlet mappings.

That’s it for the plugin.  The next step is to export the plugin (Export –> Deployable plug-ins and fragments).  The resulting plugin (jar file) can be installed into an Eclipse instance with Skyway Builder 6.3.  I’ll cover that in more detail in the next post (part four).

June 2010 Update: This original blog post was written prior to the release of Spring Flex Scaffolding support in MyEclipse for Spring 8.6. Wanna build an entire Spring Flex CRUD app using your tables or code in a matter of seconds?  This tutorial is now productized in the MyEclipse for Spring 8.6 release.  Download and try it today! Check out the what’s generated blog or the getting started video.
Body builder competition Flex application

This blog/tutorial covers the basics to getting started with spring-flex development in Skyway.  The spring-flex framework uses Adobe’s open source BlazeDS project, which is the remoting and messaging foundation for connecting a Flex-based front-end to Java back-end services.  Skyway is used to accelerate the Spring development by providing a visual environment to generate all the necessary Spring configuration files and CRUD operations in a SpringSource certified Spring MVC application.  The tutorial then goes on to tweak the Skyway generated configuration files to support Flex Remoting to produce the list view above that calls the Skyway generated Spring service.

This blog is divided into 2 parts:

What you’ll need first

Before creating the project, there are a handful of items you’ll need to setup your Skyway Flex Builder environment.

  1. Download BlazeDS: I downloaded the BlazeDS turnkey ready-to-use distribution, which comes with a version of tomcat.  The BlazeDS installation guide was very helpful after the download.
  2. Get FlexBuilder: You’ll need something to compile your mxml into swf.  There’s a 60 day trial of FlexBuilder 3.  IMPORTANT: per M. Zach’s comments, it is essential to download Eclipse Ganymede (3.4 – for Java Developers) first, then install the FlexBuilder 3 plug-ins on top of that install, and finally install the Skyway Builder plug-ins.
  3. Get Skyway: Install the Skyway plug-ins on top of the FlexBuilder Eclipse instance. Download the Community Edition, or test drive the full featured Commercial Edition.
  4. Server & DB: Create your server and datasource connections inside Eclipse.  If you need help, Skyway has a sandbox setup guide that can help.  Point the server to the BlazeDS tomcat installation.
  5. References: Have the references section at the end of this blog handy.  They are great resources for deeper understanding on any topic discussed here.

Create the Project & CRUD

There are several ways to create a Flex Project with Skyway’s generation capabilities.  If you have an existing Flex Project, follow the recipe on setting up and Eclipse Dynamic Web Project.  For new projects, the cleanest way I found to set up the project is to create a Skyway Project and then add the Flex Nature described here:

  1. New Skyway Project: File > New > Skyway Project.  Name it BodyBuilder. Accept all defaults and click Finish.
  2. Add Flex Nature: Right-click the created BodyBuilder-Web project, and select Flex Project Nature > Add Flex Project Nature.  Modify the defaults as described in the following:
    1. Application server type: J2EE
    2. Use remote object access service: Checked
    3. LifeCycle Data Services: Enabled
    4. Click Next
    5. Flex WAR file: <Blazeds installation>\blazeds.war
    6. Click Finish.

  3. Clean up the Errors: You may get some errors in the Problems tab after adding the Flex Nature (also see M. Zach’s comments below):
    1. Server SDK: Directory does not contain a Flex SDK.  To resolve, right-click the Web project > Properties > Flex Compiler.  Choose Use default SDK in the Flex SDK version. This will then create another error about Cannot create HTML wrapper.  Just follow the instructions in the error:right-click and choose Recreate HTML Templates.
    2. Web library project archive commons-codec-1.3.jar conflicts with another archive also mapped to the WEB-INF/lib folder: This is due to Skyway’s default library classpath container management.  The easiest way to resolve is to go to the Web Project > WebContent/WEB-INF/lib folder and delete all the jars that do NOT start with flex-*.
  4. Create the Domain Object: This is the start of CRUD Scaffolding.  If you aren’t familiar with Skyway’s CRUD Scaffolding capabilities, please take a look at the short How To on CRUD App Scaffolding for more details.
    1. Right-click the Spring DSL artifact under the BodyBuilder project, and select New > Model Package.  Name it com.bodybuilder.domain.
    2. Right-click that Model Package, and select New > Domain Object.  Name it Contestant. Add any fields to the Contestant Domain Object, making sure a primary key is specified.  It may look something like the following image (click to enlarge):contestant-do
    3. Scaffold CRUD: With a few short clicks, all the necessary Java and Spring MVC artifacts will be generated to support Create, Read, Update, and Delete operations on this domain object.  Right-click the Contestant visual Domain Object, and select Scaffolding > Scaffold CRUD.

Add Spring Flex

Covered in Part 2 of 2

Page 1 | 2 | >

June 2010 Update: This original blog post was written prior to the release of Spring Flex Scaffolding support in MyEclipse for Spring 8.6. Why read this tutorial, when you can build an entire Spring Flex CRUD app using your own tables or code in a matter of seconds?  This tutorial is now productized in the MyEclipse for Spring 8.6 release. Download and try it today! Check out the what’s generated blog or the getting started video.
In Part 1 of Accelerate Spring Flex development with Skyway + BlazeDS, I covered prerequisites, development environment setup, project creation, and scaffolding a domain object in Skyway.  In Part 2, I will discuss adding the necessary pieces to get a Spring application Flex enabled through BlazeDS remoting.
This blog is divided into 2 parts:

web.xml

  1. Turn off web.xml generation: At this point, you may want to turn off Skyway code generation for the web.xml since we will manually add code into the web.xml for spring-flex.  To do this, double-click the Spring DSL visual artifact and go to the Code Generation tab.  In the Code Generation section, find the Web Deployment Descriptor / web.xml row, and uncheck the Generate checkbox.  Save the Spring DSL visual artifact. Skyway does have merging capabilities in the web.xml, so this step is optional.
  2. Add the messagebroker servlet mapping: Insert the following code where the servlet mappings are defined.  This mapping is used by the Flex remoting object.
    <servlet-mapping>
        <servlet-name>BodyBuilder Servlet</servlet-name>
        <url-pattern>/messagebroker/*</url-pattern>
    </servlet-mapping>
  3. Add the flex context file: Find where the BodyBuilder Servlet is defined.  In the param-value element for the contextConfigLocation, add /WEB-INF/flex-servlet.xml,.  So the resulting servlet block should look like:
    <servlet>
        <description>generated-servlet</description>
        <servlet-name>BodyBuilder Servlet</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/flex-servlet.xml,
              classpath:BodyBuilder-generated-web-context.xml,
              classpath:BodyBuilder-web-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

flex-servlet.xml

  1. Add a file, named flex-servlet.xml, to the Web Project > WebContent/WEB-INF folder with the following contents:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:flex="http://www.springframework.org/schema/flex"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="
    
    http://www.springframework.org/schema/beans
    
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    
    http://www.springframework.org/schema/flex
    
     http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">        
    
         <flex:message-broker/>
    
         <!-- Expose the ContestantService bean for BlazeDS remoting -->
         <flex:remoting-destination ref="ContestantService" />
    
    </beans>

services-config.xml

  1. When adding the Flex Project Nature, it adds a handful of files to the Web Project > WebContent/WEB-INF/flex folder.  Feel free to use whatever Flex provides.  However, to just get remoting up and running on a channel, all you need in the services-config.xml file is the following:
    <?xml version="1.0" encoding="UTF-8"?>
    <services-config>
    
        <services>
            <default-channels>
                <channel ref="my-amf"/>
            </default-channels>
        </services>
    
        <channels>
            <channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
            <endpoint
           url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf"
           class="flex.messaging.endpoints.AMFEndpoint"/>
            </channel-definition>
        </channels>     
    </services-config>

    NOTE: Anytime this file is udpated or modified, you’ll want to force a recompile of the swf file. These configurations are compiled into the flash file.

Add jars

  1. The following jars need to be added either through classpath containers or the WEB-INF/lib folder.  Both can be found in the spring-flex download (with dependencies):
    • org.codehaus.jackson-1.0.0.jar
    • org.springframework.flex-1.0.1.RELEASE.jar

Flex UI – main.mxml

  1. To get a simple list view of the Body Builder Contestants, all that is needed is a remoting object defined, a data grid, and a button to load the data:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    
        <mx:RemoteObject id="ro" destination="ContestantService"/>
    
        <mx:DataGrid dataProvider="{ro.loadContestants.lastResult}"
            width="100%" height="50%"/>
    
        <mx:Button label="Get Contestants" click="ro.loadContestants()"/>
    
    </mx:Application>

A couple final project tweaks

  1. Flex Server: The last tweak to make is in the Web Project Properties > Flex Server.  Change the Root URL to http://localhost:8400 (if using the turnkey BlazeDS server), and the Context Root to /BodyBuilder-Web.  Click Validate Location. If it does not validate, you should still be able to click OK.
  2. Logging: The Flex Project Nature adds a commons-logging.properties file to the WEB-INF/classes folder.  Feel free to delete or tweak that file as necessary as it won’t show the Spring Hibernate logs that you may be used to with Skyway upon server startup.

Run it on BlazeDS

If the BlazeDS tomcat server was added to the Eclipse Server view, just add the BodyBuilder-Web project to the server and run!  (you may want to add some data to your Contestant table first)

Potential Errors

[RPC Fault faultString="[MessagingError message='Destination 'ContestantService' either does not exist or the destination has no channels defined (and the application does not define any default channels.)']” faultCode=”InvokeFailed” faultDetail=”Couldn’t establish a connection to ‘ContestantService’”]

I thought the above error was important to mention since I received it about 300 times :-) This usually means something is wrong with the services-config.xml file in the flex folder, or it hasn’t been compiled into the SWF file.  Ensure the file exists, and sometimes forcing a recompile of the mxml file does the trick.

References

< Page 1 | 2

Update 7/9/2010 – MyEclipse for Spring 8.6 now generates full ready-to-run GWT applications based on MVP and UI Binder in minutes. Just point the scaffolding wizard at your database tables, Java beans, or JPA Entities. You can learn more about it from the Generating Enterprise Class GWT applications for Spring post that I wrote on Genuitec blog. Or, you can keep reading my original post…

In the previous post I introduced a new GWT extension for Skyway Builder that automatically makes Spring @Services accessible as GWT RPC services and accelerates the development of GWT events that can be used with a GWT event bus.  This blog post will provide a high-level description of the implementation of the extension, and in the next blog post I will dive into the implementation details .

I’m not going to spend a lot of time explaining how spring4gwt works.  Please refer to the project site for detailed description of spring4gwt.  There are essentially five steps for making Spring @Services accessible as GWT RPC Services using spring4gwt.

Implementation requirements for producing GWT RPC services from Spring Services:

  1. Copy Spring4GWT library into project
  2. Modify web application context file (web.xml) – add spring4gwt servlet and servlet mapping
  3. Create a a GWT callback interface for the Spring @Service – each service operation should be reflected in callback interface
  4. Modify the service interface – add import statements for GWT remote service; add @RemoteServiceRelativePath annotation; extend Remote Service
  5. Modify service context file (Spring) - since GWT clients replace JSP and controllers, the component scan that is typically located in the web context file needs to be moved to the service context file, otherwise the Spring framework won’t be able to find other components that the service might be reliant upon.

Except for the new GWT callback interface, all the relevant artifacts are already generated by the Spring DSL.  The GWT extension will just need to customize the generation of these artifacts to support GWT RPC using spring4gwt.  The callback interface, on the other hand, is a new artifact, and the Spring DSL will need to be extended to generate it.

Here’s what you need to know about the Spring DSL.  The Spring DSL defines 10 abstractions, which include Project, Controller, Component, Service, Domain Object, Data Access Object, Operation, Named Query, Exception and Action.  Each Spring DSL abstraction will generate primary and secondary artifacts, and the generated artifacts are typically Java code or XML configuration files, although you really can generate anything that can be emitted with JET.

springdslabstraction

During the course of application development using the Spring DSL a developer will define instances of  Spring DSL artifacts, and Skyway Builder will generate the primary and secondary artifacts according to the configuration of the Spring DSL artifacts.

springdslinstantiation

For the GWT RPC functions the two relevent Spring DSL abstractions are: Project and Service.  According to the Spring DSL there are 6 artifact definitions for a Service, and the following diagram shows the most relevant ones -plus- the new artifact definition (GWT Interface).

springdslservices

For the Service interface the GWT extension will override the default code generation template that’s provided by Skyway Builder, and the new template will emit code required in the service interface (see requirement #3).  For the GWT callback interface (requirement #4) the GWT extension will extend the definition of a Service by adding a new artifact definition and contributing a new code generation template.

Now that requirements 3 and 4 are out of the way, let’s proceed to requirements 2 and 5.  These requirements will be handled in a very similar manner.  The web.xml and Spring context files are generated by the Spring DSL Project abstraction.  There are a lot of artifacts generated from a Project, so the following diagram only shows the most relevant ones.

springdslproject

The GWT extension will override the code generation templates for web.xml and service context file.  The new templates will add the additional configurations needed to support GWT RPC.

In the grand scheme of things this exercise was pretty trivial because all the required steps are handled by the GWT extension by just overriding an existing template or contributing a new artifact definition to an existing Spring DSL element.  It’s worth noting that this is just the tip of iceberg when it comes to extending the Spring DSL.  If needed you could extend Spring DSL element to capture more metadata, which presumably would be used to drive the code generation.  You could also create entirely new Spring DSL elements with their own meta-data and code generation templates.

The implementation overview of the GWT RPC function is complete, and now we will proceed to the GWT Events function.  For this function I needed to decide whether or not I should create an entirely new Spring DSL element for Events or whether I could use a pre-existing Spring element.  For the sake of simplicity I decided to use the existing Spring DSL Component element because it already captures all the metadata that I need for generating Events.  Components have a name, which I’ll use as the event name, and components have variables, which I’ll use for defining the event payload.  Here’s the definition of a Component -plus- the new GWT event.

springdslcomponent

The process for adding support for generating GWT events from a Component is nearly identical to the process of generating the callback interface from a Service.  The GWT extension defines a new artifact definition for Spring DSL Components, and a new code generation template will be used to produce GWT events.

As you can see it was relatively simple to customize the Spring DSL, and the basic recipe described in this post can be applied to countless development scenarios.

If you are familiar with Skyway Template Projects, you may be wondering how this process is different than Skyway Template Projects.  Both let you customize the code generation templates, so why was an Spring DSL extension used instead of a Skyway Template Project.  While Spring DSL extensions and Skyway Template Projects share some functionality, you can do a lot more with the Spring DSL extensions. I already pointed out that this recipe is just the tip of the iceberg when it comes to extending the Spring DSL.  While Template Projects let you customize the templates, they don’t let you add new artifact definitions (which was one of the requirements of the GWT integration), extend the Spring DSL with additional metadata, or define entirely new Spring DSL abstractions.  If you are only interested in overriding pre-existing code generation templates for pre-existing Spring DSL abstrations, then the Skyway Template Project is your best bet.  However Skyway Template Projects weren’t adequate for the GWT-RPC or GWT events requirements.

In the next post I will describe the implementation of the extension in more detail.

Update 7/9/2010 – MyEclipse for Spring 8.6 now generates full ready-to-run GWT applications based on MVP and UI Binder in minutes. Just point the scaffolding wizard at your database tables, Java beans, or JPA Entities. You can learn more about it from the Generating Enterprise Class GWT applications for Spring post that I wrote on Genuitec blog. Or, you can keep reading my original post…

A few months ago I did a series of posts related to GWT, and in the posts I covered the creation of a Google Web Toolkit (GWT) application that uses Javascript/JSON services provide by the new Direct Web Remoting (DWR) generation feature [Video] of Skyway Builder 6.3.  The feedback to the DWR feature has been excellent.  Since Skyway Builder takes care of generating all the DWR configuration, AJAX developers are able to focus their efforts on development of the front-end.  While the DWR generation feature was the star of the series, writing the blog posts really sparked my interest in GWT.  As I investigated GWT further and experimented with other GWT development projects, I decided that I needed to revisit the integration between the GWT front-end and Spring-based back-end application.  With the help of others I came up with an implementation that I think is better than the DWR approach.  I also found that the implementation could be expedited using code generation, and I built a GWT extension to Skyway Builder that handles most of the work.  In the next few blog posts I will describe the GWT-Spring integration strategy and the implementation of the experimental Skyway Builder extension for GWT development.  At the end of the series I will provide a download link for the GWT extension for Skyway Builder.

Before I dive into the new GWT-Spring integration strategy let me point out that the Javascript/JSON approach described in the original posts is still perfectly valid.  I have talked to other GWT developers, and there is nothing wrong with the original approach.  As a matter fact using Javascript/JSON is highly recommended for scenarios where the back-end is not Java based.  However if you happened to be using Java back-end (like I do), GWT provides an RPC mechanism using Java servlets.  The primary benefit of GWT RPC is that the developer doesn’t need to worry about serialization/deserialization of data, and the GWT compiler has the opportunity to optimize the client-side RPC logic.

Let me take a moment to describe my ideal development scenario in regards to GWT and my Spring back-end.  Web applications are typically organized into layers, and the most common layers are web, service, domain and DAO.  If I’m developing an HTML application (traditional or light AJAX), then the web layer consists of my JSP pages and controllers, which call the application logic contained in the service layer.  I consider a GWT client to be an alternative to JSP pages and controllers in the web layer, and the GWT client should be able to leverage the same application logic in the service layer.  In the GWT/DWR blog post series the Spring DSL Services were DWR-enabled, making the respective Spring @Services accessible to clients via javascript and JSON.  I expect the GWT RPC mechanism to be structured in the same manner, and ideally the Spring @Services will be accessible as GWT RPC services.

While GWT RPC provides an RPC mechanism, there was still some work to be done to get it to talk to my Spring Services.  Not wanting to reinvent the wheel, I did some investigating on how others solved this problem, and I found the Spring4GWT project.  What Spring4GWT basically does is to make it easy to expose Spring @Services as GWT RPC services.  The @Services generated by the Spring DSL are already in excellent shape to use with Spring4GWT.  There were only two additional requirements to use Spring4GWT.  First of all I needed to register the Spring4GWT servlet for handling GWT RPC requests, and I also needed to modify the service interface to support GWT callbacks (AsyncCallback).  While these requirements are easy enough to do manually, the GWT extension for Skyway Builder will handle this (plus a few other things) automatically for you.  Automating this allows me to just focus on the services themselves, without being bothered by keeping the interfaces and Junit tests in sync.

What’s really cool about this is that when I combine the capabilities of the GWT extension with the Spring scaffolding capabilities of Skyway Builder, I can go from a database table (or set of tables) or domain object(s) to a fully implemented Service layer with GWT RPC support in less than a minute.  Furthermore if I enable the DWR and JAX-WS checkboxes, I have a scaffolded service layer that’s accessible using Java, Spring DI, GWT RPC, DWR and JAX-WS in less than 2 minutes.  However I digress.

My perspective may be uncommon, but I always look at development from the perspective of code generation.  While generating GWT RPC ready back-end Spring applications definitely accelerates GWT development, I found many other opportunities for GWT code generation that can further accelerate GWT development.  In this series of blog posts I will describe and share one of the additional GWT code generation functions, and this function is applicable to all GWT development….not just GWT development that’s using Spring back-ends.

While exploring GWT development I have been studying up a bit on  best practices on GWT development.  There’s an excellent presentation (Google Web Toolkit Architecture: Best Practices For Architecting Your GWT App) by Ray Ryan from Google that was very educational.  It’s a very worthwhile presentation, and I encourage all GWT developers to watch it at least once.  One of the recommendations of the presentation was to use an event bus.  Event buses are very interesting.  While it take a little bit more time to get it set up intially, I find event buses save a lot of time in the long run…and makes development much easier by decoupling GWT artifacts.  I adopted an EventBus implementation call GWT-EB.  While it worked very well, I found that creating events was a bit tedious.  Except for the event payload (the data that travels with the event), the implementation of events is mostly boilerplate code.  This seemed to me like a great opportunity for code generation.  So I added a code generation function to the GWT extension for Skyway Builder to generate the GWT Events.  With the GWT extension, creating events is now just a matter of giving it a name and specifying the payload (if applicable).  The GWT extension for Skyway Builder will generate the GWT events.

In the next few blog posts I will describe the development, installation and use of the GWT extension for Skyway Builder.  In addition to providing some GWT code generation that can be immediately used for GWT application development, it will serve as a good case study for extending the code generation features of Skyway Builder.

Stay tuned.

Update: Part 2 can be found here.

Gathering and validating user requirements is tedious, tough and thankless work for most IT organizations.  Requirements gathering typically takes a long time, especially in a large, complex organization.   And, unfortunately, even after spending a lot of effort on the task, most organizations still don’t get the requirements right up front.  This happens for a whole host of reasons and results in costly rework, frustrated users and unmet business needs.

I believe the primary reason application requirements are inaccurate and/or incomplete is because the process used to gather the requirements is in most organizations fundamentally flawed.

People, for the most part, are visual creatures.  This is best expressed by the common catch phrase “I’ll know it when I see it”.  Even if users actively participate in requirements gathering exercises and “sign off” on the requirements, they always reserve the right to object until they actually see a working system.

Unfortunately, most requirements gathering approaches today are heavy on the textual capture of user requirements – perhaps with some UI mock-ups done in HTML and process/application flows via Microsoft Visio.  This results in approaches that are very light on the actual validation of the requirements through use of software prototypes.

As a result, the first time many users actually see their requirements in the context of a working application is in the user acceptance testing phase of a project.  It’s at that point users typically say things like “that’s not right” or “that’s not what I meant”.   At this point, users and developers alike get pretty frustrated, and the non virtuous (and expensive) cycle of rework begins to implement the “real” requirements of the users within the application.

I firmly believe that no application system should be implemented that has not been prototyped.   Most IT organizations resist prototyping for two reasons: 1) the rationale that building a prototype may take just as long as developing the application,  and 2) the premise that the prototype itself will end up being largely throw away.  So while a software prototype will improve the accuracy of the requirements, it does so at the cost of essentially developing a system twice.  With this trade off, most IT organizations opt for “good enough” requirements that they know will have to be fixed once the user sees the application during user acceptance testing.

Using software generation technology like Skyway Builder, IT organizations can change this dynamic and make prototyping economical.  Skyway Builder enables the building of prototypes in weeks rather than the months it would take to build them using conventional development tooling.  In addition, because of Skyway Builder’s advanced data and web service discovery capabilities, these prototypes will enable you to validate what data the planned application will use and how to best access it.

Once a user sees and interacts with the software prototype the “that’s not what I meant/need” type comments still will arise.  However, they will be raised much earlier in the development process and will be much less expensive and time consuming to handle.  After a series of iterations using the prototype, the user will sign off on the requirements documentation with a much higher confidence level that their requirements have been captured accurately and completely.

The other benefit of using a true development platform like Skyway Builder for software prototyping is that up to 50% of the actual system will be developed during the prototyping phase.  The prototype isn’t throw away; it’s essentially a scaled-down version of the planned application and as such can be used downstream in the formal development process.  This dramatically reduces the time and expense needed to build out the desired system, often resulting in project schedules, efforts and costs 30% shorter than those using conventional requirements gathering approaches and tooling.  And most importantly, the application will be delivered right the first time due to software requirements validated through use of prototyping up front.

As I discussed in an earlier post, automated software generation technologies can dramatically improve the productivity of developers.   The business value of these tools is only increased when you consider the impact they can have on the effectiveness of the requirements gathering and validation process — effectively making software prototyping economical and practical.