f14d0ffa8da791f0363c703c7b68bd9e1b29e3e5
[Sone.git] / src / main / java / net / pterodactylus / sone / template / SubstringFilter.java
1 /*
2  * Sone - SubstringFilter.java - Copyright © 2010–2016 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.template;
19
20 import java.util.Map;
21
22 import net.pterodactylus.util.template.Filter;
23 import net.pterodactylus.util.template.TemplateContext;
24
25 /**
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.
31  *
32  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
33  */
34 public class SubstringFilter implements Filter {
35
36         /**
37          * {@inheritDoc}
38          */
39         @Override
40         public Object format(TemplateContext templateContext, Object data, Map<String, Object> parameters) {
41                 String startString = String.valueOf(parameters.get("start"));
42                 String lengthString = String.valueOf(parameters.get("length"));
43                 int start = 0;
44                 try {
45                         start = Integer.parseInt(startString);
46                 } catch (NumberFormatException nfe1) {
47                         /* ignore. */
48                 }
49                 String dataString = String.valueOf(data);
50                 int dataLength = dataString.length();
51                 int length = dataLength;
52                 try {
53                         length = Integer.parseInt(lengthString);
54                 } catch (NumberFormatException nfe1) {
55                         /* ignore. */
56                 }
57                 if (start < 0) {
58                         return dataString.substring(dataLength + start, Math.min(dataLength, dataLength + start + length));
59                 }
60                 return dataString.substring(start, Math.min(dataLength, start + length));
61         }
62
63 }