001    /**
002     * Copyright (c) 2000-2013 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            @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);
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 boolean _success;
066            private long _userId;
067    
068    }