001/* 002 * This file is part of the Kompics component model runtime. 003 * 004 * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) 005 * Copyright (C) 2009 Royal Institute of Technology (KTH) 006 * 007 * This program is free software; you can redistribute it and/or 008 * modify it under the terms of the GNU General Public License 009 * as published by the Free Software Foundation; either version 2 010 * of the License, or (at your option) any later version. 011 * 012 * This program is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 015 * GNU General Public License for more details. 016 * 017 * You should have received a copy of the GNU General Public License 018 * along with this program; if not, write to the Free Software 019 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 020 */ 021package se.sics.kompics.config; 022 023import java.util.Optional; 024import java.util.ArrayList; 025import java.util.Collection; 026 027/** 028 * 029 * @author Lars Kroll {@literal <[email protected]>} 030 */ 031public interface ValueMerger { 032 public ConfigValue merge(String key, ConfigValue oldValue, ConfigValue newValue, ConfigValueFactory cvFactory); 033 034 public static final ValueMerger NEWEST = new ValueMerger() { 035 036 @Override 037 public ConfigValue merge(String key, ConfigValue oldValue, ConfigValue newValue, ConfigValueFactory cvFactory) { 038 return newValue; 039 } 040 }; 041 public static final ValueMerger HIGHEST_ID = new ValueMerger() { 042 043 @Override 044 public ConfigValue merge(String key, ConfigValue oldValue, ConfigValue newValue, ConfigValueFactory cvFactory) { 045 if (oldValue.version() < newValue.version()) { 046 return newValue; 047 } else { 048 return oldValue; 049 } 050 } 051 }; 052 public static final ValueMerger APPEND = new ValueMerger() { 053 054 @SuppressWarnings("unchecked") 055 @Override 056 public ConfigValue merge(String key, ConfigValue oldValue, ConfigValue newValue, ConfigValueFactory cvFactory) { 057 Object o = oldValue.unwrap(); 058 if (o instanceof Collection) { 059 Collection<Object> c = (Collection<Object>) o; 060 c.add(newValue.unwrap()); 061 return cvFactory.create(c, Math.max(oldValue.version(), newValue.version()), newValue.options()); 062 } else { 063 ArrayList<Object> l = new ArrayList<Object>(); 064 l.add(oldValue.unwrap()); 065 l.add(newValue.unwrap()); 066 return cvFactory.create(l, Math.max(oldValue.version(), newValue.version()), newValue.options()); 067 } 068 } 069 }; 070 public static final Optional<ValueMerger> NONE = Optional.empty(); 071}