001    /**
002     * Copyright (c) 2000-2010 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.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    }