Use unique IDs for images
[Sone.git] / src / main / java / net / pterodactylus / sone / template / BuildIdFilter.java
1 package net.pterodactylus.sone.template;
2
3 import java.util.Map;
4
5 import javax.annotation.Nullable;
6
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;
11
12 import com.google.common.base.Function;
13 import com.google.common.base.Optional;
14
15 /**
16  * Filter that {@link IdBuilder builds IDs} from a piped-in element ID and a Sone or Sone ID given as parameter “sone.”
17  *
18  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
19  */
20 public class BuildIdFilter implements Filter {
21
22         private final IdBuilder idBuilder = new IdBuilder();
23
24         @Override
25         public Object format(TemplateContext templateContext, Object data, Map<String, Object> parameters) {
26                 Optional<String> soneId = getSoneId(parameters);
27                 if (!soneId.isPresent()) {
28                         return null;
29                 }
30                 Optional<String> elementId = Optional.fromNullable(data).transform(getStringValue());
31                 if (!elementId.isPresent()) {
32                         return null;
33                 }
34                 return idBuilder.buildId(soneId.get(), elementId.get());
35         }
36
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());
43                 }
44                 return Optional.absent();
45         }
46
47         private Function<? super Object, String> getStringValue() {
48                 return new Function<Object, String>() {
49                         @Nullable
50                         @Override
51                         public String apply(Object input) {
52                                 return (input != null) ? input.toString() : null;
53                         }
54                 };
55         }
56
57 }