Java tutorial
/** * Copyright (c) 2001-2012 "Redbasin Networks, INC" [http://redbasin.org] * * This file is part of Redbasin OpenDocShare community project. * * Redbasin OpenDocShare is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Cookie; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.HashSet; import java.util.ArrayList; import java.util.List; import model.Directory; import ldap.LdapApi; /** * * @author Smitha Gudur (smitha@redbasin.com) * @version $Revision: 1.1 $ */ public class LdapUtil { /** Logger for this class and subclasses */ protected static final Log logger = LogFactory.getLog("util.LdapUtil"); private static int MAX_QNAMES_WITHOUT_HEADS = 4; private static int MAX_QNAMES_WITH_HEADS = 5; /** * Check if a string is null. If the string has blanks, then they * will be trimmed! * * @param str check if the string is a null * @return boolean the login */ public static List getOrganization() { List organization = new ArrayList(); if (organization == null) { return null; } else { organization.add(LdapConstants.ldapOrganization); return organization; } } /** * get the quotaValue for a user * The order of precedence is as follows, the highest being the user and the lowest being * enterprise/default/organization wide. * 1. user * 2. section * 3. division * 4. group * 5. organization * The superceding rule applies in the precedence order whether the quota level is higher or * or lower value. * Eg: user quota size=100 GB * organization quota size = 200GB. * The user quota size takes precedence over the organizations quota size. * If the user user quota size is not set, then the user quota size will take the value of the * based on the precedence value which is set. * * @param quotaListTypes - quota types is the one that the user belongs to * @param quotaListVals - quota size values is the ones that the user belongs to * @param userQuotaSize - userQuotaSize * @return String - return the user quota * */ public static String getUserQuota(List quotaList, String userQuotaSize) throws Exception { /** return the userQuotaSize as this takes precedence over everything, if it not zero or "0" */ if (RegexStrUtil.isNull(userQuotaSize)) { userQuotaSize = "0"; } else { if (!userQuotaSize.equals("0")) { return userQuotaSize; } } /** if userQuotaSize is not set or is "0", proceed with the precedence order */ if (quotaList == null) { return userQuotaSize; } /** * set the array with the precedence */ String[] ldapTypes = { LdapConstants.ldapArea, LdapConstants.ldapSection, LdapConstants.ldapDivision, LdapConstants.ldapGroup, LdapConstants.ldapOrganization }; for (int i = 0; i < ldapTypes.length; i++) { // get first area for (int j = 0; j < quotaList.size(); j++) { String qType = (String) ((Directory) quotaList.get(j)).getValue(DbConstants.QTYPE); String qName = (String) ((Directory) quotaList.get(j)).getValue(DbConstants.QNAME); String qSize = (String) ((Directory) quotaList.get(j)).getValue(DbConstants.QSIZE); logger.info("Name = " + qType); logger.info("Type = " + qName); logger.info("Value = " + qSize); logger.info("quotaList.get(j) = " + (String) quotaList.get(j).toString()); logger.info("ldapTypes[i] = " + (String) ldapTypes[i]); if (qType.equalsIgnoreCase(((String) ldapTypes[i]))) { logger.info("matches " + qType + " for " + qName); if (RegexStrUtil.isNull(qSize) || qSize.equals("0")) { continue; // we should move ahead to the next level of precedence //throw new Exception("qSize is null for quotaname= " + (String)qName = " + userQuotaSize); } else { logger.info("quotaListName = " + qType); logger.info("quotaListType = " + qName); logger.info("quotaListVals = " + qSize); return qSize; } } // if } //quotaListTypes } //ldapTypes return ("0"); } /** * checks if the user is exceeding the limits of userquota * @param userQuotaSize * @param quotaList * @param userUsedQuota * @return boolean * returns true if it exceeds the quota size, false otherwise. */ public static boolean checkMaxLimit(String userQuotaSize, List quotaList, String userUsedQuota) throws Exception { // set it to the default precedence try { if (RegexStrUtil.isNull(userQuotaSize)) { userQuotaSize = "0"; } if (RegexStrUtil.isNull(userUsedQuota)) { logger.info("userUsedQuota is null, checkMaxLimit"); return false; } float userUsedQuotaFloat = 0; String usedQuota = null; usedQuota = userUsedQuota.substring(0, userUsedQuota.length() - 1); if (!RegexStrUtil.isNull(usedQuota)) { logger.info("boolean, usedQuota=" + usedQuota); userUsedQuotaFloat = new Float(usedQuota).floatValue(); logger.info("boolean, userUsedQuotaFloat=" + userUsedQuotaFloat); } else { logger.info("boolean, usedQuota is null"); return false; } logger.info("userQuotaSize = " + userQuotaSize); String assignedQuota = getUserQuota(quotaList, userQuotaSize); if (RegexStrUtil.isNull(assignedQuota)) { logger.info("assignedQuota is null, checkMaxLimit"); return false; } logger.info("boolean, assignedQuota = " + assignedQuota); String sizeType = getSizeType(userUsedQuota); if (sizeType.equals(SanConstants.kiloBytes)) { return false; } else { if (sizeType.equals(SanConstants.megaBytes)) { if (!RegexStrUtil.isNull(assignedQuota)) { float quotaLimit = (new Float(assignedQuota).floatValue()) * SanConstants.minSizeLimit; if (userUsedQuotaFloat >= quotaLimit) { logger.info( "megaBytes, userUsedQuotaFloat is greater than the quotaLimit, return true, userUsedQuota = " + userUsedQuotaFloat + " QuotaLimit=" + quotaLimit); return true; } } } else { if (sizeType.equals(SanConstants.gigaBytes)) { if (!RegexStrUtil.isNull(assignedQuota)) { float quotaLimit = new Float(assignedQuota).floatValue(); if (userUsedQuotaFloat >= quotaLimit) { logger.info( "gigaBytes, userUsedQuotaFloat is greater than the quotaLimit, return true, userUsedQuota=" + userUsedQuotaFloat + " quotaLimit=" + quotaLimit); return true; } } } } } } catch (Exception e) { throw new Exception("boolean(), checkMaxLimit() error in getUserQuota" + e.getMessage(), e); } return false; } /** * checks if the user is exceeding the limits of userquota * if based on the % threshold, put the statement in red or orange */ public static String checkUserQuotaLimit(String userQuotaSize, List quotaList, String userUsedQuota) throws Exception { // set it to the default precedence String assignedQuota = userQuotaSize; try { if (RegexStrUtil.isNull(userQuotaSize)) { userQuotaSize = "0"; } if (RegexStrUtil.isNull(userUsedQuota)) { return null; } assignedQuota = getUserQuota(quotaList, userQuotaSize); logger.info("assignedQuota = " + assignedQuota); float softQuotaLimit = 0; String sizeType = getSizeType(userUsedQuota); if (!RegexStrUtil.isNull(assignedQuota) && !RegexStrUtil.isNull(sizeType)) { if (sizeType.equals(SanConstants.megaBytes)) { logger.info("userUsedQuota is in gigabytes"); softQuotaLimit = (new Float(assignedQuota).floatValue()) * LdapConstants.softQuotaLimit * SanConstants.minSizeLimit; } else { if (sizeType.equals(SanConstants.gigaBytes)) { logger.info("userUsedQuota is in gigabytes"); softQuotaLimit = (new Float(assignedQuota).floatValue()) * LdapConstants.softQuotaLimit; } else { // no message for kilobytes as it less than the limit if (sizeType.equals(SanConstants.kiloBytes)) { return null; } } } logger.info("softQuotaLimit = " + softQuotaLimit); } return getQuotaMsg(softQuotaLimit, userUsedQuota); } catch (Exception e) { throw new Exception("checkUserQuotaLimit() error in getUserQuota" + e.getMessage(), e); } } /** * get the quota names for quota types (area/section/group/division) */ public static List getQNames(String expression, String token) { //String expression = "cn=ANANT SHRIPADRAO ATHAVALE,ou=Central Computer Systems Division,ou=Central Computer Systems Division,ou=COMPUTERS AND INFORMATION GROUP,ou=DIRECTORS OFFICE AREA,ou=isac,dc=isro,dc=dos"; //String token = ",ou="; logger.info("expression = " + expression + " token=" + token); if (RegexStrUtil.isNull(expression) || RegexStrUtil.isNull(token)) { return null; } int SkipFirst = 0; int MaxQNames = MAX_QNAMES_WITHOUT_HEADS; /* 4 */ if (expression.contains("heads")) { MaxQNames = MAX_QNAMES_WITH_HEADS; /* 5 */ } String[] users = expression.split(token); logger.info("users = " + users.toString()); List keywords = new ArrayList(); int k = 0; if (keywords != null && users != null && users.length > 0) { for (int i = 0; i < users.length; i++) { if (users[i] != null) { if (i == SkipFirst || i > MaxQNames) { continue; } else { logger.info("users[" + i + "]=" + users[i]); /** * Needa better a way to get the organization information */ if (users[i].contains("heads")) { logger.info("skip the heads definition"); continue; } /* if (users[i].contains("dc=")) { String[] areaOrg = users[i].split("dc="); for (int j = 0; j < areaOrg.length; j++) { if (!RegexStrUtil.isNull( areaOrg[j])) { logger.info("areaOrg = " + areaOrg[j]); int ind = areaOrg[j].indexOf(","); if (ind != -1) { areaOrg[j] = areaOrg[j].substring(0,ind); logger.info("substring areaOrg = " + areaOrg[j]); } keywords.add(areaOrg[j]); } } } else { */ /* } */ keywords.add(users[i]); logger.info("keywords[" + k + "]=" + keywords.get(k)); k++; } } } keywords.add("organization"); } logger.info("keywords SIZE = " + keywords.size()); logger.info("keywords Str = " + keywords.toString()); return keywords; } /** * getQTypes - get structure types that are already predefined in ldap structure * in the order of precedence * @return List - list of structure types that are mapped to quotas * */ public static String[] getQTypes() { String[] ldapTypes = { LdapConstants.ldapSection, LdapConstants.ldapDivision, LdapConstants.ldapGroup, LdapConstants.ldapArea, LdapConstants.ldapOrganization }; return ldapTypes; } /** * getUserGroupInfo * @param login - login * @return String - return group the user belongs to * @throw Exception */ public static String getUserGroupInfo(String attrType, String attrVal) throws Exception { logger.info("entered getUserGroupInfo, attrVal=" + attrVal + " attrType=" + attrType); try { LdapApi ldapConnection = new LdapApi(); logger.info("ldapConnection"); if (ldapConnection == null) { throw new Exception("ldapConnection is null, LdapUtil"); } else { logger.info("attrType = " + attrType + " attrValue = " + attrVal); List qNames = ldapConnection.getUserStructure(attrType, attrVal); logger.info("getUserStructure entered"); if (qNames != null) { logger.info("qNames.size()" + qNames.size()); logger.info("group = " + (String) qNames.get(LdapConstants.ldapGroupIndex - 1)); return (String) qNames.get(LdapConstants.ldapGroupIndex - 1); } } } catch (Exception e) { throw new Exception("getUserGroupInfo() ldapConnection/getUserStructure() exception, " + e.getMessage(), e); } logger.info("qnames is null"); return null; } /** * getUserGroupAndAreaInfo * @param login - login * @return String - return group and area the user belongs to * ou=< division/group >,ou=< area > * @throw Exception */ public static String getUserGroupAndAreaInfo(String attrType, String attrVal) throws Exception { logger.info("entered getUserGroupAndAreaInfo, attrVal=" + attrVal + " attrType=" + attrType); try { LdapApi ldapConnection = new LdapApi(); if (ldapConnection == null) { throw new Exception("ldapConnection is null, LdapUtil::getUserGroupAndAreaInfo"); } else { logger.info("attrType = " + attrType + " attrValue = " + attrVal); List qNames = ldapConnection.getUserStructure(attrType, attrVal); logger.info("getUserGroupAndAreaInfo(), getUserStructure() entered"); if (qNames != null) { logger.info("qNames.size()" + qNames.size()); logger.info("group = " + (String) qNames.get(LdapConstants.ldapGroupIndex - 1)); if (qNames.size() >= LdapConstants.ldapGroupIndex) { String group = (String) qNames.get(LdapConstants.ldapGroupIndex - 1); String area = (String) qNames.get(LdapConstants.ldapGroupIndex); if (!RegexStrUtil.isNull(group)) { StringBuffer sb = new StringBuffer(); if (sb != null) { sb.append(group); sb.append(","); if (!RegexStrUtil.isNull(area)) { sb.append("ou="); sb.append(area); } logger.info("sb = " + sb.toString()); sb.toString(); return sb.toString(); } } } } else { logger.info("qnames is null"); } } } catch (Exception e) { throw new Exception("getUserGroupInfo() ldapConnection/getUserStructureGroupAndAreaInfo() exception, " + e.getMessage(), e); } return null; } /** * getUserSearchDn This method returns the complete searchDn used for ldap searches * @param - searchDn This can be a string composing of * user(cn)/section/division/area/organization for example: Computers User Group * @return - returns the complete searchDn that will be used for ldap appended * with ldapAdminRoleDn */ public static String getUserSearchDn(String searchDn) throws Exception { logger.info("searchDn = " + searchDn); if (!RegexStrUtil.isNull(searchDn)) { StringBuffer sb = new StringBuffer("ou="); sb.append(searchDn); sb.append(","); sb.append(LdapConstants.ldapAdminRoleDn); logger.info("searchDn = " + sb.toString()); return sb.toString(); } else { return null; } } /** * removeElements() remove the elements from list1 that are in list2 and return list1. * @param list1 remove the elements that contains in the list2 * @param list2 has elements that need to be removed from list1 * @return List return the list of elements from the list1 */ public static List removeElements(List list1, List list2) throws Exception { if (list1 == null) { throw new Exception("list1 is null"); } if (list2 == null) { return list1; } HashSet hs1 = new HashSet((List) list1); logger.info(" list1= " + list1.size() + " hs1 = " + hs1.size()); HashSet hs2 = new HashSet((List) list2); logger.info(" list2= " + list2.size() + " hs2 = " + hs2.size()); if (hs1 != null && hs2 != null) { if (hs1.removeAll(hs2)) { logger.info("removed the elements of list2 from list1" + hs1.size()); } else { logger.info("did not find any elements of list1 in list2" + hs1.size()); } } logger.info("hs1 = " + hs1.toString()); if (hs1 != null) { return new ArrayList(hs1); } else { return null; } } /** * getSizeType() - get size type * @param userUsedQuota - string that has the userUsedQuota * @return String - sizeType (K, M (meg),G (gig)); */ public static String getSizeType(String usedSize) throws Exception { if (!RegexStrUtil.isNull(usedSize)) { logger.info("usedSize length=" + usedSize.length()); String sizeType = null; if (usedSize.endsWith(SanConstants.kiloBytes)) { return SanConstants.kiloBytes; } else { if (usedSize.endsWith(SanConstants.megaBytes)) { return SanConstants.megaBytes; } else { if (usedSize.endsWith(SanConstants.gigaBytes)) { return SanConstants.gigaBytes; } } } } return null; } /** * checks the soft quota limits and return the warning message * @param softQuotaLimit - based on the allocated size for the user * @param usedQuota - actual used space by the user * @return String - warning message or no message */ private static String getQuotaMsg(float softQuotaLimit, String usedQuota) throws Exception { logger.info("softQuotaLimit = " + softQuotaLimit); logger.info("usedQuota = " + usedQuota); try { if (softQuotaLimit > 0 && !RegexStrUtil.isNull(usedQuota)) { String userUsedQuota = usedQuota.substring(0, usedQuota.length() - 1); logger.info("userUsedQuota=" + userUsedQuota); if ((new Float(userUsedQuota).floatValue()) > (new Float(softQuotaLimit).floatValue())) { return LdapConstants.softQuotaWarning; } } } catch (Exception e) { throw new Exception("Error in getQuotaMsg()=" + e.getMessage(), e); } return null; } /** * returns usedQuota * @param userQuotaSize - can be in M or G or K * @param fileSize - fileSize is in bytes * @return newUsedSize as string */ public static String addUserSize(String usedQuota, long fileSizeNum) throws Exception { if (RegexStrUtil.isNull(usedQuota)) { return usedQuota; } try { String usedQuotaStr = usedQuota.substring(0, usedQuota.length() - 1); logger.info("usedQuotaStr=" + usedQuotaStr); float userUsedQuota = 0; if (!RegexStrUtil.isNull(usedQuotaStr)) { userUsedQuota = new Float(usedQuotaStr).floatValue(); } else { logger.info("return usedQuota becos usedQuotaNum is null, " + usedQuota); return usedQuota; } Long fileSizeLong = new Long(fileSizeNum); String fileSize = fileSizeLong.toString(); String nSize = null; String fileSizeType = null; if (fileSize.length() >= 8 && fileSize.length() < 10) { fileSizeType = SanConstants.megaBytes; logger.info("megaBytes, fileSize.length() = " + fileSize.length()); if (fileSize.length() == 8) { nSize = fileSize.substring(0, 2); logger.info("megSize = " + nSize); } else { if (fileSize.length() == 9) { nSize = fileSize.substring(0, 3); logger.info("megSize = " + nSize); } } } else { if (fileSize.length() >= 10) { fileSizeType = SanConstants.gigaBytes; logger.info("gigaBytes() fileSize.length() = " + fileSize.length()); if (fileSize.length() > 9) { nSize = fileSize.substring(0, 3); logger.info("gigSize, substring 3 = " + nSize); } } } /** * nSize is not null */ if (!RegexStrUtil.isNull(nSize)) { float newSize = new Float(nSize).floatValue(); logger.info("newSize = " + newSize); newSize = newSize + userUsedQuota; logger.info("newSize = " + newSize); if (newSize != 0.0) { int newSizeint = new Float(newSize).intValue(); logger.info("newSizeint = " + newSizeint); /** convert float to int and to string and append the sizetype (M or G) */ if (newSizeint != 0) { String newSizeStr = new Integer(newSizeint).toString(); logger.info("newSizeStr = " + newSizeStr); logger.info("fileSizeType = " + fileSizeType); logger.info("newSizeStr = " + newSizeStr + fileSizeType); return newSizeStr + fileSizeType; } else { logger.info("returning usedQuota as newSizeint is null"); return usedQuota; } } } else { logger.info("returning usedQuota as nSize is null"); return usedQuota; } } catch (Exception e) { throw new Exception("addUserSize() error in " + e.getMessage(), e); } logger.info("usedQuota = " + usedQuota); return usedQuota; } /** * returns size Type With UsedQuota (in decimal units) * 1000 k (kilo), 1000 * 1000 (mega) 1000 * 1000 * 1000 - Giga * (bytes) 1024 ki, 1024 * 1024 (Mega) 1024 * 1024 * 1024 = Giga * @param totalSize - is in bytes * @return newUsedSize as string in M or G or K */ public static String getSizeWithType(String fileSize) throws Exception { if (RegexStrUtil.isNull(fileSize)) { return fileSize; } else { int index = fileSize.indexOf("."); if (index != -1) { logger.info("index = " + index); fileSize = fileSize.substring(0, index).trim(); } } logger.info("fileSize = " + fileSize); logger.info("fileSize.length() = " + fileSize.length()); try { double fileSizeDouble = new Double(fileSize).doubleValue(); if (fileSize.length() >= 4 && fileSize.length() < 7) { logger.info("meg, fileSize.length() = " + fileSize.length()); if (fileSizeDouble > 1024) { double newSize = (fileSizeDouble / 1024); String newFileSize = new Double(newSize).toString(); int index = newFileSize.indexOf("."); if (index != -1) { newFileSize = newFileSize.substring(0, index + 2); logger.info("newFileSize=" + newFileSize); } logger.info("meg, newFileSize = " + newFileSize); return newFileSize + SanConstants.megaBytes; } else { return fileSize + SanConstants.kiloBytes; } } else { if (fileSize.length() >= 7) { logger.info("gig() fileSize.length() = " + fileSize.length()); if (fileSizeDouble > (1024 * 1024)) { double newSize = fileSizeDouble / (1024 * 1024); String newFileSize = new Double(newSize).toString(); int index = newFileSize.indexOf("."); if (index != -1) { newFileSize = newFileSize.substring(0, index + 2); logger.info("newFileSize=" + newFileSize); } logger.info("gig, newFileSize = " + newFileSize); return newFileSize + SanConstants.gigaBytes; } } else { if (fileSize.length() < 4) { logger.info("kilo"); logger.info("kilo, fileSize = " + fileSize); return fileSize + SanConstants.kiloBytes; } } } } catch (Exception e) { throw new Exception("getSizeType() error in " + e.getMessage(), e); } return null; } /** * getLdapGroupUsers - This method gets all the users that belong to this userLogins group * @param userLogin - user Login * @param userId - user Id */ public static List getLdapGroupUsers(String userLogin, String userId, String group) throws Exception { if (RegexStrUtil.isNull(userId) || RegexStrUtil.isNull(userLogin) || RegexStrUtil.isNull(group)) { logger.info("userId and userLogin and group are null"); throw new Exception("params are null"); } LdapApi ldapConnection = new LdapApi(); if (ldapConnection == null) { logger.info("ldapConnection is null, getLdapGroupUsers()"); return null; } else { String[] attrs = { LdapConstants.ldapAttrUid }; String searchDn = null; try { searchDn = getUserSearchDn(group); } catch (Exception e) { throw new Exception("Error in getUserSearchDn() group=" + group + " exception =" + e.getMessage(), e); } if (!RegexStrUtil.isNull(searchDn)) { logger.info("searchDn = " + searchDn); /* * groupUsers - IdList */ List groupUsers = ldapConnection.getLdapUsers(searchDn, attrs); int userUidIndex = 0; if (groupUsers != null) { logger.info("groupUsers is not null, size =" + groupUsers.size()); if (groupUsers.size() >= userUidIndex) { List groupUsersUid = (List) groupUsers.get(userUidIndex); if (groupUsersUid != null) { logger.info("groupUsersUid = " + groupUsersUid.toString()); return groupUsersUid; } } else { logger.info("groupUsers.size() < userUidIndex (0), returning null"); return null; } } else { logger.info("groupUsers is null"); return null; } } } return null; } public static boolean isLdapEncryptionEnabled() { return LdapConstants.enableLdapEncryption; } }