2 * Sone - SubstringFilter.java - Copyright © 2010 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.template;
22 import net.pterodactylus.util.template.DataProvider;
23 import net.pterodactylus.util.template.Filter;
26 * {@link Filter} implementation that executes
27 * {@link String#substring(int, int)} on the given data. It has two parameters:
28 * “start” and “length.” “length” is optional and defaults to “the rest of the
29 * string.” “start” starts at {@code 0} and can be negative to denote starting
30 * at the end of the string.
32 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
34 public class SubstringFilter implements Filter {
40 public Object format(DataProvider dataProvider, Object data, Map<String, String> parameters) {
41 String startString = parameters.get("start");
42 String lengthString = parameters.get("length");
45 start = Integer.parseInt(startString);
46 } catch (NumberFormatException nfe1) {
49 String dataString = String.valueOf(data);
50 int dataLength = dataString.length();
51 if (lengthString == null) {
53 return dataString.substring(dataLength + start);
55 return dataString.substring(start);
57 int length = Integer.MAX_VALUE;
59 length = Integer.parseInt(lengthString);
60 } catch (NumberFormatException nfe1) {
64 return dataString.substring(dataLength + start, Math.min(dataLength, dataLength + start + length));
66 return dataString.substring(start, Math.min(dataLength, start + length));