    001// Copyright 2007, 2008, 2009, 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.internal.services;
    016
    017import java.util.Locale;
    018import java.util.Set;
    019
    020import org.apache.tapestry5.SymbolConstants;
    021import org.apache.tapestry5.commons.util.CollectionFactory;
    022import org.apache.tapestry5.internal.TapestryInternalUtils;
    023import org.apache.tapestry5.ioc.annotations.Symbol;
    024import org.apache.tapestry5.ioc.services.PerThreadValue;
    025import org.apache.tapestry5.ioc.services.PerthreadManager;
    026import org.apache.tapestry5.services.PersistentLocale;
    027
    028public class PersistentLocaleImpl implements PersistentLocale
    029{
    030    private final String supportedLocales;
    031
    032    private final PerThreadValue<Locale> localeValue;
    033
    034    private final Set<String> localeNames = CollectionFactory.newSet();
    035
    036    public PersistentLocaleImpl(PerthreadManager perThreadManager,
    037
    038    @Symbol(SymbolConstants.SUPPORTED_LOCALES)
    039    String supportedLocales)
    040    {
    041        this.supportedLocales = supportedLocales;
    042
    043        localeValue = perThreadManager.createValue();
    044
    045        for (String name : TapestryInternalUtils.splitAtCommas(supportedLocales))
    046        {
    047            localeNames.add(name.toLowerCase());
    048        }
    049    }
    050
    051    public void set(Locale locale)
    052    {
    053        assert locale != null;
    054
    055        if (!localeNames.contains(locale.toString().toLowerCase()))
    056        {
    057            String message = String
    058                    .format("Locale '%s' is not supported by this application. Supported locales are '%s'; this is configured via the %s symbol.",
    059                            locale, supportedLocales, SymbolConstants.SUPPORTED_LOCALES);
    060
    061            throw new IllegalArgumentException(message);
    062        }
    063
    064        localeValue.set(locale);
    065    }
    066
    067    public Locale get()
    068    {
    069        return localeValue.get();
    070    }
    071
    072    public boolean isSet()
    073    {
    074        return localeValue.exists();
    075    }
    076}