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 return entries.stream().anyMatch(entry -> entry.isValid(dataProvider)); 049 } 050 051 @Override 052 public String toString() { 053 StringBuilder sb = new StringBuilder(); 054 sb.append("?{ "); 055 for (TemplateEntry entry: entries) { 056 if (entry instanceof SearchExpressionCondition) { 057 sb.append(entry); 058 } else { 059 sb.append('\'').append(entry).append('\''); 060 } 061 sb.append(" | "); 062 } 063 sb.setLength(sb.length() - 3); 064 sb.append(" }"); 065 return sb.toString(); 066 } 067 068 @Override 069 public int hashCode() { 070 return 31 + ((entries == null) ? 0 : entries.hashCode()); 071 } 072 073 @Override 074 public boolean equals(Object obj) { 075 if (this == obj) 076 return true; 077 if (obj == null || getClass() != obj.getClass()) 078 return false; 079 Condition other = (Condition) obj; 080 if (entries == null) { 081 if (other.entries != null) 082 return false; 083 } else if (!entries.equals(other.entries)) 084 return false; 085 return true; 086 } 087}