CHAPTER 16

image

Enterprise Solutions Using Alternative Programming Languages

Dozens of programming languages are available for use on the Java platform; the Java language is no longer the only available language for developing applications on the JVM. Nowadays, developers have their choice of a wide variety of languages when developing for the JVM, from small scripting languages to statically typed languages that have their own sets of libraries. Although developers of Java EE 7 applications are interested in utilizing the technology stack that encompasses the Java enterprise, in some cases alternative languages can provide a more dynamic and sometimes easier development life cycle than using Java.

In this chapter, I will cover how to develop enterprise applications on the JVM using alternative languages. The recipes in this chapter will cover solutions utilizing two of the most popular alternative languages for the JVM: Groovy and Jython. Although this chapter will delve into some specific enterprise solutions that can be provided via the use of these three languages, you should not read this chapter as a means of learning these two alternative solutions. Rather, this chapter should serve as a starting point for creating entire or partial enterprise solutions for the JVM using alternative languages.

The Groovy language has a very similar syntax to that of Java. It has been embraced by a large number of loyal Groovy coders for its ease of use, its productive syntax, and its easy integration into Java-based application solutions. Groovy maintains a tight integration with the Java language in that Groovy source can include Java source, import and use Java libraries, and so forth. Groovy is compiled on the fly, so it is an easy way to develop applications very quickly. This chapter includes a couple of examples that demonstrate how to integrate Groovy servlets into a Java EE application. It is possible to set up advanced configurations, allowing Groovy code to be used for the development of EJB classes and other Java EE technology via the utilization of build systems such as Maven, but those topics are out of scope for this book. That said, Groovy is an easy way to supplement an existing Java EE application, although it takes some advanced configuration to develop an entire Java EE application using only Groovy.

The Jython language is a port of the Python language that runs on the JVM. Much of the Jython community uses it for its elegant syntax and its dynamic tendencies. Jython, just like Groovy, is very helpful to use for adding servlet content to existing Java EE applications. Therefore, it is also a very useful supplement to any Java EE application.

This chapter will cover a handful of recipes that show how to integrate Groovy and Jython into your Java EE projects in order to use their productive syntax and dynamic compilation tendencies. Adding each of these alternative languages, as well as others (JRuby, Clojure, Scala, and so on), to existing Java EE applications can enhance the functionality and productivity all around.

16-1. Developing Servlets with Groovy

Problem

You want to utilize a robust alternative language to create servlets for your enterprise application.

Solution

Develop Groovy servlets (groovlets) and integrate them into your enterprise application. The following example Groovy servlet demonstrates how to retrieve values from a database using Groovy and display them within a servlet. In this example, the Acme Bookstore database is queried for the book titles within the BOOK table. The titles are then displayed within the servlet. You can find the code for the following example within the JavaEERecipes project within the web/chapter16 / BookstoreServlet.groovy file.

image Note   This example utilizes the Oracle database driver for connectivity, not JPA.

import groovy.sql.Sql

def sql = Sql.newInstance("jdbc:oracle:thin:@host:1521:database", "user",
        "password", "oracle.jdbc.driver.OracleDriver")

html.html()
{
    head()
    {
        title 'Acme Bookstore Book List'
    }
    body()
    {
        print '<p>The list of books:<br/><br/>'
        sql.eachRow("select * from Book"){
            println "$it.title </br></br>"
        }
        print '</p>'
    }
}

In the previous example, take note of the $it keyword. In Groovy syntax, this keyword provides a handle to the currently available object within a closure body. The sql.eachRow method performs the given SQL query, allowing traversal of the results. The servlet will display the list of books, as follows:

The list of books:
Java 7 Recipes
Java EE 7 Recipes
The Definitive Guide to Jython
Oracle PL/SQL Recipes

How It Works

Developing servlets in an alternative language can increase developer productivity, and it can also allow for dynamic code updates since many alternative languages can compile on the fly. One such language that provides a productive syntax and can be compiled dynamically is Groovy. It is very easy to develop servlets using the Groovy language because any Java web application can simply route Groovy files to a special servlet that compiles and displays the content at will. Any file that is passed to groovy.servlet.GroovyServlet is treated as a Groovy servlet, compiled, and translated, and then the output is displayed within the browser. To route requests to the GroovyServlet, you must configure a url-pattern that will be used to pass certain files to the GroovyServlet. This configuration can be done within the web-xml deployment descriptor as follows:

<servlet>
    <servlet-name>GroovyServlet</servlet-name>
    <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
</servlet>
  
<servlet-mapping>
    <servlet-name>GroovyServlet</servlet-name>
    <url-pattern>*.groovy</url-pattern>
</servlet-mapping>

The GroovyServlet can be added to an application by including the groovy-all-x.x.x.jar file in your CLASSPATH, where x.x.x is the Groovy version number. This JAR file will allow you to utilize all of the Groovy essentials, and it is nicely bundled into a single JAR for convenience.

There are a couple of tactics that can be taken when writing a Groovy servlet. In the solution to this recipe, a Groovy MarkupBuilder is used to create the servlet. Groovy builders are great for building a tree of objects. In this case, they are great for dealing with HTML. Rather than coding HTML tags, the markup builder allows you to code elements using the Groovy syntax, rather than working directly with XML. Groovy servlets implicitly define the following lines of code at the top of each servlet being invoked:

import groovy.xml.*
def writer = new StringWriter()
def html = new MarkupBuilder(writer)

The fact that these lines of Groovy are always invoked when a servlet is initiated means you can get right into coding the servlet using Groovy’s MarkupBuilder with no setup at all. As you can see from the example servlet, the html object is never created because it all occurs behind the scenes. Utilizing the markup builder syntax, you can create a parent element and then define subelements within the parent by naming an element accordingly; using an open/close bracket syntax, as in { ... }; and encompassing all of an element’s subelements between its opening and closing bracket. Since the HTML markup builder contains specific elements for the different portions of an HTML page, each of those elements carries attributes specific to the type of element it is. For instance, the head() element contains a title attribute, so placing the title My Title within the head element will assign “My Title” to the HTML page. Running down the example, the body() element consists of a couple of print statements, along with a SQL loop. Simply invoking the print statement within an element will cause the string contained within the print statement to be printed to the markup. Therefore, the following lines of markup:

body() {
    print  '<p>The list of books:</p>'
}

will generate the following HTML:

<body>
    <p>The list of books.</p>
 </body>

Furthermore, any HTML element can be specified as an entity using the MarkupBuilder. That is, if you would rather not use print statements, then the following syntax could achieve the same effect as the previous MarkupBuilder code:

body(){
    p 'The list of books.'
}

Remember when I mentioned that the print statement will produce HTML output for whatever is contained within the String that is passed to it? Well, if you prefer to use HTML markup, then you can simply use a print statement and then enclose the HTML markup that you want to use within the String as follows:

print '
    <html>
        <body>
            <p>The list of books:</p>
        </body>
    </html>'

Solutions such as those shown can be produced with standard JSF and XHTML quite easily, but if you want to perform all of the processing and view code in the same file, then using a Groovy servlet can be the way to go. Even if you prefer to include only JSF XHTML views within an application, it makes sense to prototype with Groovy servlets in some circumstances. Groovy servlets provide a quick way to produce a dynamic servlet that can be used for testing purposes while producing web applications. Groovy servlets have a number of purposes, and they can be included in any Java EE application by simply adding the groovy-all-xxx.jar file to the CLASSPATH.

16-2. Working with Groovy Servlet Parameters

Problem

You want to create a form that accepts input and passes the input to another form using the Groovy language.

Solution

Create an input form using a Groovy servlet, and invoke another Groovy servlet when the form is submitted, passing the input as parameters to the second form. The following example demonstrates the use of two Groovy servlets that pass data from one to the other. The following source, taken from ParameterExample.groovy, constructs an input form using MarkupBuilder, and upon submission, the form will activate the BookstoreServletAction.groovy servlet:

html.html()
{
    head()
    {
        title 'Acme Bookstore Groovy Parameters'
    }
    body()
    {
        
        form(method: 'GET', action: 'BookstoreServletAction.groovy') {
            b'First Name: '
            input(type: 'text', name:'firstName')
            br{}
            b'Last Name: '
            input(type: 'text' ,name:'lastName')
            br{}
            input(type: 'submit', value:'Submit Values')
        }
    }
}

Next is the source for the receiving servlet, BookstoreServletAction.groovy:

html.html()
{
    head()
    {
        title 'Processing Values'
    }
    body()
    {
        String first = request.getParameter('firstName'),
        String last = request.getParameter('lastName'),
  
        h1 "Hello ${first} ${last}"
    }
}

The values that are entered into the text fields within the first Groovy servlet are passed to the second Groovy servlet as request parameters and then displayed as messages.

How It Works

Two or more Groovy servlets can pass information among each other via the utilization of forms and request parameters. This solution demonstrates simply that an entire web application can be constructed from Groovy servlets. One Groovy servlet can invoke another via a GET or POST form action. Calls to Java libraries, database queries, and so on, can all occur directly within the servlet code, although this type of coding is not recommended since it does not adhere to the Model-View-Controller (MVC) pattern.

In the solution to this recipe, two input text areas are displayed via the initial servlet, ParameterAction.groovy. The content from both of those forms is then submitted via an HTML form, which has an action attribute set to BookstoreServletAction.groovy, which is the name of another Groovy servlet. When the form is submitted, the request is then sent to the servlet that is set within the action attribute, which is then displayed. The BookstoreServletAction.groovy servlet processes the request by obtaining each parameter that was sent to it via a String-based name and storing the values of each property to local variables. The servlet then simply prints out the contents of those variables. However, this example demonstrates an important feature of Groovy: variable substitution. It is easy to substitute a variable within a String by prefixing the name of the variable with a $ character.

16-3. Developing Servlets with Jython

Problem

You want to utilize a mature and robust alternative language to create servlets for your enterprise application.

Solution

Develop a servlet with the Python syntax using the Jython language. To add support for Jython to a Java EE application, you must add the jython.jar file to your CLASSPATH and configure the web.xml deployment descriptor to use org.python.util.PyServlet whenever a file that includes a .py suffix is invoked from a browser.

First, let’s configure the web.xml deployment descriptor accordingly. The following excerpt, taken from the web.xml deployment descriptor of the JavaEERecipes sources, demonstrates how to add Jython servlet support to an application:

<servlet>
       <servlet-name>PyServlet</servlet-name>
       <servlet-class>org.python.util.PyServlet</servlet-class>
       <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
       <servlet-name>PyServlet</servlet-name>
       <url-pattern>*.py</url-pattern>
    </servlet-mapping>

Once the web.xml file has been set up correctly, you can add Jython servlet files (including a .py suffix) anywhere that web files (.xhtml, .js, and so on) are located within your application. The following code is that of the BookstoreJython.py servlet, which resides within the JavaEERecipes web/chapter15 folder:

from org.python.core.FutureFeature import with_statement
from com.ziclix.python.sql import zxJDBC
from javax.servlet.http import HttpServlet

 

 
jdbc_url = "jdbc:oracle:thin:@host:1521:database"
username = "user"
password = "password"
driver = "oracle.jdbc.driver.OracleDriver"

class BookstoreJython (HttpServlet):

    def doGet(self, request, response):
        self.doPost(request, response)

    def doPost(self, request, response):
        response.setContentType("text/html")
        out = response.getWriter()

        htmlbody = """<h1>Acme Bookstore</h1>
                      <br/>
                      <p>List of books: """ + """</p>"""
        with zxJDBC.connect(jdbc_url, username, password, driver) as conn:
            with conn:
                with conn.cursor() as c:
                    c.execute("select title from book")
                    books = c.fetchall()
                    for book in books:
                        htmlbody = htmlbody + """%s <br/>""" % (book,)
        out.println(self.convertHtml('Acme Bookstore', htmlbody))

    def convertHtml(self, title, info):
        return """<html>
                      <head><title> """ + title + """ </title></head>
                      <body> """ + info + """</body>
                  </html>"""

    def getServletInfo(self):
        return "This servlet returns a list of books in the Acme Bookstore"

The servlet can be invoked by deploying the JavaEERecipes project to your application server and then entering the following URL into your browser: http://localhost:8080/JavaEERecipes/chapter16/BookstoreServlet.py.

How It Works

Utilizing Jython for servlet development can be quite handy, especially if you envision a need for dynamically updating the servlet or changing it without recompiling. Setting up a project for using Jython is relatively simple and involves only the requirement for the jython.jar file to be included in the application CLASSPATH and a servlet configuration within the web.xml deployment descriptor. In the solution to this recipe, an excerpt from the web.xml deployment descriptor shows how to map org.util.python.PyServlet to a url-pattern in order to invoke the Python/Jython interpreter. Once the web.xml file has been configured to use this servlet mapping, then you can begin to include files containing Jython code with the suffix of .py within the web source directories of your application. When a URL containing a Jython servlet file is invoked, the servlet code is passed to the PyServlet, interpreted into Java, and compiled on the fly, and then the results are posted.

The Jython servlet in the solution to this recipe demonstrates how to make a database call in order to obtain a list of records. The zxJDBC API, a Jython-proprietary library, is used to obtain a database connection, query, and return the results to the servlet. Other than the database invocation, the Jython servlet is simply a translation of Java to Python. That is, the Java code that is used to implement a servlet is simply translated into Python syntax. Breaking it down, there are doGet(HttpRequest, HttpResponse) and doPost(HttpRequest, HttpResponse) functions that perform the exact tasks as their Java counterparts would. A variable named out is set to response.getWriter(), which then causes the output to be printed to the page. The bulk of the processing occurs within the doPost function, where a String named htmlbody is assigned a string of HTML markup and then passed to the convertHTML function, which has the responsibility of wrapping the strings passed into it with the appropriate tags to produce an HTML page. Within the doPost function, a with_statement is utilized to connect to the underlying database, query the BOOK table, and iterate through each record that is returned. While iterating through the records, the htmlbody variable is continuously updated, adding the title of the next book record that is obtained from the database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.93.12