001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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                    if (remoteUser != null) {
041                            PrincipalThreadLocal.setName(remoteUser);
042    
043                            long userId = GetterUtil.getLong(remoteUser);
044    
045                            _user = UserLocalServiceUtil.getUserById(userId);
046    
047                            if (_companyId == 0) {
048                                    _companyId = _user.getCompanyId();
049                            }
050                    }
051                    else {
052                            if (_companyId == 0) {
053                                    _companyId = PortalInstances.getCompanyId(request);
054                            }
055    
056                            if (_companyId != 0) {
057                                    _user = UserLocalServiceUtil.getDefaultUser(_companyId);
058                            }
059                    }
060            }
061    
062            public long getCompanyId() {
063                    return _companyId;
064            }
065    
066            public User getUser() {
067                    return _user;
068            }
069    
070            private long _companyId;
071            private User _user;
072    
073    }