001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Anahide Tchertchian
016 */
017package org.nuxeo.ecm.platform.ui.web.component;
018
019import javax.faces.model.SelectItem;
020
021/**
022 * Helper for select items management
023 *
024 * @since 6.0
025 */
026public abstract class SelectItemFactory {
027
028    protected abstract String getVar();
029
030    protected abstract SelectItem createSelectItem();
031
032    public SelectItem createSelectItem(Object value) {
033        SelectItem item = null;
034        Object varValue = saveRequestMapVarValue();
035        try {
036            putIteratorToRequestParam(value);
037            item = createSelectItem();
038            removeIteratorFromRequestParam();
039        } finally {
040            restoreRequestMapVarValue(varValue);
041        }
042        return item;
043    }
044
045    protected void putIteratorToRequestParam(Object object) {
046        String var = getVar();
047        VariableManager.putVariableToRequestParam(var, object);
048    }
049
050    protected void removeIteratorFromRequestParam() {
051        String var = getVar();
052        VariableManager.removeVariableFromRequestParam(var);
053    }
054
055    /**
056     * Returns the value exposed in request map for the var name.
057     * <p>
058     * This is useful for restoring this value in the request map.
059     *
060     * @since 5.4.2
061     */
062    protected final Object saveRequestMapVarValue() {
063        String varName = getVar();
064        return VariableManager.saveRequestMapVarValue(varName);
065    }
066
067    /**
068     * Restores the given value in the request map for the var name.
069     *
070     * @since 5.4.2
071     */
072    protected final void restoreRequestMapVarValue(Object value) {
073        VariableManager.restoreRequestMapVarValue(getVar(), value);
074    }
075
076}