001    /**
002     * Copyright (c) 2000-2011 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            @Override
037            public void run() {
038                    try {
039                            PrincipalThreadLocal.setName(_userId);
040    
041                            User user = UserLocalServiceUtil.getUserById(_userId);
042    
043                            PermissionChecker permissionChecker =
044                                    PermissionCheckerFactoryUtil.create(user, true);
045    
046                            PermissionThreadLocal.setPermissionChecker(permissionChecker);
047    
048                            doRun();
049    
050                            _success = true;
051                    }
052                    catch (Exception e) {
053                            _log.error(e, e);
054                    }
055                    finally {
056                            PrincipalThreadLocal.setName(null);
057                            PermissionThreadLocal.setPermissionChecker(null);
058                    }
059            }
060    
061            protected abstract void doRun() throws Exception;
062    
063            private static Log _log = LogFactoryUtil.getLog(DoAsUserThread.class);
064    
065            private long _userId;
066            private boolean _success;
067    
068    }