001package org.nuxeo.template.adapters.doc; 002 003import java.io.Serializable; 004import java.util.ArrayList; 005import java.util.Iterator; 006import java.util.List; 007import java.util.Map; 008 009import org.nuxeo.ecm.core.api.DocumentModel; 010 011public class TemplateBindings extends ArrayList<TemplateBinding> { 012 013 private static final long serialVersionUID = 1L; 014 015 public static final String DEFAULT_BINDING = "default"; 016 017 public static final String BINDING_PROP_NAME = "nxts:bindings"; 018 019 public TemplateBindings(DocumentModel doc) { 020 Serializable value = doc.getPropertyValue(BINDING_PROP_NAME); 021 if (value != null) { 022 @SuppressWarnings("unchecked") 023 List<Map<String, Serializable>> bindings = (List<Map<String, Serializable>>) value; 024 for (Map<String, Serializable> binding : bindings) { 025 add(new TemplateBinding(binding)); 026 } 027 } 028 } 029 030 public String useMainContentAsTemplate() { 031 for (TemplateBinding tb : this) { 032 if (tb.isUseMainContentAsTemplate()) { 033 return tb.getName(); 034 } 035 } 036 return null; 037 } 038 039 public TemplateBinding get() { 040 return get(DEFAULT_BINDING); 041 } 042 043 public void removeByName(String templateName) { 044 Iterator<TemplateBinding> it = this.iterator(); 045 while (it.hasNext()) { 046 TemplateBinding binding = it.next(); 047 if (binding.getName().equals(templateName)) { 048 it.remove(); 049 return; 050 } 051 } 052 } 053 054 public boolean containsTemplateName(String templateName) { 055 for (TemplateBinding tb : this) { 056 if (templateName.equals(tb.getName())) { 057 return true; 058 } 059 } 060 return false; 061 } 062 063 public boolean containsTemplateId(String templateId) { 064 for (TemplateBinding tb : this) { 065 if (templateId.equals(tb.getTemplateId())) { 066 return true; 067 } 068 } 069 return false; 070 } 071 072 public TemplateBinding get(String name) { 073 for (TemplateBinding tb : this) { 074 if (name.equals(tb.getName())) { 075 return tb; 076 } 077 } 078 return null; 079 } 080 081 public void addOrUpdate(TemplateBinding tb) { 082 TemplateBinding existing = get(tb.getName()); 083 if (existing == null) { 084 add(tb); 085 } else { 086 existing.update(tb); 087 } 088 } 089 090 public List<String> getNames() { 091 092 List<String> names = new ArrayList<String>(); 093 for (TemplateBinding tb : this) { 094 names.add(tb.getName()); 095 } 096 return names; 097 } 098 099 public void save(DocumentModel doc) { 100 List<Map<String, Serializable>> bindings = new ArrayList<Map<String, Serializable>>(); 101 for (TemplateBinding tb : this) { 102 bindings.add(tb.getAsMap()); 103 } 104 doc.setPropertyValue(BINDING_PROP_NAME, (Serializable) bindings); 105 } 106}