001    /**
002     * Copyright (c) 2000-2010 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.security.permission;
016    
017    import com.liferay.portal.kernel.log.Log;
018    import com.liferay.portal.kernel.log.LogFactoryUtil;
019    import com.liferay.portal.model.User;
020    import com.liferay.portal.security.auth.PrincipalThreadLocal;
021    import com.liferay.portal.service.UserLocalServiceUtil;
022    
023    /**
024     * @author Brian Wing Shun Chan
025     */
026    public abstract class DoAsUserThread extends Thread {
027    
028            public DoAsUserThread(long userId) {
029                    _userId = userId;
030            }
031    
032            public boolean isSuccess() {
033                    return _success;
034            }
035    
036            public void run() {
037                    try {
038                            PrincipalThreadLocal.setName(_userId);
039    
040                            User user = UserLocalServiceUtil.getUserById(_userId);
041    
042                            PermissionChecker permissionChecker =
043                                    PermissionCheckerFactoryUtil.create(user, true);
044    
045                            PermissionThreadLocal.setPermissionChecker(permissionChecker);
046    
047                            doRun();
048    
049                            _success = true;
050                    }
051                    catch (Exception e) {
052                            _log.error(e, e);
053                    }
054                    finally {
055                            PrincipalThreadLocal.setName(null);
056                            PermissionThreadLocal.setPermissionChecker(null);
057                    }
058            }
059    
060            protected abstract void doRun() throws Exception;
061    
062            private static Log _log = LogFactoryUtil.getLog(DoAsUserThread.class);
063    
064            private long _userId;
065            private boolean _success;
066    
067    }