001/*
002 * (C) Copyright 2006-2008 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 *     bstefanescu
018 */
019package org.nuxeo.ecm.webengine.forms;
020
021import java.util.Collection;
022import java.util.HashMap;
023import java.util.Map;
024
025import org.nuxeo.ecm.webengine.forms.validation.Form;
026import org.nuxeo.ecm.webengine.forms.validation.FormManager;
027import org.nuxeo.ecm.webengine.forms.validation.ValidationException;
028
029/**
030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
031 */
032public class SimpleFormDataProvider extends HashMap<String, String[]> implements FormDataProvider {
033
034    private static final long serialVersionUID = 1L;
035
036    @Override
037    public Collection<String> getKeys() {
038        return keySet();
039    }
040
041    @Override
042    public String[] getList(String key) {
043        return get(key);
044    }
045
046    @Override
047    public String getString(String key) {
048        String[] v = get(key);
049        if (v != null && v.length > 0) {
050            return v[0];
051        }
052        return null;
053    }
054
055    @Override
056    public Map<String, String[]> getFormFields() {
057        return this;
058    }
059
060    public void putString(String key, String value) {
061        put(key, new String[] { value });
062    }
063
064    public void putList(String key, String... values) {
065        put(key, values);
066    }
067
068    public void putList(String key, Collection<String> values) {
069        if (values == null) {
070            return;
071        }
072        String[] ar = values.toArray(new String[values.size()]);
073        put(key, ar);
074    }
075
076    public <T extends Form> T validate(Class<T> type) throws ValidationException {
077        T proxy = FormManager.newProxy(type);
078        try {
079            proxy.load(this, proxy);
080            return proxy;
081        } catch (ValidationException e) {
082            e.setForm(proxy);
083            throw e;
084        }
085    }
086
087}