001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.servlet;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.exception.SystemException;
019    import com.liferay.portal.kernel.util.GetterUtil;
020    import com.liferay.portal.kernel.util.ParamUtil;
021    import com.liferay.portal.model.User;
022    import com.liferay.portal.security.auth.PrincipalThreadLocal;
023    import com.liferay.portal.service.UserLocalServiceUtil;
024    import com.liferay.portal.util.PortalInstances;
025    
026    import javax.servlet.http.HttpServletRequest;
027    
028    /**
029     * @author Igor Spasic
030     */
031    public class UserResolver {
032    
033            public UserResolver(HttpServletRequest request)
034                    throws PortalException, SystemException {
035    
036                    _companyId = ParamUtil.getLong(request, "companyId");
037    
038                    String remoteUser = request.getRemoteUser();
039    
040                    long userId = GetterUtil.getLong(remoteUser);
041    
042                    if (userId == 0) {
043                            remoteUser = null;
044                    }
045    
046                    if (remoteUser != null) {
047                            PrincipalThreadLocal.setName(remoteUser);
048    
049                            _user = UserLocalServiceUtil.getUserById(userId);
050    
051                            if (_companyId == 0) {
052                                    _companyId = _user.getCompanyId();
053                            }
054                    }
055                    else {
056                            if (_companyId == 0) {
057                                    _companyId = PortalInstances.getCompanyId(request);
058                            }
059    
060                            if (_companyId != 0) {
061                                    _user = UserLocalServiceUtil.getDefaultUser(_companyId);
062                            }
063                    }
064            }
065    
066            public long getCompanyId() {
067                    return _companyId;
068            }
069    
070            public User getUser() {
071                    return _user;
072            }
073    
074            private long _companyId;
075            private User _user;
076    
077    }