001package io.jstach.jstachio.formatters;
002
003import java.io.IOException;
004import java.net.URI;
005import java.net.URL;
006
007import org.eclipse.jdt.annotation.Nullable;
008
009import io.jstach.jstache.JStacheFormatter;
010import io.jstach.jstache.JStacheFormatterTypes;
011import io.jstach.jstachio.Appender;
012import io.jstach.jstachio.Formatter;
013import io.jstach.jstachio.context.ContextNode;
014
015/**
016 * Default formatters.
017 *
018 * Unlike the mustache spec it will throw a NPE trying to format null objects.
019 *
020 * @author agentgt
021 */
022@JStacheFormatter
023@JStacheFormatterTypes(types = { URI.class, URL.class })
024public interface DefaultFormatter extends Formatter {
025
026        /**
027         * {@inheritDoc} Will throw an NPE if parameter o is <code>null</code>.
028         */
029        @Override
030        default <A extends Appendable, APPENDER extends Appender<A>> void format(APPENDER downstream, A a, String path,
031                        Class<?> c, @Nullable Object o) throws IOException {
032                if (o == null) {
033                        throw new NullPointerException("null at: " + path);
034                }
035                else if (o instanceof ContextNode m) {
036                        downstream.append(a, m.renderString());
037                }
038                else {
039                        downstream.append(a, String.valueOf(o));
040                }
041        }
042
043        /**
044         * {@inheritDoc} Will throw an NPE if parameter s is <code>null</code>.
045         */
046        @Override
047        default <A extends Appendable, APPENDER extends Appender<A>> void format(APPENDER downstream, A a, String path,
048                        String s) throws IOException {
049                if (s == null) {
050                        throw new NullPointerException("null at: " + path);
051                }
052                downstream.append(a, s);
053        }
054
055        /**
056         * Provides the default formatter for static lookup.
057         * @return the default formatter singleton
058         */
059        public static Formatter provider() {
060                return DefaultFormatterSingleton.DefaultFormatter;
061        }
062
063}
064
065enum DefaultFormatterSingleton implements DefaultFormatter {
066
067        DefaultFormatter;
068
069}