Something I do on the NixMash Home Page is a Vermont Banner of the Day. Photos are licensed with a Creative Commons License, so you'll always see an attribution at the bottom of the page. The Banner changes every day, and in this post we're going to look at the logic of making that happen. And yes, it's more interesting that it sounds if you're a Java Coder.
A NixMash Home Page with banner at the top and attribution at the bottom.
I started the feature with 10 or so banners and added images over time, so the original logic was to use the image ID based on the day of the month. It was slightly more involved because banners could be deactivated, so the dayOfMonth retrieved from the Active SiteImage Array index. As a side point, notice the long but effective Spring JPA Named Method .findByBannerImageTrueAndIsActiveTrue().
This logic was fine as long as the number of images was less than the number of days in the month, but not so much when the number of images was larger. Time to bring in a random selection logic, but as simple a solution as possible. Remember, one banner per day, no more, no less.
The trick was to modify the SiteImage table to support an isCurrent Boolean and a fixed value for each record that changed by day, a dayOfYear Integer.
Banner of the Day Logic Overview
As an overview, the logic for displaying one-and-only-one Banner of the Day is the following:
- Retrieve the SiteImage for the current dayOfYear with isCurrent flag set to true.
- If SiteImage is null (let's say it's 12:01 AM when the page is loaded), the table is reset with all isCurrent false and dayOfYear updated.
- A random image from all active banner images is set to isCurrent and retrieved.
- All subsequent banner retrievals for that day are that SiteImage now set as isCurrent with the current dayOfYear value.
Let's see what that looks like in an Integrated @Test method. We're going to go through a year's worth of banner displays in our 1-to-365 day iteration loop. We reset the table and confirm we don't have a currentSiteImage. Next we select a random image from our Active Banners and set it as our isCurrent SiteImage. Our final step is to retrieve a SiteImage object based on our isCurrent is true and current dayOfYear value.
The Service Method
Go Live Time, with the final Service Layer Method looking like this.
One of the things you strive for as a developer is perform tasks simply, and with Banner of the Day you see that in action.
Source Code Notes for this Post
Source code discussed in this post can be found in my NixMash Blog project located on GitHub.