Home » Java » Enterprise Java » Project Student: Maintenance Webapp (read-only)

About Bear Giles

Bear Giles

Project Student: Maintenance Webapp (read-only)

This is part of Project Student. Other posts are Webservice Client With Jersey, Webservice Server with Jersey, Business Layer, Persistence with Spring Data, Sharding Integration Test Data, Webservice Integration and JPA Criteria Queries.

When I started this project I had four goals. In no particular order they were to:

  • learn about jQuery and other AJAX technologies. For that I needed a REST server I understood,
  • capture recently acquired knowledge about jersey and tapestry,
  • create a framework I could use to learn about other technologies (e.g., spring MVC, restlet, netty), and
  • have something to discuss in job interviews

If it was useful to others – great! That’s why it’s available under the Apache license.

(It should go without saying that acceptable uses does not include turning “Project Student” into a student project without proper attribution!)

The problem with learning AJAX is that I’ll initially be uncertain where the problem lies. Is it bad jQuery? A bad REST service? Something else? The extensive unit and integration tests are a good start but there will always be some uncertainty.

The other consideration is that in the real world we’ll often need a basic view into the database. It won’t be for public consumption – it’s for internal use when we hit a WTF moment. It can also be used to maintain information that we don’t want to manage via a public interface, e.g., values in pulldown menus.

A small twist on this can be used to provide a modest level of scalability. Use hefty servers for your database and REST service, then have N front-end servers that run conventional webapps that act as an intermediary between the user and the REST service. The front-end servers can be fairly lightweight and spun up on an as-needed basis. Bonus points for putting a caching server between the front ends and the REST server since the overwhelming fraction of hits will be reads.

This approach won’t scale to Amazon or Facebook scales but it will be good enough for many sites.

Maintenance Webapp

This brings us to the optional layers of the webapp onion – a conventional webapp that acts as a frontend to the REST service. For various reasons I’m using Tapestry 5 for the application but it’s an arbitrary decision and I won’t spend much time delving into Tapestry-specific code.

You can create a new tapestry project with

$ mvn archetype:generate -DarchetypeCatalog=http://tapestry.apache.org

I’ve found the examples at http://jumpstart.doublenegative.com.au/jumpstart/examples/ invaluable. I’ve kept in attribution where appropriate.

Later I will also create the second optional layer of the webapp – functional and regression tests with Selenium and WebDriver (that is, Selenium 2.0).


Read-only – spinning up the webapp takes a lot of work so the initial version will only provide read-only access of simple tables. No updates, no one-to-many mappings.

User Authentication – no effort has been made to authenticate users.

Encryption – no effort has been made to encrypt communications.

Database Locks – we’re using opportunistic locking with hibernate versions instead of explicit database locks. Security note: under the principle of least disclosure we don’t want to make the version visible unless it’s required. A good rule is that you’ll see if it you request a specific object but not see it in lists.

REST Client – the default GET handler for each type is very crude – it just returns a list of objects. We need a more sophisticated response (e.g., the number of records, the start- and end-index, a status code, etc.) and will let the UI drive it. For now the only thing we really need is a count and we can just request the list and count the number of elements.


We want a page that lists all courses in the database. It does not need to worry about pagination, sorting, etc. It should have links (possibly inactive) for editing and deleting a record. It does not need to have a link to add a new course.

The page should look something like this:


Course template

The Tapestry page listing courses is straightforward – it’s basically just a decorated grid of values.

(See the tapestry archetype for Layout.tml, etc.)

<html t:type="layout" title="Course List"
      t:sidebarTitle="Framework Version"
        <!-- Most of the page content, including <head>, <body>, etc. tags, comes from Layout.tml -->

    <t:zone t:id="zone">   
            "Course" page

        <t:grid source="courses" row="course" include="uuid,name,creationdate" add="edit,delete">
                <t:pagelink page="CourseEditor" context="course.uuid">${course.name}</t:pagelink>
                <t:actionlink t:id="edit" context="course.uuid">Edit</t:actionlink>
                <t:actionlink t:id="delete" context="course.uuid">Delete</t:actionlink>
              <p>There are no courses to display; you can <t:pagelink page="Course/Editor" parameters="{ 'mode':'create', 'courseUuid':null }">add some</t:pagelink>.</p>

            <t:pagelink page="Index">Index</t:pagelink>
            <t:pagelink page="Course/List">Courses</t:pagelink>

with a properties file of

delete-course=Delete course?

I’ve included the actionlinks for edit and delete but they’re nonfunctional.


Our page needs a source for the values to display. This requires two classes. The first defines the courses property used above.

package com.invariantproperties.sandbox.student.maintenance.web.tables;

import com.invariantproperties.sandbox.student.business.CourseFinderService;

public class GridDataSources {
    // Screen fields

    private GridDataSource courses;

    // Generally useful bits and pieces

    private CourseFinderService courseFinderService;

    private Grid grid;

    // The code

    void setupRender() {
        courses = new CoursePagedDataSource(courseFinderService);

and the actual implementation is

package com.invariantproperties.sandbox.student.maintenance.web.tables;

import com.invariantproperties.sandbox.student.business.CourseFinderService;
import com.invariantproperties.sandbox.student.domain.Course;
import com.invariantproperties.sandbox.student.maintenance.query.SortCriterion;
import com.invariantproperties.sandbox.student.maintenance.query.SortDirection;

public class CoursePagedDataSource implements GridDataSource {

    private int startIndex;
    private List<Course> preparedResults;

    private final CourseFinderService courseFinderService;

    public CoursePagedDataSource(CourseFinderService courseFinderService) {
        this.courseFinderService = courseFinderService;

    public int getAvailableRows() {
        long count = courseFinderService.count();
        return (int) count;

    public void prepare(final int startIndex, final int endIndex, final List<SortConstraint> sortConstraints) {

        // Get a page of courses - ask business service to find them (from the
        // database)
        // List<SortCriterion> sortCriteria = toSortCriteria(sortConstraints);
        // preparedResults = courseFinderService.findCourses(startIndex,
        // endIndex - startIndex + 1, sortCriteria);
        preparedResults = courseFinderService.findAllCourses();

        this.startIndex = startIndex;

    public Object getRowValue(final int index) {
        return preparedResults.get(index - startIndex);

    public Class<Course> getRowType() {
        return Course.class;

     * Converts a list of Tapestry's SortConstraint to a list of our business
     * tier's SortCriterion. The business tier does not use SortConstraint
     * because that would create a dependency on Tapestry.
    private List<SortCriterion> toSortCriteria(List<SortConstraint> sortConstraints) {
        List<SortCriterion> sortCriteria = new ArrayList<>();

        for (SortConstraint sortConstraint : sortConstraints) {

            String propertyName = sortConstraint.getPropertyModel().getPropertyName();
            SortDirection sortDirection = SortDirection.UNSORTED;

            switch (sortConstraint.getColumnSort()) {
            case ASCENDING:
                sortDirection = SortDirection.ASCENDING;
            case DESCENDING:
                sortDirection = SortDirection.DESCENDING;

            SortCriterion sortCriterion = new SortCriterion(propertyName, sortDirection);

        return sortCriteria;


Now that we have a GridDataSource we can see what it needs – a CourseFinderService. While there is a Tapestry-Spring integration we want to keep the maintenance webapp as thin as possible so for now we use standard Tapestry injection.

package com.invariantproperties.sandbox.student.maintenance.web.services;

import com.invariantproperties.sandbox.student.business.CourseFinderService;
import com.invariantproperties.sandbox.student.business.CourseManagerService;
import com.invariantproperties.sandbox.student.maintenance.service.impl.CourseFinderServiceTapestryImpl;
import com.invariantproperties.sandbox.student.maintenance.service.impl.CourseManagerServiceTapestryImpl;

 * This module is automatically included as part of the Tapestry IoC Registry,
 * it's a good place to configure and extend Tapestry, or to place your own
 * service definitions.
public class AppModule {
    public static void bind(ServiceBinder binder) {
        binder.bind(CourseFinderService.class, CourseFinderServiceTapestryImpl.class);
        binder.bind(CourseManagerService.class, CourseManagerServiceTapestryImpl.class);


Note that we’re using the standard CourseFinderService interface with the tapestry-specific implementation. This means we can use the standard implementation directly with nothing more than a small change to the configuration files!


The local implementation of the CourseFinderService interface must use the REST client instead of the Spring Data implementation. Using the outside-in approach used earlier the needs of the Tapestry template should drive the needs of the Service implementation and that, in turn, drives the needs of the REST client and server.

package com.invariantproperties.sandbox.student.maintenance.service.impl;

public class CourseFinderServiceTapestryImpl implements CourseFinderService {
    private final CourseFinderRestClient finder;

    public CourseFinderServiceTapestryImpl() {
        // resource should be loaded as tapestry resource
        final String resource = "http://localhost:8080/student-ws-webapp/rest/course/";
        finder = new CourseFinderRestClientImpl(resource);

        // load some initial data
        initCache(new CourseManagerRestClientImpl(resource));

    public long count() {
        // FIXME: grossly inefficient but good enough for now.
        return finder.getAllCourses().length;

    public long countByTestRun(TestRun testRun) {
        // FIXME: grossly inefficient but good enough for now.
        return finder.getAllCourses().length;

    public Course findCourseById(Integer id) {
        // unsupported operation!
        throw new ObjectNotFoundException(id);

    public Course findCourseByUuid(String uuid) {
        return finder.getCourse(uuid);

    public List<Course> findAllCourses() {
        return Arrays.asList(finder.getAllCourses());

    public List<Course> findCoursesByTestRun(TestRun testRun) {
        return Collections.emptyList();

    // method to load some test data into the database.
    private void initCache(CourseManagerRestClient manager) {
        manager.createCourse("physics 101");
        manager.createCourse("physics 201");
        manager.createCourse("physics 202");

Our JPA Criteria query can give us a quick count but our REST client doesn’t support that yet.

Wrapping up

After we finish the grunt work we’ll have a maintenance .war file. We can deploy it with the webservice .war on our appserver – or not. There’s no reason the two .war files have to be on the same system other than the temporarily hardcoded URL for the webservice.

We should first go to http://localhost:8080/student-maintenance-webapp/course/list. We should see a short list of courses as shown above. (In that case I had restarted the webapp three times so each entry is duplicated three-fold.)

Now we should go to our webservice webapp at http://localhost:8080/student-ws-webapp/rest/course and verify that we can get data via the browser there as well. After a bit of cleanup we should see:

     "name":"physics 101"
     "name":"physics 201"
     "name":"physics 202"
     "name":"physics 101"

Source Code


(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of