1 package net.pterodactylus.sone.template;
5 import javax.annotation.Nullable;
7 import net.pterodactylus.sone.data.IdBuilder;
8 import net.pterodactylus.sone.data.Sone;
9 import net.pterodactylus.util.template.Filter;
10 import net.pterodactylus.util.template.TemplateContext;
12 import com.google.common.base.Function;
13 import com.google.common.base.Optional;
16 * Filter that {@link IdBuilder builds IDs} from a piped-in element ID and a Sone or Sone ID given as parameter “sone.”
18 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
20 public class BuildIdFilter implements Filter {
22 private final IdBuilder idBuilder = new IdBuilder();
25 public Object format(TemplateContext templateContext, Object data, Map<String, Object> parameters) {
26 Optional<String> soneId = getSoneId(parameters);
27 if (!soneId.isPresent()) {
30 Optional<String> elementId = Optional.fromNullable(data).transform(getStringValue());
31 if (!elementId.isPresent()) {
34 return idBuilder.buildId(soneId.get(), elementId.get());
37 private Optional<String> getSoneId(Map<String, Object> parameters) {
38 Object soneObject = parameters.get("sone");
39 if (soneObject instanceof String) {
40 return Optional.of((String) soneObject);
41 } else if (soneObject instanceof Sone) {
42 return Optional.of(((Sone) soneObject).getId());
44 return Optional.absent();
47 private Function<? super Object, String> getStringValue() {
48 return new Function<Object, String>() {
51 public String apply(Object input) {
52 return (input != null) ? input.toString() : null;