001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Anahide Tchertchian
018 */
019package org.nuxeo.ecm.platform.ui.web.component;
020
021import javax.faces.model.SelectItem;
022
023/**
024 * Helper for select items management
025 *
026 * @since 6.0
027 */
028public abstract class SelectItemFactory {
029
030    protected abstract String getVar();
031
032    protected abstract SelectItem createSelectItem();
033
034    public SelectItem createSelectItem(Object value) {
035        SelectItem item = null;
036        Object varValue = saveRequestMapVarValue();
037        try {
038            putIteratorToRequestParam(value);
039            item = createSelectItem();
040            removeIteratorFromRequestParam();
041        } finally {
042            restoreRequestMapVarValue(varValue);
043        }
044        return item;
045    }
046
047    protected void putIteratorToRequestParam(Object object) {
048        String var = getVar();
049        VariableManager.putVariableToRequestParam(var, object);
050    }
051
052    protected void removeIteratorFromRequestParam() {
053        String var = getVar();
054        VariableManager.removeVariableFromRequestParam(var);
055    }
056
057    /**
058     * Returns the value exposed in request map for the var name.
059     * <p>
060     * This is useful for restoring this value in the request map.
061     *
062     * @since 5.4.2
063     */
064    protected final Object saveRequestMapVarValue() {
065        String varName = getVar();
066        return VariableManager.saveRequestMapVarValue(varName);
067    }
068
069    /**
070     * Restores the given value in the request map for the var name.
071     *
072     * @since 5.4.2
073     */
074    protected final void restoreRequestMapVarValue(Object value) {
075        VariableManager.restoreRequestMapVarValue(getVar(), value);
076    }
077
078}