001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.upgrade.util;
016    
017    import com.liferay.portal.kernel.upgrade.StagnantRowException;
018    import com.liferay.portal.kernel.upgrade.util.ValueMapper;
019    
020    import java.util.Iterator;
021    import java.util.LinkedHashMap;
022    import java.util.LinkedHashSet;
023    import java.util.Map;
024    import java.util.Set;
025    
026    /**
027     * @author Alexander Chow
028     * @author Brian Wing Shun Chan
029     */
030    public class MemoryValueMapper implements ValueMapper {
031    
032            public MemoryValueMapper() {
033                    this(new LinkedHashSet<Object>());
034            }
035    
036            public MemoryValueMapper(Set<Object> exceptions) {
037                    _map = new LinkedHashMap<Object, Object>();
038                    _exceptions = exceptions;
039            }
040    
041            public void appendException(Object exception) {
042                    _exceptions.add(exception);
043            }
044    
045            public Map<Object, Object> getMap() {
046                    return _map;
047            }
048    
049            public Object getNewValue(Object oldValue) throws Exception {
050                    Object value = _map.get(oldValue);
051    
052                    if (value == null) {
053                            if (_exceptions.contains(oldValue)) {
054                                    value = oldValue;
055                            }
056                            else {
057                                    throw new StagnantRowException(String.valueOf(oldValue));
058                            }
059                    }
060    
061                    return value;
062            }
063    
064            public Iterator<Object> iterator() throws Exception {
065                    return _map.keySet().iterator();
066            }
067    
068            public void mapValue(Object oldValue, Object newValue) throws Exception {
069                    _map.put(oldValue, newValue);
070            }
071    
072            public int size() throws Exception {
073                    return _map.size();
074            }
075    
076            private Set<Object> _exceptions;
077            private Map<Object, Object> _map;
078    
079    }