星期二, 五月 07, 2013

Book Review: Arquillian Testing Guide




Today I have received my hard copy of the book, Arquillian Testing Guide. Comparing to the resource I had got at the end of last year, much content are improved.
Arquillian is a modern Java EE testing framework, based the well-known JUnit or TestNG, brought by JBoss.org.
In fact, currently Arquillian is beyond Java EE, and not only for Java EE application and Java EE container, such as it also supports Android application test and can run test in Android system(or Android simulator) . Most of my Arquillian experience is based on Java EE.
If you have some experience of JUnit experience before, and eager to find a testing solution for your Java EE application and want to run the test case in container automatically, this book is for you.
With Arquillian, you are free from preparing the test fixture before you write real tests. You can write tests in the nature way, such as using @Inject, @Resource etc in your test case directly as the way in your classes.
Let's have a look at what is included in the book.
Chapter 1 : What is Arquillian is a conceptual introduction to Arquillian, and also includes some some best practice to categorize the test case classes via Maven Profiles when you are using Maven.
Chapter 2: The Evolution of Testing is a review of the testing solution history for Java, especially for Java EE, and the pain and the lack of these legacy testing solution, and how Arquillian fills the blank table.
Chapter 3: Container Testing is a comprehensive reference of all popular Container supports. In this chapter, the popular embedded containers, managed containers, and remote containers will be introduced one by one. You can review this chapter frequently, when you are using Arquillian and some specific containers and encountering some problems in development .
Chapter 4: Why Did the Test Fail is a good beginning when you are a newbie of Arquillian, it will help find the reasons of the problems and resolve them gracefully when you are adopting Arquillian .
Chapter 5: Enriching the Enterprise Test Case , you will learn how to use Arquillian to test CDI and EJB in your enterprise application. It also provides some content for Spring application test with Arquillian.
Chapter 6: Arquillian Extensions extends what you have learned in Chapter 5, and introduces the JPA, Transaction testing, and it is also an introduction of the code coverage.
Chapter 7: Functional Application Testing , in this chapter you will learn how to use Selenium with Arquillian together, and use the Warp and Graphere arquillian extension to test modern Ajax and rich web application.
Chapter 8: Service Testing includes the approaches to test SOAP based web service and REST web service, also includes an introduction of JMS and Seam 2 testing.
Chapter 9: Arquillian and OSGI will introduce how to use Arquillian to test the OSGI bundle in JBoss and Glassfish application server.
Chapter 10: ShrinkWrap in Action is an excellent tutorial of the ShrinkWrap API, you can learn how to resolve the dependencies and package the test archive in detail.
You can review the detailed content table from the Arquillian Testing Guide book page of packt publishing website.
Thank the JBoss Arquillian Team for bringing the Arquillian to the Java world and a special thank to Johon D. Ament who wrote such a good book to all Arquillian fans. And thank Packt publishing for providing me excellent experience to review this book.
Enjoy reading!

星期一, 五月 06, 2013

Click4nb Update for NetBeans 7.3

I just updated the click4nb and rebuilt the source code against NetBeans IDE 7.3.

No new features added.

Follow the installation guide to install it into your IDE.

Installation

Read this wiki page to start your first Click application.

Getting Started with Apache Click and NetBeans IDE

Enjoy!

星期四, 十二月 20, 2012

Getting Started with Apache Click and NetBeans IDE

Note: this post is from my project wiki pages, please read https://github.com/hantsy/click4nb/wiki/Getting-Started-with-Apache-Click-and-NetBeans-IDE for the newest version. If you have some suggestion or find some errors, please file an issue. Thanks.

After moved from Google Code, I have cleaned the codes and just released a new version of click4nb, which was tested against the stable NetBeans IDE 7.2.

Installation

Following the steps in Installation wiki page to install click4nb into your NetBeans IDE.

Create a web project with Apache Click Support

Create a Web Application in NetBeans is very easy, follow the following steps to create one for yourself.
  1. Click the New Project button or click "File/New Project" menu from main menu in NetBeans IDE.
  2. In the popup New Project dialog, select Java Web in the Categories list, and Web Application in the "Projects", click Next button.
  3. In the Name and Location dialog, input the project related info, such Project Name, Project Location, Project Folder, click Next button.
  4. In the Server and Settings dialog, select an application server, for example, tomcat. If there is no servers in your NetBeans IDE, click Add... button to add one.
  5. In the Frameworks dialog, click the check box of the Click Framework in the list, make "Click" is selected.
    The basic configuration pane of Click framework will be showed in the below.
    There are two tabs in the panel.
    The main panel includes basic configuration, such defining a basic package name, and choose a mode in development phase, you can also add some extra features, such as Add Spring for adding Spring Click configuration and Spring Libraries, Enable Compression Filter for adding CompressionFilter to web.xml file, Enable Performance Filter for adding PerformanceFilter to web.xml file.
    CompressionFilter and PerformanceFilter are shipped with Apache Click release distribution.
    The Libraries panel includes two options to add Click library(jar files grouped by NetBeans) to the project. This plugin(click4nb) provides a configured a Click Library after you installed the plugin files. You can also define your own Click library, it will be organized by this plugin. You can also select None to skip adding Click Library directly.
  6. Click Finish button to complete the project creation.

Explore the project codes

Let us have a look at the codes generated click4nb.
Open web.xml under the Web Pages/WEB-INF in Projects view or you can find web.xml in Configuration Files folder, there is a web.xml bookmark for web.xml.
By default, it created a Click Servlet registration.
<servlet>
    <servlet-name>ClickServlet</servlet-name>
    <servlet-class>org.apache.click.ClickServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>ClickServlet</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

It also created click.xml and menu.xml configuration files at the same time.
If you enabled Add Spring when you created the project, it will use a Spring specified Servlet.
<servlet>
    <servlet-name>ClickServlet</servlet-name>
    <servlet-class>org.apache.click.extras.spring.SpringClickServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>ClickServlet</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
And also add extra Spring configuration.
For example, registered a contextConfigLocation context-param.
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
And registered Spring ContextLoaderListener.
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
And a spring configuration file named applicationContext.xml under WEB-INF was created.
In this file, it registered the Spring Click specific ScopeResovler.

<context:component-scan base-package="example.page" scope-resolver="org.apache.click.extras.spring.PageScopeResolver "/>
If you enabled CompressionFilter or PerformanceFilter in the creation phase, it will add extra codes into web.xml.

<filter>
    <filter-name>CompressionFilter</filter-name>
    <filter-class>org.apache.click.extras.filter.CompressionFilter</filter-class>
</filter>
<filter>
    <filter-name>PerformanceFilter</filter-name>
    <filter-class>org.apache.click.extras.filter.PerformanceFilter</filter-class>
    <init-param>
        <param-name>cachable-paths</param-name>
        <param-value>/assets/*</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CompressionFilter</filter-name>
    <servlet-name>ClickServlet</servlet-name>
</filter-mapping>
<filter-mapping>
    <filter-name>PerformanceFilter</filter-name>
    <servlet-name>ClickServlet</servlet-name>
</filter-mapping>
<filter-mapping>
    <filter-name>PerformanceFilter</filter-name>
    <url-pattern>*.css</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>PerformanceFilter</filter-name>
    <url-pattern>*.js</url-pattern>
</filter-mapping>
But in the development stage, it is better to disable the two filters.

Run the project

In NetBeans IDE, running a project is easy work. Just right click the project node, and select Run or click the Run button in the toolar, and wait for few seconds, it will start the application server if it is stopped, and then deploy the web application into the application server.
After all are done, it will open a browser window and display the index page of the web application.

Hello, Click

We have created a Clicked based web application and have run it on application server.
Now let us add some codes into this project.
By default, it includes a simple home.htm and Home.java to display the current datetime.
The content of Home.java.
public class Home extends Page {

    private Date time = new Date();    

    public Home() {
       addModel("time", time);
    }
}
A click page must be derived from Click Page class.
The content of the home.htm(only copied the content of the body tag here).
<div id="header">
<span id="title">Home</span>
</div>
<div id="container">
Greetings from Click Framework at $time.
</div>

No surprise, it is very simple and direct. By default, Apache Click use Apache Velocity as template engine. It can be configured the click.xml file, the popular Freemarker template engine is also supported.
Let us create a new Click page now.
There are two ways to open the Creation wizard. The generic way is using the wizard.
If your cursor is focusing on the click.xml, and Alt+Insert to select New Page to open the Click Page creation dialog.
  1. Click New File from File menu or New File button on the toolbar to open New File dialog.
  2. In the popup New File dialog, choose Apache Click Framework from "Categories" list and Click Page from "File Types", click Next button.
  3. In the New Click Page dialog, you can fill the page.
    This wizard provides two templates for you, "Blank" and "Simple Form". If "Blank" is selected, it will create a blank template page and page for you. The "Simple Form" one add an extra form tag for you by default.
    By default, it will create a Java class and a template file for you.
    You can input the Page Class name, the template name will be generated by the Apache Click rule automatically.
    The package name, you can select a existing package or input a new one.
    The Add mapping to click.xml provides an option for you if your page class and template do not apply the Click rule. A custom mapping will be added into click.xml file.
    In this exercise, input the following values.
    Template: select "Simple Form"
    Class Name: Greeting
    Package Name: select the existing example.page
    Leave other fields as default, click Finish button.
  4. Change the content of GreetingForm class.

    private Form form = new Form("form"); 
     public GreetingForm() {
         addControl(form);
         form.add(new TextField("name", "Greeting Name", 50,  true));
         form.add(new Submit("OK"));
         form.setListener(this, "onSubmit");
     } 
    
     public boolean onSubmit() {
         if (form.isValid()) {
             String  msg = "Your name is " + form.getFieldValue("name");
             addModel("msg", msg);
         }
         return true;
     }
    We added a Form control in the page, and add a TextField field to the form, and add a Submit button to the form to submit the form.
    When the form is submitted, the form will invoke Form listener(onSubmit) to process to the submit action, firstly fetch the input value from text field, and display it in the page.
    Open the greeting-form.htm file, and chnage the content slightly, just add some code fragments to display msg.

    $form
    #if ($msg)
       <div id="msgDiv">
    $msg </div>
    #end
  5. Run the project again, open web browser and navigate http://localhost:8080/ /greeting-form.htm.

Next step

Now it is your turn.
Read the official user guide from official Apache Click website.
Enjoy programming with Apache Click and NetBeans IDE. ;)

星期二, 十月 23, 2012

Generate reports with Seam 3 Reports and Apache Velocity

Seam 3 provides a collection of standard CDI extensions. Seam3 report module bridges CDI and several report engines, such as

Basic Configuration

Assume you have already created a Maven based Java EE 6 application. If not, you can create one using JBoss Forge.
Add Seam 3 reports related dependencies into your pom.xml.
  <dependency>
        <groupId>org.jboss.seam.reports</groupId>
        <artifactId>seam-reports-api</artifactId>
        <version>${seam-reports-version}</version>
  </dependency>

  <!-- If you are using Jasper Reports, add the following dependency --> 
  <dependency>
        <groupId>org.jboss.seam.reports</groupId>
        <artifactId>seam-reports-jasper</artifactId>
        <version>${seam-reports-version}</version>
  </dependency>
Generally, in order to generate a JasperReports based report in a Seam 3/Java EE6 project, you could consider the following steps:
  1. Create JasperRoports jrxml file using iReports or JasperStudio
  2. Compile jrxml file to PDF
You can use the official JaperReports Studio(for Eclipse users) or iReports(for NetBeans users) to create the reports template source file.
In your java code, inject JasperReports compiler to compile the jasperReports source, and JasperReports renderer to render the compiled result.
  @Inject
  @Jasper
  private transient ReportCompiler compiler;

  @Inject
  @PDF
  @Jasper
  private transient ReportRenderer pdfRenderer;
The @Jasper annotation states we will use JasperReports as report engine, @PDF is the final generated document format.
    ReportDefinition report;
    try {
        report = compiler.compile(<JasperReporst source>);
        Report reportInstance = report.fill(<JR DataSource>, null);

        pdfRenderer.render(reportInstance,
                externalContext.getResponseOutputStream());
    } catch (ReportException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
JRDataSource is a JasperReports specified "datasource" which is responsible of gathering the data for report generation. JasperReports provides several implementations natively, please refer to the JRDataSource javadoc for more detailed info. In this case, we have got a list, we can use JRBeanCollectionDataSource to wrap the existing list and use it in this reports.
Everything works well.
But personally, I dislike the jrxml syntax and do not want to use jrxml syntax to fill data, I only want to use JasperReports as report engine. I am familiar with Apache Velocity, is possible using Velocity as template and fill data?

Improve the codes with Apache Veloctiy

Now change the report generation process slightly, and introduce an extra step to generate the pure jrxml.
  1. Create a velocity template source(embed velocity syntax into jrxml)
  2. Convert the velocity template to pure jrxml
  3. Compile the jrmxl to PDF.
Create a jrxml firstly, and embed the velocity syntax.
  <detail>
        <band height="125" splitType="Stretch">
            #set( $y = 0 )
            #foreach($obj in $contacts)
            <staticText>
                <reportElement  x="0" y="$y" width="177" height="20"/>
                <textElement textAlignment="Left" verticalAlignment="Middle"/>
                <text><![CDATA[$!obj.name]]></text>
            </staticText>
            <staticText>
                <reportElement  x="177" y="$y" width="200" height="20"/>
                <textElement textAlignment="Left" verticalAlignment="Middle"/>
                <text><![CDATA[$!obj.phoneNumber]]></text>
            </staticText>
            <staticText>
                <reportElement x="377" y="$y" width="178" height="20"/>
                <textElement textAlignment="Left" verticalAlignment="Middle"/>
                <text><![CDATA[$!obj.emailAddress]]></text>
            </staticText>
            #set($y = $y + 20)
            #end
        </band>
    </detail>
In java codes, firstly fill data in the velocity based jrxml, then convert it to pure jrxml, finally compile it to PDF document.
    InputStream sourceTemplate = resourceProvider
            .loadResourceStream(reportTemplate);

    Map<String, Object> _values = new HashMap<String, Object>();
    _values.put("contacts", contacts);
    _values.put("usd", "$");

    String stringReport = new VelocityTemplate(sourceTemplate,
            velocityContext).merge(_values);

    if (log.isDebugEnabled()) {
        log.debug("report source file content@" + stringReport);
    }
    // source
    ReportDefinition report;
    try {
        report = compiler.compile(new ByteArrayInputStream(stringReport
                .getBytes("UTF-8")));
        Report reportInstance = report.fill(new JREmptyDataSource(), null);

        pdfRenderer.render(reportInstance,
                externalContext.getResponseOutputStream());
    } catch (ReportException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
Note, the velocity support is from the Seam3 mail module.
In the Seam3 repository, there is a standalone renderer module for rendering template, but it is not released a stable version at the moment.
So you have to add Seam3 mail dependencies in your pom.xml.
    <dependency>
        <groupId>org.jboss.seam.mail</groupId>
        <artifactId>seam-mail-api</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.seam.mail</groupId>
        <artifactId>seam-mail</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity</artifactId>
    </dependency>

Run the project

I assume you have installed the latest Oracle JDK 7, JBoss AS 7.1.1.Final and Apache Maven 3.0.4.
  1. Check out the complete codes from github.com.
    git clone git://github.com/hantsy/seam3-report-demo.git
    
  2. Start JBoss AS from command line.
    <JBOSS_HOME>\bin\standalone.bat
    
  3. Deploy the application into the running JBoss AS.
    mvn clean package jboss-as:deploy
    
  4. Open your browser and go to http://localhost:8080/seam3-reports-demo.

Send email with Seam 3 Mail and JMS

Seam 3 Mail module provides simple API to use Java Mail API to send email message.

Basic Configuration

Assume you have already created a Maven based Java EE 6 application.

Add seam mail dependency to your pom.xml file.

<dependency>
    <groupId>org.jboss.seam.mail</groupId>
    <artifactId>seam-mail-api</artifactId>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.jboss.seam.mail</groupId>
    <artifactId>seam-mail</artifactId>
    <scope>compile</scope>
</dependency>

Add basic mail configuration in your META-INF/seam-beans.xml.

<mail:MailConfig serverHost="smtp.gmail.com"
    serverPort="587" 
    auth="true" 
    enableTls="true" 
    username="<your gmail account>"
    password="<your password>">
    <ee:modifies />
</mail:MailConfig>

In your Java codes, inject MailMessage and Session.

@Inject
private transient Instance<MailMessage> mailMessage;

@Inject
private transient Instance<Session> session;

MailMessage is provided by Seam3 module, it is a fluid API to build message object and send message. Session is from the standard Java Mail API.

MailMessage msg = mailMessage.get();
msg.subject("test subject")
    .from("test@test.com")
    .to("user@test.com")
    .send();

Everything works well.

But if you try to send an email from jsf pages, the page will be blocked when the email is being sent.

EJB 3.1 provides a simple way to execute asynchronous action. You can simply create a @Stateless EJB and put the logic in a @Asynchronous method. But unfortunately when you try to use @Asynchronous and CDI together, it does not work.

JMS provides standard asynchronous processing capability for Java EE, Seam3 also includes a JMS module.

Send email asynchronously with JMS

Seam 3 also provides a JMS module which simplify JMS and CDI integration, we can utilize JMS to process the asynchronous work.

Configure the JMS connection factory in your META-INF/seam-beans.xml.

<jmsi:JmsConnectionFactoryProducer>
    <ee:modifies />
    <jmsi:connectionFactoryJNDILocation>
        java:/ConnectionFactory
    </jmsi:connectionFactoryJNDILocation>
</jmsi:JmsConnectionFactoryProducer>

Create a standard JMS listener to handle JMS message.

@MessageDriven(....)
public class MailProcessorMDB extends MessageListener {

    @EJB MailProcessor processor;

    public void send()...//

    @Override
    protected void onMessage(Message _msg) throws JMSException {
        if (log.isDebugEnabled()) {
            log.debug("call handleMessage...");
        }

        ObjectMessage objMessage = (ObjectMessage) _msg;
        EmailMessage mailMessage = (EmailMessage) objMessage.getObject();
        processor.send(mailMessage);
    }
}

MailProcessor is a @Stateless EJB which is use for sending mail.

When a message is arrived, the listener will call MailProcessor to process email.

Use an interface to observe the CDI event and route it to the JMS queue.

@Outbound
public void mapStatusToQueue(@Observes @NoneBlocking EmailMessage message,
        @JmsDestination(jndiName = "java:/queue/test") Queue q);

In the presentation layer, fire an event directly. The event object will be routed as the payload of JMS message automatically.

messageEventSrc.fire(message);

Run the project

I assume you have installed the latest Oracle JDK 7, JBoss AS 7.1.1.Final and Apache Maven 3.0.4.

  1. Check out the complete codes from github.com.

    git clone git://github.com/hantsy/seam3-mail-demo.git
    
  2. Start JBoss AS with standalone full profile which includes JMS support.

    <JBOSS_HOME>\bin\standalone.bat --server-config=standalone-full.xml
    
  3. Deploy the application into the running JBoss AS.

    mvn clean package jboss-as:deploy
    
  4. Open your browser and go to http://localhost:8080/seam3-mail-demo.

星期五, 五月 14, 2010

Click4nb 1.1.1 is available now

Click4nb 1.1.1 is available for downloading now. I have uploaded the file to Google Code and NetBeans Plugin center.

Get it and try.

This release does not provide more new features but an improvement for Page class hyperlink support( Issue 1 ).

Currently, click4nb works well on NetBeans 6.8.

I will move my development envoriment ot NetBeans 6.9 for the next version.
In the next version, I will try my best to implement the following features.
1. Add click 2.2 support (Cllick team has just release the first RC of Click 2.2), update the libary to Click 2.2 and improve the Content Assistance for 2.2.
2. Intergrate Cayenne Modeler into NetBeans IDE, add a action to open Cayenne file directly in NetBeans IDE.
3. Configuration for Cayenne ORM framework and Click intergration.

Feel free to submit your feedback by email( hantsy@tom.com ) or leave message on this blog, you can also report your bug in theissue tracker.

星期四, 三月 25, 2010

Click Plugin for NetBeans 1.1 is avai...

Click Plugin for NetBeans 1.1 is available now

Due to the shutdown of Kenai.com, I decided to move this project to Google Code.
You can access from the new host page.
http://code.google.com/p/click4nb/

Some features are provided in 1.1:
1. Click library update to 2.1 release.
2. You can customize a Click library, and create web project using your click library. see bug:NBX-1


3. CssImport and JsImport hyperlink support. see NBX-2


4. If more than one templates are mapped to one page class, it will popup a panel for you to select which file to open.


You can download it from NetBeans Plugin portal or Google Code.



星期三, 十月 21, 2009

Click for NetBeans plugin 1.0 is avai...

Click for NetBeans plugin 1.0 is available now.
I am very pleased to announce that the first version of Click for netBeans plugin is available now. You can get it from the Kenai.com or NetBeans plugin portal.

Click is a simple, but effective and component based web framework, it hosts on the Apache as a incubator project.

This plugin bring basic Click support for NetBeans IDE.
It includes the following features:
1、Project creation wizard.
2、Click Page creation wizard(the interface cloned clickide).
3、Provide basic error checkshyperlinkcode templatescode completionrefacotoring in click.xml file.
4、Also provide hyperlinkcode templatescode completion in menu component configuration file.
5、Switch between Page Template, Page Class , Page properties quickly。


This project is open source under GPL, it hosts on kenai.com.
Homepage:http://kenai.com/projects/nbx

User Forum:http://kenai.com/projects/nbx/forums/user-forum

Mail List:http://kenai.com/projects/nbx/lists

Bugzilla: http://kenai.com/bugzilla/buglist.cgi?product=nbx&order=Importance&limit=25

Svn Repository: http://kenai.com/projects/nbx/sources/subversion/show


Thank Rohan Ranade for helping me during the development progress.


Try it now.