001/*
002 * Stallion Core: A Modern Web Framework
003 *
004 * Copyright (C) 2015 - 2016 Stallion Software LLC.
005 *
006 * This program is free software: you can redistribute it and/or modify it under the terms of the
007 * GNU General Public License as published by the Free Software Foundation, either version 2 of
008 * the License, or (at your option) any later version. This program is distributed in the hope that
009 * it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
011 * License for more details. You should have received a copy of the GNU General Public License
012 * along with this program.  If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
013 *
014 *
015 *
016 */
017
018package io.stallion.requests.validators;
019
020import io.stallion.dataAccess.Model;
021import io.stallion.reflection.PropertyUtils;
022
023import java.util.ArrayList;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027
028import static io.stallion.utils.Literals.*;
029
030
031public class SafeViewer<T extends Model> {
032
033    private String[] fields = new String[]{};
034
035    public SafeViewer(String...fields) {
036        this.fields = fields;
037    }
038
039    public SafeViewer(List<String> fields) {
040        this.fields = asArray(fields, String.class);
041    }
042
043    public Map<String, Object> wrap(T obj) {
044        return objToMap(obj);
045    }
046
047    public List<Map<String, Object>> wrap(List<T> objects) {
048        List<Map<String, Object>> items = new ArrayList<>();
049        for (T obj: objects) {
050            items.add(objToMap(obj));
051        }
052        return items;
053    }
054
055    private Map<String, Object> objToMap(T obj) {
056        Map<String, Object> map = new HashMap<>();
057        for (String field: fields) {
058            Object val = PropertyUtils.getPropertyOrMappedValue(obj, field);
059            map.put(field, val);
060        }
061        return map;
062    }
063
064
065}