2 * Sone - CollectionAccessor.java - Copyright © 2010–2020 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;
20 import static net.pterodactylus.sone.data.SoneKt.*;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
26 import net.pterodactylus.sone.data.*;
27 import net.pterodactylus.util.template.Accessor;
28 import net.pterodactylus.util.template.ReflectionAccessor;
29 import net.pterodactylus.util.template.TemplateContext;
32 * {@link Accessor} for {@link Collection}s that adds a couple of specialized
33 * properties that only work for collections that contain the right types.
36 * <dt>Returns the nice names of all {@link Sone}s in the collection, sorted
37 * ascending by their nice names.</dt>
40 public class CollectionAccessor extends ReflectionAccessor {
46 public Object get(TemplateContext templateContext, Object object, String member) {
47 Collection<?> collection = (Collection<?>) object;
48 if (member.equals("soneNames")) {
49 List<Sone> sones = new ArrayList<>();
50 for (Object sone : collection) {
51 if (!(sone instanceof Sone)) {
54 sones.add((Sone) sone);
56 sones.sort(niceNameComparator());
57 StringBuilder soneNames = new StringBuilder();
58 for (Sone sone : sones) {
59 if (soneNames.length() > 0) {
60 soneNames.append(", ");
62 soneNames.append(SoneAccessor.getNiceName(sone));
64 return soneNames.toString();
66 return super.get(templateContext, object, member);