001/*
002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Sun Seng David TAN <stan@nuxeo.com>
016 */
017package org.nuxeo.ecm.user.center.profile.localeProvider;
018
019import java.util.Locale;
020import java.util.TimeZone;
021
022import org.apache.commons.lang.LocaleUtils;
023import org.apache.commons.logging.Log;
024import org.apache.commons.logging.LogFactory;
025import org.nuxeo.ecm.core.api.CoreSession;
026import org.nuxeo.ecm.core.api.DocumentModel;
027import org.nuxeo.ecm.platform.web.common.locale.LocaleProvider;
028import org.nuxeo.ecm.user.center.profile.UserProfileConstants;
029import org.nuxeo.ecm.user.center.profile.UserProfileService;
030import org.nuxeo.runtime.api.Framework;
031
032/**
033 * Provides user local stored in profile doc model
034 *
035 * @since 5.6
036 */
037public class UserLocaleProvider implements LocaleProvider {
038    public static final Log log = LogFactory.getLog(UserLocaleProvider.class);
039
040    @Override
041    public Locale getLocale(CoreSession repo) {
042        UserProfileService userProfileService = Framework.getLocalService(UserProfileService.class);
043        DocumentModel userProfileDoc = userProfileService.getUserProfileDocument(repo);
044        return getLocale(userProfileDoc);
045    }
046
047    @Override
048    public Locale getLocale(DocumentModel userProfileDoc) {
049        String locale = (String) userProfileDoc.getPropertyValue(UserProfileConstants.USER_PROFILE_LOCALE);
050        if (locale == null || locale.trim().length() == 0) {
051            // undefined if not set
052            return null;
053        }
054        try {
055            return LocaleUtils.toLocale(locale);
056        } catch (IllegalArgumentException e) {
057            log.error("Locale parse exception:  \"" + locale + "\"", e);
058        }
059        return null;
060    }
061
062    @Override
063    public TimeZone getTimeZone(CoreSession repo) {
064        // the timezone is not retrieved from the user profile (cookie and Seam
065        // TimezoneSelector)
066        return null;
067    }
068
069}