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