|
| 1 | +/** |
| 2 | + * Jooby https://jooby.io |
| 3 | + * Apache License Version 2.0 https://jooby.io/LICENSE.txt |
| 4 | + * Copyright 2014 Edgar Espina |
| 5 | + */ |
| 6 | +package io.jooby.internal; |
| 7 | + |
| 8 | +import io.jooby.Context; |
| 9 | +import io.jooby.MessageEncoder; |
| 10 | +import io.jooby.ModelAndView; |
| 11 | +import io.jooby.TemplateEngine; |
| 12 | + |
| 13 | +import javax.annotation.Nonnull; |
| 14 | +import java.util.Iterator; |
| 15 | +import java.util.LinkedList; |
| 16 | + |
| 17 | +public class CompositeMessageEncoder implements MessageEncoder { |
| 18 | + |
| 19 | + private LinkedList<MessageEncoder> list = new LinkedList<>(); |
| 20 | + |
| 21 | + private MessageEncoder templateEngine; |
| 22 | + |
| 23 | + public CompositeMessageEncoder() { |
| 24 | + list.add(MessageEncoder.TO_STRING); |
| 25 | + } |
| 26 | + |
| 27 | + public CompositeMessageEncoder add(MessageEncoder encoder) { |
| 28 | + if (encoder instanceof TemplateEngine) { |
| 29 | + templateEngine = computeRenderer(templateEngine, encoder); |
| 30 | + } else { |
| 31 | + list.addFirst(encoder); |
| 32 | + } |
| 33 | + return this; |
| 34 | + } |
| 35 | + |
| 36 | + private MessageEncoder computeRenderer(MessageEncoder it, MessageEncoder next) { |
| 37 | + if (it == null) { |
| 38 | + return next; |
| 39 | + } else if (it instanceof CompositeMessageEncoder) { |
| 40 | + ((CompositeMessageEncoder) it).list.addFirst(next); |
| 41 | + return it; |
| 42 | + } else { |
| 43 | + CompositeMessageEncoder composite = new CompositeMessageEncoder(); |
| 44 | + composite.list.addFirst(it); |
| 45 | + composite.list.addFirst(next); |
| 46 | + return composite; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + @Override public byte[] encode(@Nonnull Context ctx, @Nonnull Object value) throws Exception { |
| 51 | + if (value instanceof ModelAndView) { |
| 52 | + return templateEngine.encode(ctx, value); |
| 53 | + } else { |
| 54 | + Iterator<MessageEncoder> iterator = list.iterator(); |
| 55 | + /** NOTE: looks like an infinite loop but there is a default renderer at the end of iterator. */ |
| 56 | + byte[] result = null; |
| 57 | + while (result == null) { |
| 58 | + MessageEncoder next = iterator.next(); |
| 59 | + result = next.encode(ctx, value); |
| 60 | + } |
| 61 | + return result; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments