001/*
002 * Copyright 2007-2008 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.rice.kim.util;
017
018import java.util.Map;
019import java.util.Set;
020
021import org.apache.commons.beanutils.PropertyUtils;
022import org.apache.commons.lang.StringUtils;
023import org.kuali.ole.sys.context.SpringContext;
024import org.kuali.rice.core.api.config.property.ConfigurationService;
025import org.kuali.rice.kew.api.KewApiServiceLocator;
026import org.kuali.rice.kew.api.doctype.DocumentType;
027import org.kuali.rice.kim.api.KimConstants;
028
029/**
030 * This is a description of what this class does - bhargavp don't forget to fill
031 * this in.
032 *
033 * @author Kuali Rice Team (rice.collab@kuali.org)
034 *
035 */
036public class KimCommonUtils {
037    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(KimCommonUtils.class);
038
039    public static String getClosestParentDocumentTypeName( DocumentType documentType, Set<String> potentialParentDocumentTypeNames) {
040        if ( potentialParentDocumentTypeNames == null || documentType == null ) {
041            return null;
042        }
043        if (potentialParentDocumentTypeNames.contains(documentType.getName())) {
044            return documentType.getName();
045        } else {
046            if ( StringUtils.isBlank(documentType.getParentId())
047                    || StringUtils.equals( documentType.getParentId(), documentType.getId() ) ) {
048                return null;
049            } else {
050                return getClosestParentDocumentTypeName(KewApiServiceLocator.getDocumentTypeService().getDocumentTypeById(documentType.getParentId()), potentialParentDocumentTypeNames);
051            }
052        }
053    }
054
055    public static boolean storedValueNotSpecifiedOrInputValueMatches(Map<String,String> storedValues, Map<String,String> inputValues, String attributeName) {
056        return ((storedValues == null) || (inputValues == null)) || !storedValues.containsKey(attributeName) || StringUtils.equals( storedValues.get(attributeName), inputValues.get(attributeName));
057    }
058
059    public static boolean doesPropertyNameMatch(
060            String requestedDetailsPropertyName,
061            String permissionDetailsPropertyName) {
062        if (StringUtils.isBlank(permissionDetailsPropertyName)) {
063            return true;
064        }
065        return StringUtils.equals(requestedDetailsPropertyName, permissionDetailsPropertyName)
066                || (StringUtils.startsWith(requestedDetailsPropertyName,permissionDetailsPropertyName+"."));
067    }
068
069//    public static Map<String,String> getNamespaceAndComponentSimpleName( Class<? extends Object> clazz) {
070//        Map<String,String> attributeSet = new HashMap<String,String>();
071//        attributeSet.put(KimConstants.AttributeConstants.NAMESPACE_CODE, getNamespaceCode(clazz));
072//        attributeSet.put(KimConstants.AttributeConstants.COMPONENT_NAME, getComponentSimpleName(clazz));
073//        return attributeSet;
074//    }
075//
076//    public static Map<String,String> getNamespaceAndComponentFullName( Class<? extends Object> clazz) {
077//        Map<String,String> attributeSet = new HashMap<String,String>();
078//        attributeSet.put(KimConstants.AttributeConstants.NAMESPACE_CODE, getNamespaceCode(clazz));
079//        attributeSet.put(KimConstants.AttributeConstants.COMPONENT_NAME, getComponentFullName(clazz));
080//        return attributeSet;
081//    }
082//
083//    public static Map<String,String> getNamespaceAndActionClass( Class<? extends Object> clazz) {
084//        Map<String,String> attributeSet = new HashMap<String,String>();
085//        attributeSet.put(KimConstants.AttributeConstants.NAMESPACE_CODE, getNamespaceCode(clazz));
086//        attributeSet.put(KimConstants.AttributeConstants.ACTION_CLASS, clazz.getName());
087//        return attributeSet;
088//    }
089//
090//    public static String getNamespaceCode(Class<? extends Object> clazz) {
091//        ModuleService moduleService = getKualiModuleService().getResponsibleModuleService(clazz);
092//        if (moduleService == null) {
093//            return KimApiConstants.KIM_TYPE_DEFAULT_NAMESPACE;
094//        }
095//        return moduleService.getModuleConfiguration().getNamespaceCode();
096//    }
097
098    public static String getComponentSimpleName(Class<? extends Object> clazz) {
099        return clazz.getSimpleName();
100    }
101
102    public static String getComponentFullName(Class<? extends Object> clazz) {
103        return clazz.getName();
104    }
105
106//    public static boolean isAttributeSetEntryEquals( Map<String,String> map1, Map<String,String> map2, String key ) {
107//        return StringUtils.equals( map1.get( key ), map2.get( key ) );
108//    }
109
110    public static void copyProperties(Object targetToCopyTo, Object sourceToCopyFrom){
111        if(targetToCopyTo!=null && sourceToCopyFrom!=null)
112        try{
113            PropertyUtils.copyProperties(targetToCopyTo, sourceToCopyFrom);
114        } catch(Exception ex){
115            throw new RuntimeException("Failed to copy from source object: "+sourceToCopyFrom.getClass()+" to target object: "+targetToCopyTo,ex);
116        }
117    }
118
119    public static String getKimBasePath(){
120        String kimBaseUrl = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(KimConstants.KimUIConstants.KIM_URL_KEY);
121        if (!kimBaseUrl.endsWith(KimConstants.KimUIConstants.URL_SEPARATOR)) {
122            kimBaseUrl = kimBaseUrl + KimConstants.KimUIConstants.URL_SEPARATOR;
123        }
124        return kimBaseUrl;
125    }
126
127    public static String getPathWithKimContext(String path, String kimActionName){
128        String kimContext = KimConstants.KimUIConstants.KIM_APPLICATION+KimConstants.KimUIConstants.URL_SEPARATOR;
129        String kimContextParameterized = KimConstants.KimUIConstants.KIM_APPLICATION+KimConstants.KimUIConstants.PARAMETERIZED_URL_SEPARATOR;
130        if(path.contains(kimActionName) && !path.contains(kimContext + kimActionName)
131                && !path.contains(kimContextParameterized + kimActionName))
132            path = path.replace(kimActionName, kimContext+kimActionName);
133        return path;
134    }
135
136//    protected static boolean canOverrideEntityPrivacyPreferences( String principalId ){
137//        return getIdentityManagementService().isAuthorized(
138//                GlobalVariables.getUserSession().getPrincipalId(),
139//                KimConstants.NAMESPACE_CODE,
140//                KimApiConstants.PermissionNames.OVERRIDE_ENTITY_PRIVACY_PREFERENCES,
141//                null,
142//                new HashMap<String,String>(KimConstants.AttributeConstants.PRINCIPAL_ID, principalId) );
143//    }
144//
145//    public static boolean isSuppressName(String entityId) {
146//        EntityPrivacyPreferences privacy = null;
147//        EntityDefaultInfo entityInfo = getIdentityManagementService().getEntityDefaultInfo(entityId);
148//        if (entityInfo != null) {
149//            privacy = entityInfo.getPrivacyPreferences();
150//        }
151//        UserSession userSession = GlobalVariables.getUserSession();
152//
153//        boolean suppressName = false;
154//        if (privacy != null) {
155//            suppressName = privacy.isSuppressName();
156//        }
157//        return suppressName
158//                && userSession != null
159//                && !StringUtils.equals(userSession.getPerson().getEntityId(), entityId)
160//                && !canOverrideEntityPrivacyPreferences(entityInfo.getPrincipals().get(0).getPrincipalId());
161//    }
162//
163//    public static boolean isSuppressEmail(String entityId) {
164//        EntityPrivacyPreferences privacy = null;
165//        EntityDefaultInfo entityInfo = getIdentityManagementService().getEntityDefaultInfo(entityId);
166//        if (entityInfo != null) {
167//            privacy = entityInfo.getPrivacyPreferences();
168//        }
169//        UserSession userSession = GlobalVariables.getUserSession();
170//
171//        boolean suppressEmail = false;
172//        if (privacy != null) {
173//            suppressEmail = privacy.isSuppressEmail();
174//        }
175//        return suppressEmail
176//                && userSession != null
177//                && !StringUtils.equals(userSession.getPerson().getEntityId(), entityId)
178//                && !canOverrideEntityPrivacyPreferences(entityInfo.getPrincipals().get(0).getPrincipalId());
179//    }
180//
181//    public static boolean isSuppressAddress(String entityId) {
182//        EntityPrivacyPreferences privacy = null;
183//        EntityDefaultInfo entityInfo = getIdentityManagementService().getEntityDefaultInfo(entityId);
184//        if (entityInfo != null) {
185//            privacy = entityInfo.getPrivacyPreferences();
186//        }
187//        UserSession userSession = GlobalVariables.getUserSession();
188//
189//        boolean suppressAddress = false;
190//        if (privacy != null) {
191//            suppressAddress = privacy.isSuppressAddress();
192//        }
193//        return suppressAddress
194//                && userSession != null
195//                && !StringUtils.equals(userSession.getPerson().getEntityId(), entityId)
196//                && !canOverrideEntityPrivacyPreferences(entityInfo.getPrincipals().get(0).getPrincipalId());
197//    }
198//
199//    public static boolean isSuppressPhone(String entityId) {
200//        EntityPrivacyPreferences privacy = null;
201//        EntityDefaultInfo entityInfo = getIdentityManagementService().getEntityDefaultInfo(entityId);
202//        if (entityInfo != null) {
203//            privacy = entityInfo.getPrivacyPreferences();
204//        }
205//        UserSession userSession = GlobalVariables.getUserSession();
206//
207//        boolean suppressPhone = false;
208//        if (privacy != null) {
209//            suppressPhone = privacy.isSuppressPhone();
210//        }
211//        return suppressPhone
212//                && userSession != null
213//                && !StringUtils.equals(userSession.getPerson().getEntityId(), entityId)
214//                && !canOverrideEntityPrivacyPreferences(entityInfo.getPrincipals().get(0).getPrincipalId());
215//    }
216//
217//    public static boolean isSuppressPersonal(String entityId) {
218//        EntityPrivacyPreferences privacy = null;
219//        EntityDefaultInfo entityInfo = getIdentityManagementService().getEntityDefaultInfo(entityId);
220//        if (entityInfo != null) {
221//            privacy = entityInfo.getPrivacyPreferences();
222//        }
223//        UserSession userSession = GlobalVariables.getUserSession();
224//
225//        boolean suppressPersonal = false;
226//        if (privacy != null) {
227//            suppressPersonal = privacy.isSuppressPersonal();
228//        }
229//        return suppressPersonal
230//                && userSession != null
231//                && !StringUtils.equals(userSession.getPerson().getEntityId(), entityId)
232//                && !canOverrideEntityPrivacyPreferences(entityInfo.getPrincipals().get(0).getPrincipalId());
233//    }
234//
235//    public static String encryptExternalIdentifier(String externalIdentifier, String externalIdentifierType){
236//        Map<String, String> criteria = new HashMap<String, String>();
237//        criteria.put(KimConstants.PrimaryKeyConstants.KIM_TYPE_CODE, externalIdentifierType);
238//        ExternalIdentifierType externalIdentifierTypeObject = (ExternalIdentifierType) KNSServiceLocator.getBusinessObjectService().findByPrimaryKey(ExternalIdentifierTypeImpl.class, criteria);
239//        if( externalIdentifierTypeObject!= null && externalIdentifierTypeObject.isEncryptionRequired()){
240//            if(StringUtils.isNotEmpty(externalIdentifier)){
241//                try{
242//                    return SpringContext.getBean(EncryptionService.class).encrypt(externalIdentifier);
243//                }catch (GeneralSecurityException e) {
244//                    LOG.info("Unable to encrypt value : " + e.getMessage() + " or it is already encrypted");
245//                }
246//            }
247//        }
248//        return externalIdentifier;
249//    }
250//
251//    public static String decryptExternalIdentifier(String externalIdentifier, String externalIdentifierType){
252//        Map<String, String> criteria = new HashMap<String, String>();
253//        criteria.put(KimConstants.PrimaryKeyConstants.KIM_TYPE_CODE, externalIdentifierType);
254//        ExternalIdentifierType externalIdentifierTypeObject = (ExternalIdentifierType) KNSServiceLocator.getBusinessObjectService().findByPrimaryKey(ExternalIdentifierTypeImpl.class, criteria);
255//        if( externalIdentifierTypeObject!= null && externalIdentifierTypeObject.isEncryptionRequired()){
256//            if(StringUtils.isNotEmpty(externalIdentifier)){
257//                try{
258//                    return SpringContext.getBean(EncryptionService.class).decrypt(externalIdentifier);
259//                }catch (GeneralSecurityException e) {
260//                    LOG.info("Unable to decrypt value : " + e.getMessage() + " or it is already decrypted");
261//                }
262//            }
263//        }
264//        return externalIdentifier;
265//    }
266//
267//    public static IdentityManagementService getIdentityManagementService() {
268//        if ( identityManagementService == null ) {
269//            identityManagementService = SpringContext.getBean(IdentityManagementService.class);
270//        }
271//        return identityManagementService;
272//    }
273//
274//
275//    public static GroupImpl copyInfoToGroup(Group info, GroupImpl group) {
276//        group.setActive(info.isActive());
277//        group.setGroupDescription(info.getGroupDescription());
278//        group.setGroupId(info.getGroupId());
279//        group.setGroupName(info.getGroupName());
280//        group.setKimTypeId(info.getKimTypeId());
281//        group.setNamespaceCode(info.getNamespaceCode());
282//
283//        return group;
284//    }
285//
286//    /**
287//     *
288//     * @param infoMap Containing the Info Attribute objects.
289//     * @param groupId for the group of attributes
290//     * @param kimTypeId for the group of attributes
291//     * @return a list of group attributes
292//     */
293//
294//    public static List<GroupAttributeDataImpl> copyInfoAttributesToGroupAttributes(Map<String, String> infoMap, String groupId, String kimTypeId) {
295//        List<GroupAttributeDataImpl> attrList = new ArrayList<GroupAttributeDataImpl>(infoMap.size());
296//        List<KimTypeAttribute> attributeInfoList = SpringContext.getBean(KimTypeInfoService.class).getKimType(kimTypeId).getAttributeDefinitions();
297//
298//        for (String key : infoMap.keySet()) {
299//            KimTypeAttribute typeAttributeInfo = getAttributeInfo(attributeInfoList, key);
300//
301//            if (typeAttributeInfo != null) {
302//                GroupAttributeDataImpl groupAttribute = new GroupAttributeDataImpl();
303//                groupAttribute.setKimAttributeId(typeAttributeInfo.getKimAttributeId());
304//                groupAttribute.setAttributeValue(infoMap.get(typeAttributeInfo.getAttributeName()));
305//                groupAttribute.setGroupId(groupId);
306//                groupAttribute.setKimTypeId(kimTypeId);
307//                attrList.add(groupAttribute);
308//            } else {
309//                throw new IllegalArgumentException("KimAttribute not found: " + key);
310//            }
311//        }
312//        return attrList;
313//    }
314//
315//    private static KimTypeAttribute getAttributeInfo(List<KimTypeAttribute> attributeInfoList, String attributeName) {
316//        KimTypeAttribute kRet = null;
317//        for (KimTypeAttribute attributeInfo : attributeInfoList) {
318//            if (attributeInfo.getAttributeName().equals(attributeName)) {
319//                kRet = attributeInfo;
320//                break;
321//            }
322//        }
323//        return kRet;
324//    }
325
326}