    001// Copyright 2006, 2007, 2008, 2010,, 2011 The Apache Software Foundation
    002//
    003// Licensed under the Apache License, Version 2.0 (the "License");
    004// you may not use this file except in compliance with the License.
    005// You may obtain a copy of the License at
    006//
    007// http://www.apache.org/licenses/LICENSE-2.0
    008//
    009// Unless required by applicable law or agreed to in writing, software
    010// distributed under the License is distributed on an "AS IS" BASIS,
    011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    012// See the License for the specific language governing permissions and
    013// limitations under the License.
    014
    015package org.apache.tapestry5.ioc.internal;
    016
    017import java.util.Collection;
    018
    019import org.apache.tapestry5.commons.Configuration;
    020import org.apache.tapestry5.commons.ObjectLocator;
    021
    022/**
    023 * Wraps a {@link java.util.Collection} as a {@link org.apache.tapestry5.commons.Configuration} and perform validation that
    024 * collected value are of the correct type.
    025 */
    026public class ValidatingConfigurationWrapper<T> extends AbstractConfigurationImpl<T> implements Configuration<T>
    027{
    028    private final TypeCoercerProxy typeCoercer;
    029
    030    private final String serviceId;
    031
    032    private final Class<T> expectedType;
    033
    034    private final Collection<T> collection;
    035
    036    public ValidatingConfigurationWrapper(Class<T> expectedType, ObjectLocator locator, TypeCoercerProxy typeCoercer,
    037            Collection<T> collection, String serviceId)
    038    {
    039        super(expectedType, locator);
    040        this.typeCoercer = typeCoercer;
    041
    042        this.collection = collection;
    043        this.serviceId = serviceId;
    044        this.expectedType = expectedType;
    045    }
    046
    047    @Override
    048    public void add(T object)
    049    {
    050        if (object == null)
    051            throw new NullPointerException(IOCMessages.contributionWasNull(serviceId));
    052
    053        T coerced = typeCoercer.coerce(object, expectedType);
    054
    055        collection.add(coerced);
    056    }
    057
    058    @Override
    059    public void addInstance(Class<? extends T> clazz)
    060    {
    061        add(instantiate(clazz));
    062    }
    063}