001package io.jstach.jstachio.formatters; 002 003import java.net.URI; 004import java.net.URL; 005 006import org.eclipse.jdt.annotation.Nullable; 007 008import io.jstach.jstache.JStacheFormatter; 009import io.jstach.jstache.JStacheFormatterTypes; 010import io.jstach.jstachio.Appender; 011import io.jstach.jstachio.Formatter; 012import io.jstach.jstachio.Output; 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 Output<E>, E extends Exception> void format(Appender downstream, A a, String path, Class<?> c, 031 @Nullable Object o) throws E { 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 Output<E>, E extends Exception> void format(Appender downstream, A a, String path, String s) 048 throws E { 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 * Provides the default formatter for static lookup. 065 * @return the default formatter singleton 066 */ 067 public static Formatter of() { 068 return DefaultFormatterSingleton.DefaultFormatter; 069 } 070 071} 072 073enum DefaultFormatterSingleton implements DefaultFormatter { 074 075 DefaultFormatter; 076 077}