001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools.template_engine; 003 004import java.util.Arrays; 005 006/** 007 * {@link TemplateEntry} that concatenates several templates. 008 */ 009public final class CompoundTemplateEntry implements TemplateEntry { 010 011 /** 012 * Factory method to concatenate several {@code TemplateEntry}s. 013 * 014 * If the number of entries is 0 or 1, the result may not be a {@code CompoundTemplateEntry}, 015 * but optimized to a static text or the single entry itself. 016 * @param entries the {@code TemplateEntry}s to concatenate 017 * @return a {@link TemplateEntry} that concatenates all the entries 018 */ 019 public static TemplateEntry fromArray(TemplateEntry... entries) { 020 if (entries.length == 0) 021 return new StaticText(""); 022 else if (entries.length == 1) 023 return entries[0]; 024 else 025 return new CompoundTemplateEntry(entries); 026 } 027 028 private CompoundTemplateEntry(TemplateEntry... entries) { 029 this.entries = entries; 030 } 031 032 private final TemplateEntry[] entries; 033 034 @Override 035 public void appendText(StringBuilder result, TemplateEngineDataProvider dataProvider) { 036 for (TemplateEntry te: entries) { 037 te.appendText(result, dataProvider); 038 } 039 } 040 041 @Override 042 public boolean isValid(TemplateEngineDataProvider dataProvider) { 043 for (TemplateEntry te: entries) { 044 if (!te.isValid(dataProvider)) 045 return false; 046 } 047 return true; 048 } 049 050 @Override 051 public String toString() { 052 StringBuilder result = new StringBuilder(); 053 for (TemplateEntry te: entries) { 054 result.append(te); 055 } 056 return result.toString(); 057 } 058 059 @Override 060 public int hashCode() { 061 return 31 + Arrays.hashCode(entries); 062 } 063 064 @Override 065 public boolean equals(Object obj) { 066 if (this == obj) 067 return true; 068 if (obj == null || getClass() != obj.getClass()) 069 return false; 070 CompoundTemplateEntry other = (CompoundTemplateEntry) obj; 071 return Arrays.equals(entries, other.entries); 072 } 073}