001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools.template_engine; 003 004import java.util.ArrayList; 005import java.util.Collection; 006import java.util.List; 007 008/** 009 * {@link TemplateEntry} that applies other templates based on conditions. 010 * <p> 011 * It goes through a number of template entries and executes the first one that is valid. 012 */ 013public class Condition implements TemplateEntry { 014 015 private final List<TemplateEntry> entries; 016 017 /** 018 * Constructs a new {@code Condition} with predefined template entries. 019 * @param entries template entries 020 */ 021 public Condition(Collection<TemplateEntry> entries) { 022 this.entries = new ArrayList<>(entries); 023 } 024 025 /** 026 * Constructs a new {@code Condition}. 027 */ 028 public Condition() { 029 this.entries = new ArrayList<>(); 030 } 031 032 @Override 033 public void appendText(StringBuilder result, TemplateEngineDataProvider dataProvider) { 034 for (TemplateEntry entry: entries) { 035 if (entry.isValid(dataProvider)) { 036 entry.appendText(result, dataProvider); 037 return; 038 } 039 } 040 041 // Fallback to last entry 042 TemplateEntry entry = entries.get(entries.size() - 1); 043 entry.appendText(result, dataProvider); 044 } 045 046 @Override 047 public boolean isValid(TemplateEngineDataProvider dataProvider) { 048 049 for (TemplateEntry entry: entries) { 050 if (entry.isValid(dataProvider)) 051 return true; 052 } 053 054 return false; 055 } 056 057 @Override 058 public String toString() { 059 StringBuilder sb = new StringBuilder(); 060 sb.append("?{ "); 061 for (TemplateEntry entry: entries) { 062 if (entry instanceof SearchExpressionCondition) { 063 sb.append(entry); 064 } else { 065 sb.append('\'').append(entry).append('\''); 066 } 067 sb.append(" | "); 068 } 069 sb.setLength(sb.length() - 3); 070 sb.append(" }"); 071 return sb.toString(); 072 } 073}