001/** 002 * jshred - Shred's Toolbox 003 * 004 * Copyright (C) 2009 Richard "Shred" Körber 005 * http://jshred.shredzone.org 006 * 007 * This program is free software: you can redistribute it and/or modify 008 * it under the terms of the GNU General Public License / GNU Lesser 009 * General Public License as published by the Free Software Foundation, 010 * either version 3 of the License, or (at your option) any later version. 011 * 012 * Licensed under the Apache License, Version 2.0 (the "License"); 013 * you may not use this file except in compliance with the License. 014 * 015 * This program is distributed in the hope that it will be useful, 016 * but WITHOUT ANY WARRANTY; without even the implied warranty of 017 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 018 * 019 */ 020package org.shredzone.jshred.web; 021 022/** 023 * A helper class that returns an endless sequence of the given item set. This is useful 024 * in JSPs, e.g. for rendering each row of a table in a different color. 025 * <p> 026 * Example: 027 * 028 * <pre> 029 * <% pageContext.setAttribute("sequence", new Sequencer("oddrow", "evenrow")); %> 030 * <c:forEach var="entry" items="${entryList}"> 031 * <tr class="${sequence.next}"> 032 * <td><c:out value="${entry.name}"/></td> 033 * </tr> 034 * </c:forEach> 035 * </pre> 036 * 037 * @author Richard "Shred" Körber 038 */ 039public class Sequencer { 040 private int pos = 0; 041 private final String[] sequence; 042 043 /** 044 * Creates a new Sequencer with the given sequence. 045 * 046 * @param sequence 047 * The sequence of strings to be used. Must have at least one entry. 048 */ 049 public Sequencer(String... sequence) { 050 if (sequence.length == 0) 051 throw new IllegalArgumentException("At least one item is required!"); 052 053 this.sequence = sequence; 054 this.pos = 0; 055 } 056 057 /** 058 * Gets the next entry of the sequence. If the last entry was returned, it will start 059 * again with the first entry. 060 * 061 * @return Sequence entry 062 */ 063 public String getNext() { 064 if (pos >= sequence.length) pos = 0; 065 return sequence[pos++]; 066 } 067 068}