Enterprise Java

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).

Limitations

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.

Goal

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:

project-maintenance

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"
      xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd"
      xmlns:p="tapestry:parameter">
        <!-- Most of the page content, including <head>, <body>, etc. tags, comes from Layout.tml -->

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

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

    <p:sidebar>
        <p>
            [
            <t:pagelink page="Index">Index</t:pagelink>
            ]<br/>
            [
            <t:pagelink page="Course/List">Courses</t:pagelink>
            ]
        </p>
    </p:sidebar>
</html>

with a properties file of

title=Courses
delete-course=Delete course?

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

GridDataSources

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

    @Property
    private GridDataSource courses;

    // Generally useful bits and pieces

    @Inject
    private CourseFinderService courseFinderService;

    @InjectComponent
    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;
    }

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

    @Override
    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;
    }

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

    @Override
    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;
                break;
            case DESCENDING:
                sortDirection = SortDirection.DESCENDING;
                break;
            default:
            }

            SortCriterion sortCriterion = new SortCriterion(propertyName, sortDirection);
            sortCriteria.add(sortCriterion);
        }

        return sortCriteria;
    }
}

AppModule

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!

CourseFinderServiceTapestryImpl

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));
    }

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

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

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

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

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

    @Override
    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:

{"course":
 [
   {
     "creationDate":"2013-12-28T14:40:21.369-07:00",
     "uuid":"500069e4-444d-49bc-80f0-4894c2d13f6a",
     "version":"0",
     "name":"physics 101"
   },
   {
     "creationDate":"2013-12-28T14:40:21.777-07:00",
     "uuid":"54001b2a-abbb-4a75-a289-e1f09173fa04",
     "version":"0",
     "name":"physics 201"
   },
   {
     "creationDate":"2013-12-28T14:40:21.938-07:00",
     "uuid":"cfaf892b-7ead-4d64-8659-8f87756bed62",
     "version":"0",
     "name":"physics 202"
   },
   {
     "creationDate":"2013-12-28T16:17:54.608-07:00",
     "uuid":"d29735ff-f614-4979-a0de-e1d134e859f4",
     "version":"0",
     "name":"physics 101"
   },
   ....
 ]
}

Source Code

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button