util.RegexStrUtil.java Source code

Java tutorial

Introduction

Here is the source code for util.RegexStrUtil.java

Source

/**
* 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 java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import model.Blog;
import model.Directory;
import model.Mykeywords;
import model.Yourkeywords;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Smitha Gudur (smitha@redbasin.com)
 * @version $Revision: 1.1 $
 */
public class RegexStrUtil {

    /** Logger for this class and subclasses */
    protected static final Log logger = LogFactory.getLog("util.CookieUtil");

    /**
    * 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 boolean isNull(String str) {
        return ((str == null) || str.trim().equals(""));
    }

    /**
     * Converts a user entered string in text area of gui to a format that
     * is liked by sql.
     *
     * @param str the string to replace
     * @return String
     */
    public static String goodStr(String str) {
        if (!RegexStrUtil.isNull(str)) {
            return str.replaceAll("'", "&rsquo;").replaceAll("\"", "&quot;");
        }
        return str;
    }

    /**
     * Converts a user entered string in text area of gui to a format that
     * is liked by web.
     *
     * @param str the string to replace
     * @return String
     */
    public static String goodWebStr(String str) {
        if (RegexStrUtil.isNull(str)) {
            return str;
        }
        /** 
         * check if this str contains html tags. Leave them intact.
         */
        str = str.replaceAll("&apos;", "'").replaceAll("&quot;", "\"");

        if (hasHTML(str)) {
            return str;
        }
        if (str.indexOf("<") == -1) {
            return str.replaceAll("\r\n", "<br>").replaceAll("\n", "<br>");
        }
        return str;
    }

    static boolean hasHTML(String body) {
        if (!RegexStrUtil.isNull(body)) {
            Pattern pattern = Pattern.compile("<.*?>", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(body);
            return matcher.find();
        }
        return false;
    }

    public static String goodDirPath(String str) {
        if (!RegexStrUtil.isNull(str)) {
            return str.replaceAll("\\|([0-9])++", "");
        }
        return str;
    }

    /**
     * For name of person, collabrum, pblog topic, etc.
     *  directoryid, collabrumid, entryid, name, city, phone, zipcode
     * 
     * @param str
     * @return String
     **/
    public static String goodNameStr(String str) {
        if (!RegexStrUtil.isNull(str)) {
            return str.replaceAll("[^(\\w|\\s)]", "").replaceAll("\\(||\\)", "").replaceAll("\\s{2,}", " ");
        }
        return str;
    }

    /**
     * For name of directory allows most punctuation and mathematical symbols for expert system use cases.
     * 
     * @param str
     * @return String
     **/
    public static String goodDirName(String str) {
        return str.replaceAll(
                "[^(\\w|\\s|\\-|_|\\.|\\&|\\?|\\+|\\=|\\%|\\$|\\#|\\@|\\/|\\[|\\]|\\{|\\}|\\<|\\>|\\*)]", "")
                .replaceAll("\\s{2,}", " ");
    }

    /**
     * For login (@,. are allowed) for email users john@xyz.com
     * @param str
     * @return String
     */
    public static String goodId(String str) {
        if (!RegexStrUtil.isNull(str)) {
            return str.replaceAll("[^(@a-zA-Z_0-9.\\-)]", "").replaceAll("\\(||\\)||\\s", "")
                    .replaceAll("\\-{2,}", "-").replaceAll("_{2,}", "_");
        }
        return str;
    }

    /**
     * For password
     * @param str
     * @return String
     **/
    public static String goodPassword(String str) {
        if (!RegexStrUtil.isNull(str)) {
            return str.replaceAll("[^(a-zA-Z_0-9\\-)]", "").replaceAll("\\(||\\)||\\s", "")
                    .replaceAll("\\-{2,}", "-").replaceAll("_{2,}", "_");
        }
        return str;
    }

    /**
     * A bit demented method that cleans strings for text fields.
     * Good for description and other text fields.
     * used for street, url related fields
     *
     * @param str
     * @return String
     */
    public static String goodText(String str) {
        if (!RegexStrUtil.isNull(str)) {
            return goodStr(str.replaceAll(
                    "[^\\w&&^\\(&&^\\.&&^!&&^\\\"&&^#&&^\\$&&^\\&&&^\\'&&^\\(&&^\\)&&^*&&^+&&^,&&^\\-&&^+/&&^:&&^\\s&&^;&&^<&&^=&&^>&&^?&&^@&&^\\[&&^\\]&&^\\^&&^`&&^\\{&&^\\|&&^\\}&&^~&&^%]",
                    ""));
        }
        return str;
    }

    /*
        public static String goodText(String str) {
           if (!RegexStrUtil.isNull(str)) {   
       return goodStr(str.replaceAll("[^\\w&&^\\(&&^\\.&&^!&&^\\\"&&^#&&^\\$&&^\\&&&^\\'&&^\\(&&^\\)&&^*&&^+&&^,&&^\\-&&^/&&^:&&^\\s&&^;&&^<&&^=&&^>&&^?&&^@&&^\\[&&^\\\\&&^\\]&&^\\^&&^`&&^\\{&&^\\|&&^\\}&&^~&&^%]", ""));
           }
           return str;
       }
    */

    /**
     * Is this a valid email.
     *
     * @param email
     * @boolean String
     */
    public static boolean isValidEmail(String email) {
        if (isNull(email))
            return false;
        StringTokenizer st = new StringTokenizer(email, "@");
        if (st.hasMoreTokens()) {
            if (isNull(st.nextToken()))
                return false;
            if (st.hasMoreTokens()) {
                String host = st.nextToken();
                if (isNull(host))
                    return false;
                StringTokenizer st1 = new StringTokenizer(host, ".");
                if (st1.hasMoreTokens()) {
                    if (isNull(st1.nextToken()))
                        return false;
                    if (st1.hasMoreTokens()) {
                        if (isNull(st1.nextToken()))
                            return false;
                        else
                            return true;
                    } else
                        return false;
                } else
                    return false;
            }
            return false;
        } else
            return false;
    }

    /**
     * complies with internet draft standard
     */
    public static String goodCSV(String str) {

        if (RegexStrUtil.isNull(str)) {
            return str;
        }

        boolean strMatches = false;
        if (str.indexOf(",") != -1) {
            strMatches = true;
        } else {
            //if (str.indexOf("\r\n") != -1) {
            if (str.indexOf("\n") != -1) {
                strMatches = true;
            }
        }

        if (str.startsWith("\"") && str.endsWith("\"")) {
            int ind = str.indexOf("\"");
            if (ind != -1) {
                return (str.substring(0, ind) + "\"" + str.substring(ind, str.length()));
            }
        } else {
            if (strMatches) {
                return ("\"" + str + "\"");
            }
        }
        return str;
    }

    /**
      * This method generates a list of words based on the string
      * @param expression The tag array for strip exclusion
      * @return List returns the words
      */
    public static List getWords(String expression) {
        if (RegexStrUtil.isNull(expression)) {
            return null;
        }
        String modexpr = expression.replaceAll("[[\\W]&&[\\S]]", "");
        StringBuffer constraint = new StringBuffer();
        List keywords = new ArrayList();
        StringTokenizer st = new StringTokenizer(modexpr, " ");
        if (keywords != null) {
            while (st.hasMoreTokens()) {
                keywords.add(st.nextToken());
            }
        }
        return keywords;
    }

    public static List getTagListAsStringList(List myKeywords) {
        if (myKeywords == null) {
            return null;
        }
        List keyList = new ArrayList();
        if (keyList != null) {
            Iterator iterator = myKeywords.iterator();
            while (iterator.hasNext()) {
                Yourkeywords keyword = (Yourkeywords) iterator.next();
                if (keyword != null) {
                    keyList.add(keyword.getValue(DbConstants.TAG));
                }
            }
            return keyList;
        }
        return null;
    }

    /**
      * This method generates a string of words based on the HashSet
      * @param expression The tag array for strip exclusion
      * @return String returns the words
      */
    public static String getKeywordsAsString(HashSet myKeywords) {
        if (myKeywords == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        if (sb != null) {
            Iterator iterator = myKeywords.iterator();
            while (iterator.hasNext()) {
                Mykeywords keyword = (Mykeywords) iterator.next();
                if (keyword != null) {
                    sb.append(keyword.getValue(DbConstants.KEYWORD));
                    sb.append(" ");
                }
            }
            return sb.toString();
        }
        return null;
    }

    /**
      * This method generates a string of words based on the HashSet
      * @param expression The tag array for strip exclusion
      * @return String returns the words
      */
    public static String getUsertagsAsString(HashSet myKeywords) {
        if (myKeywords == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        if (sb != null) {
            Iterator iterator = myKeywords.iterator();
            while (iterator.hasNext()) {
                Blog blog = (Blog) iterator.next();
                if (blog != null) {
                    sb.append(blog.getValue(DbConstants.USER_TAGS));
                    sb.append(" ");
                }
            }
            return sb.toString();
        }
        return null;
    }

    public static String getTagListAsString(List myKeywords) {
        if (myKeywords == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        if (sb != null) {
            Iterator iterator = myKeywords.iterator();
            while (iterator.hasNext()) {
                Yourkeywords keyword = (Yourkeywords) iterator.next();
                if (keyword != null) {
                    sb.append(keyword.getValue(DbConstants.TAG));
                    sb.append(" ");
                }
            }
            return sb.toString();
        }
        return null;
    }

    public static String ajaxUtilStr(String str) {
        if (!isNull(str)) {
            return str.replaceAll("&apos;", "'").replaceAll("&quot;", "\"");
        }
        return str;
    }

    public static String getDirKeysAsString(List dirs) {
        if (dirs == null) {
            return null;
        }

        if (dirs.size() > 0) {
            StringBuffer sb = new StringBuffer();
            if (sb != null) {
                for (int i = 0; i < dirs.size(); i++) {
                    Directory dir = (Directory) dirs.get(i);
                    if (dir != null) {
                        sb.append(dir.getValue(DbConstants.KEYWORDS));
                        sb.append(" ");
                    }
                }
                return sb.toString();
            }
        }
        return null;
    }

    /**
      * This method generates a list of words based on the string token
      * @param expression The tag array for strip exclusion
      * @return List returns the words
     */
    public static List getWordsOnTokenWeb(String expression, String token) {
        if (RegexStrUtil.isNull(expression)) {
            return null;
        }
        // expression = expression.replaceAll("[[\\W]&&[\\S]]", "");
        String[] users = expression.split(token);
        List keywords = new ArrayList();
        if (keywords != null && users != null && users.length > 0) {
            for (int i = 0; i < users.length; i++) {
                if (!RegexStrUtil.isNull(users[i])) {
                    //users[i] = users[i].replaceAll(" ", "");
                    keywords.add(goodNameStr(users[i]));
                    //logger.info("users[i]=" + users[i]);
                }
            }
        }
        //logger.info("keywords = " + keywords.size());
        return keywords;
    }

    /**
      * This method generates a list of words based on the string token
      * @param expression The tag array for strip exclusion
      * @return List returns the words
     */
    public static List getWordsOnToken(String expression, String token) {
        if (RegexStrUtil.isNull(expression)) {
            return null;
        }
        // expression = expression.replaceAll("[[\\W]&&[\\S]]", "");
        String[] users = expression.split(token);
        List keywords = new ArrayList();
        if (keywords != null && users != null && users.length > 0) {
            for (int i = 0; i < users.length; i++) {
                if (!RegexStrUtil.isNull(users[i])) {
                    users[i] = users[i].replaceAll(" ", "");
                    //keywords.add(goodNameStr(users[i]));
                    keywords.add(goodId(users[i]));
                    //logger.info("users[i]=" + users[i]);
                }
            }
        }
        //logger.info("keywords = " + keywords.size());
        return keywords;
    }

    /**
     * parseldap cn: smitha
     */
    public static String parseLdapStr(String str, String attr) {

        if (RegexStrUtil.isNull(str)) {
            return str;
        }

        boolean strMatches = false;
        StringBuffer sb = new StringBuffer(attr);

        if (sb != null) {
            sb.append(":");
        } else {
            return null;
        }

        logger.info("sb = " + sb.toString());

        int begin = -1;
        int endInd = -1;
        if ((begin = str.indexOf(sb.toString())) != -1) {
            logger.info("attr matches " + attr + "  " + begin);
            begin += sb.toString().length();
            logger.info(" lastindex = " + str.lastIndexOf(sb.toString()));
            if (((endInd = str.indexOf("\n", begin)) != 1) || ((endInd = str.indexOf("\r\n", begin)) != 1)) {
                logger.info("begin = " + begin + " end = " + endInd);
                if ((begin != -1) && begin <= str.length()) {
                    if (endInd <= str.length()) {
                        logger.info("str = " + str.substring(begin, endInd).trim());
                        return str.substring(begin, endInd).trim();
                    }
                }
            }
        } else {
            return null;
        }
        return null;
    }

    /**
     * sanFilePath - used for files
     * @param - filePath - file path with |:: (rbformat)
     * @param - dirName - dirName (where the files will be located)
     * @return - filepath with appropriate separator path
     */
    public static String sanFilePath(String filePath, String dirName) {

        if (RegexStrUtil.isNull(filePath)) {
            return goodDirName(dirName);
        } else {

            String goodFilePath = goodDirPath(filePath);
            if (!RegexStrUtil.isNull(goodFilePath)) {
                logger.info("goodDirPath() goodFilePath=" + goodFilePath);
                goodFilePath = goodFilePath.replaceAll("::", File.separator);
            } else {
                return null;
            }
            logger.info("replaceAll() goodFilePath=" + goodFilePath);
            if (RegexStrUtil.isNull(goodFilePath)) {
                return null;
            }
            StringBuffer sb = new StringBuffer(goodFilePath);
            if (sb == null) {
                return null;
            }

            sb.append(File.separator);
            if (!RegexStrUtil.isNull(dirName)) {
                sb.append(dirName);
            }
            logger.info("sanFilePath=" + sb.toString());
            return goodDirName(sb.toString());
        }
    }

    /**
     * sanFilePath - this function is used for directories
     * @param - filePath - file path with |:: (rbformat)
     * @param - dirPath - dirPath
     * @param - dirName - dirName (directory to be created/deleted/moved)
     * @return - filepath with appropriate separator path
     */
    public static String sanFilePath(String filePath, String dirPath, String dirName) {

        if (RegexStrUtil.isNull(filePath) && RegexStrUtil.isNull(dirPath)) {
            return goodDirName(dirName);
        } else {
            StringBuffer sb = new StringBuffer();
            if (sb == null) {
                return null;
            }

            logger.info("dirPath = " + dirPath + " filePath = " + filePath + " dirName = " + dirName);

            if (!RegexStrUtil.isNull(dirPath)) {
                sb.append(goodDirName(dirPath));
                logger.info("dirPath appended " + sb.toString());
            } else {
                logger.info("dirPath is not appended as it is null ");
            }

            if (!RegexStrUtil.isNull(filePath)) {
                // sb.append(goodDirPath(filePath).replaceAll("::", ""\"));
                sb.append(goodDirPath(filePath).replaceAll("::", File.separator));
                sb.append(File.separator);
                logger.info("filePath appended " + sb.toString());
            }

            logger.info("filePath appended " + sb.toString());

            if (!RegexStrUtil.isNull(dirName)) {
                sb.append(goodDirName(dirName));
                logger.info("dirName appended " + sb.toString());
            }

            logger.info("sanFilePath full dirName included=" + sb.toString());
            return goodDirName(sb.toString());
        }
    }

    /**
     * For quotasize
     * @param str
     * @return String
     */
    public static String goodNum(String str) {
        if (!RegexStrUtil.isNull(str)) {
            return str.replaceAll("[^(0-9)]", "").replaceAll("\\(||\\)||\\s", "").replaceAll("\\-{2,}", "-")
                    .replaceAll("_{2,}", "_");
        }
        return str;
    }

    public static String replaceString(String dirPath, String oldPattern, String newPattern) {
        if (!RegexStrUtil.isNull(dirPath)) {
            return dirPath.replaceAll(oldPattern, newPattern);
        }
        return dirPath;
    }

    public static String goodN(String str) {
        return str.replaceAll("[^(@a-zA-Z_0-9.\\-')]", "").replaceAll("\\(||\\)||\\s", "")
                .replaceAll("\\-{2,}", "-").replaceAll("_{2,}", "_");
    }

}