X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;f=src%2Fmain%2Fjava%2Fnet%2Fpterodactylus%2Fsone%2Ftemplate%2FSubstringFilter.java;fp=src%2Fmain%2Fjava%2Fnet%2Fpterodactylus%2Fsone%2Ftemplate%2FSubstringFilter.java;h=f0075e4576ca3fda9c2a0c80d8e8c791b70054c9;hb=5a704af88b91a83ad78b5fb6dc3147a9b65d713d;hp=0000000000000000000000000000000000000000;hpb=1577df324fd0dbc47401a8ee5996ab26ad2b2a43;p=Sone.git
diff --git a/src/main/java/net/pterodactylus/sone/template/SubstringFilter.java b/src/main/java/net/pterodactylus/sone/template/SubstringFilter.java
new file mode 100644
index 0000000..f0075e4
--- /dev/null
+++ b/src/main/java/net/pterodactylus/sone/template/SubstringFilter.java
@@ -0,0 +1,69 @@
+/*
+ * Sone - SubstringFilter.java - Copyright © 2010 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+package net.pterodactylus.sone.template;
+
+import java.util.Map;
+
+import net.pterodactylus.util.template.DataProvider;
+import net.pterodactylus.util.template.Filter;
+
+/**
+ * {@link Filter} implementation that executes
+ * {@link String#substring(int, int)} on the given data. It has two parameters:
+ * âstartâ and âlength.â âlengthâ is optional and defaults to âthe rest of the
+ * string.â âstartâ starts at {@code 0} and can be negative to denote starting
+ * at the end of the string.
+ *
+ * @author David âBombeâ Roden
+ */
+public class SubstringFilter implements Filter {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Object format(DataProvider dataProvider, Object data, Map parameters) {
+ String startString = parameters.get("start");
+ String lengthString = parameters.get("length");
+ int start = 0;
+ try {
+ start = Integer.parseInt(startString);
+ } catch (NumberFormatException nfe1) {
+ /* ignore. */
+ }
+ String dataString = String.valueOf(data);
+ int dataLength = dataString.length();
+ if (lengthString == null) {
+ if (start < 0) {
+ return dataString.substring(dataLength + start);
+ }
+ return dataString.substring(start);
+ }
+ int length = Integer.MAX_VALUE;
+ try {
+ length = Integer.parseInt(lengthString);
+ } catch (NumberFormatException nfe1) {
+ /* ignore. */
+ }
+ if (start < 0) {
+ return dataString.substring(dataLength + start, Math.min(dataLength, dataLength + start + length));
+ }
+ return dataString.substring(start, Math.min(dataLength, start + length));
+ }
+
+}