001
014
015 package com.liferay.portal.service.base;
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.Validator;
021 import com.liferay.portal.model.User;
022 import com.liferay.portal.security.auth.CompanyThreadLocal;
023 import com.liferay.portal.security.auth.PrincipalException;
024 import com.liferay.portal.security.auth.PrincipalThreadLocal;
025 import com.liferay.portal.security.permission.PermissionChecker;
026 import com.liferay.portal.security.permission.PermissionThreadLocal;
027 import com.liferay.portal.service.UserLocalServiceUtil;
028
029
033 public class PrincipalBean {
034
035 public static final String[] ANONYMOUS_NAMES = {
036 PrincipalBean.JRUN_ANONYMOUS, PrincipalBean.ORACLE_ANONYMOUS,
037 PrincipalBean.SUN_ANONYMOUS, PrincipalBean.WEBLOGIC_ANONYMOUS
038 };
039
040 public static final String JRUN_ANONYMOUS = "anonymous-guest";
041
042 public static final String ORACLE_ANONYMOUS = "guest";
043
044 public static final String SUN_ANONYMOUS = "ANONYMOUS";
045
046 public static final String WEBLOGIC_ANONYMOUS = "<anonymous>";
047
048 public User getGuestOrUser() throws PortalException, SystemException {
049 try {
050 return getUser();
051 }
052 catch (PrincipalException pe) {
053 try {
054 return UserLocalServiceUtil.getDefaultUser(
055 CompanyThreadLocal.getCompanyId());
056 }
057 catch (Exception e) {
058 throw pe;
059 }
060 }
061 }
062
063 public long getGuestOrUserId() throws PrincipalException {
064 try {
065 return getUserId();
066 }
067 catch (PrincipalException pe) {
068 try {
069 return UserLocalServiceUtil.getDefaultUserId(
070 CompanyThreadLocal.getCompanyId());
071 }
072 catch (Exception e) {
073 throw pe;
074 }
075 }
076 }
077
078 public PermissionChecker getPermissionChecker() throws PrincipalException {
079 PermissionChecker permissionChecker =
080 PermissionThreadLocal.getPermissionChecker();
081
082 if (permissionChecker == null) {
083 throw new PrincipalException("PermissionChecker not initialized");
084 }
085
086 return permissionChecker;
087 }
088
089 public User getUser() throws PortalException, SystemException {
090 return UserLocalServiceUtil.getUserById(getUserId());
091 }
092
093 public long getUserId() throws PrincipalException {
094 String name = PrincipalThreadLocal.getName();
095
096 if (name == null) {
097 throw new PrincipalException();
098 }
099
100 if (Validator.isNull(name)) {
101 throw new PrincipalException("Principal cannot be null");
102 }
103 else {
104 for (int i = 0; i < ANONYMOUS_NAMES.length; i++) {
105 if (name.equalsIgnoreCase(ANONYMOUS_NAMES[i])) {
106 throw new PrincipalException(
107 "Principal cannot be " + ANONYMOUS_NAMES[i]);
108 }
109 }
110 }
111
112 return GetterUtil.getLong(name);
113 }
114
115 }