import net.pterodactylus.demoscenemusic.data.TrackDerivative;
import net.pterodactylus.demoscenemusic.data.User;
import net.pterodactylus.demoscenemusic.page.ServletRequest;
+import net.pterodactylus.demoscenemusic.template.ConciseNumberFilter;
import net.pterodactylus.demoscenemusic.template.DurationFilter;
import net.pterodactylus.demoscenemusic.template.PropertiesAccessor;
import net.pterodactylus.demoscenemusic.template.TrackDerivativeAccessor;
templateContextFactory.addFilter("sort", sortFilter);
templateContextFactory.addFilter("matches", new MatchFilter());
templateContextFactory.addFilter("time", new DurationFilter());
+ templateContextFactory.addFilter("concise", new ConciseNumberFilter());
templateContextFactory.addTemplateObject("core", core);
templateContextFactory.addTemplateObject("dataManager", core.getDataManager());
--- /dev/null
+/*
+ * DemosceneMusic - ConciseNumberFilter.java - Copyright © 2012 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 <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.demoscenemusic.template;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import net.pterodactylus.util.number.Numbers;
+import net.pterodactylus.util.template.Filter;
+import net.pterodactylus.util.template.TemplateContext;
+
+/**
+ * {@link Filter} implementation that only shows the three most significant
+ * digits of a number, adding prefix for kilo (kibi, actually), mega (mebi), et
+ * cetera, as necessary.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public class ConciseNumberFilter implements Filter {
+
+ private static final List<String> prefixes = Arrays.asList("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei");
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Object format(TemplateContext templateContext, Object data, Map<String, Object> parameters) {
+ double number = Numbers.safeParseLong(data, 0L);
+ int prefix = 0;
+ while (number > 1023) {
+ prefix++;
+ number /= 1024.0;
+ }
+ if (number >= 1000) {
+ return String.format("%1.2f %s", number / 1024.0, prefixes.get(prefix + 1));
+ }
+ if (number >= 100) {
+ return String.format("%1.0f %s", number, prefixes.get(prefix));
+ }
+ if (number >= 10) {
+ return String.format("%1.1f %s", number, prefixes.get(prefix));
+ }
+ return String.format("%1.2f %s", number, prefixes.get(prefix));
+ }
+
+}