001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.wicket.bean.validation;
018
019import java.util.ArrayList;
020
021import org.apache.wicket.model.LoadableDetachableModel;
022import org.apache.wicket.util.reference.ClassReference;
023
024/**
025 * A model that can hold on to an array of classes. Useful for keeping a definition of validation
026 * groups to be used to restrict validation.
027 * 
028 * @author igor
029 */
030public class GroupsModel extends LoadableDetachableModel<Class<?>[]>
031{
032        private static final Class<?>[] EMPTY = new Class<?>[0];
033
034        private final ArrayList<ClassReference<?>> groups;
035
036        /**
037         * Constructor
038         * 
039         * @param groups
040         *            an array of groups or {@code null} for none
041         */
042        public GroupsModel(Class<?>... groups)
043        {
044                if (groups == null || groups.length == 0)
045                {
046                        this.groups = null;
047                }
048                else
049                {
050                        this.groups = new ArrayList<>();
051                        for (Class<?> group : groups)
052                        {
053                                this.groups.add(ClassReference.of(group));
054                        }
055                        this.groups.trimToSize();
056                }
057        }
058
059        @Override
060        protected Class<?>[] load()
061        {
062                if (groups == null)
063                {
064                        return EMPTY;
065                }
066
067                Class<?>[] classes = new Class[groups.size()];
068                for (int i = 0; i < groups.size(); i++)
069                {
070                        classes[i] = groups.get(i).get();
071                }
072
073                return classes;
074        }
075
076}