66c2c3849ee9f46128fee7a96ca73d2a69f7093d
[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 public class SubstringFilter implements Filter {
33
34         /**
35          * {@inheritDoc}
36          */
37         @Override
38         public Object format(TemplateContext templateContext, Object data, Map<String, Object> parameters) {
39                 String startString = String.valueOf(parameters.get("start"));
40                 String lengthString = String.valueOf(parameters.get("length"));
41                 int start = 0;
42                 try {
43                         start = Integer.parseInt(startString);
44                 } catch (NumberFormatException nfe1) {
45                         /* ignore. */
46                 }
47                 String dataString = String.valueOf(data);
48                 int dataLength = dataString.length();
49                 int length = dataLength;
50                 try {
51                         length = Integer.parseInt(lengthString);
52                 } catch (NumberFormatException nfe1) {
53                         /* ignore. */
54                 }
55                 if (start < 0) {
56                         return dataString.substring(dataLength + start, Math.min(dataLength, dataLength + start + length));
57                 }
58                 return dataString.substring(start, Math.min(dataLength, start + length));
59         }
60
61 }