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    public Collection<String> getKeys() {
037        return keySet();
038    }
039
040    public String[] getList(String key) {
041        return get(key);
042    }
043
044    public String getString(String key) {
045        String[] v = get(key);
046        if (v != null && v.length > 0) {
047            return v[0];
048        }
049        return null;
050    }
051
052    public Map<String, String[]> getFormFields() {
053        return this;
054    }
055
056    public void putString(String key, String value) {
057        put(key, new String[] { value });
058    }
059
060    public void putList(String key, String... values) {
061        put(key, values);
062    }
063
064    public void putList(String key, Collection<String> values) {
065        if (values == null) {
066            return;
067        }
068        String[] ar = values.toArray(new String[values.size()]);
069        put(key, ar);
070    }
071
072    public <T extends Form> T validate(Class<T> type) throws ValidationException {
073        T proxy = FormManager.newProxy(type);
074        try {
075            proxy.load(this, proxy);
076            return proxy;
077        } catch (ValidationException e) {
078            e.setForm(proxy);
079            throw e;
080        }
081    }
082
083}