alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 * $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/util/StringUtil.java,v 1.25 2005/02/05 19:00:35 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.25 $
 * $Date: 2005/02/05 19:00:35 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program 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 2
 * of the License, or any later version.
 *
 * All copyright notices regarding MyVietnam and MyVietnam CoreLib
 * MUST remain intact in the scripts and source code.
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Mai  Nguyen  mai.nh@MyVietnam.net
 */
package net.myvietnam.mvncore.util;

import net.myvietnam.mvncore.exception.BadInputException;
import java.util.*;
import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
/**
 * @todo:  add option for SHORT_STRING_LENGTH
 */
public final class StringUtil {

    private StringUtil() {//prevent instantiation
    }

    private static final int SHORT_STRING_LENGTH = 100;

    /**
     * This method trim the input variable, so if it contains only spaces,
     * then it will be empty string, then we have 0 token :-)
     * The returned value is never null. If the input String is null, an
     * empty String array will be returned
     * All tokens are trimed before returning
     */
    public static String[] getStringArray(String inputValue, String delim) {
        if (inputValue == null) inputValue = "";
        inputValue = inputValue.trim();// very important
        java.util.StringTokenizer t = new java.util.StringTokenizer(inputValue, delim);
        String[] ret = new String[t.countTokens()];
        int index = 0;
        while(t.hasMoreTokens()) {
            String token = t.nextToken().trim();
            // check for valid value here if needed
            ret[index] = token;
            index++;
        }
        return ret;
    }

    public static String[] getStringArrays(String to, String cc, String bcc, String delim) {
        String[] toMail = getStringArray(to, delim);
        String[] ccMail = getStringArray(cc, delim);
        String[] bccMail= getStringArray(bcc, delim);
        String[] ret = new String[toMail.length + ccMail.length + bccMail.length];
        int index = 0;
        for (int i = 0 ; i < toMail.length; i++) {
            ret[index] = toMail[i];
            index++;
        }
        for (int i = 0; i < ccMail.length; i++) {
            ret[index] = ccMail[i];
            index++;
        }
        for (int i = 0; i < bccMail.length; i++) {
            ret[index] = bccMail[i];
            index++;
        }
        return ret;
    }

    public static String[] getDiffStringArrays(String to, String cc, String bcc, String delim) {
        String[] toMail = getStringArray(to, delim);
        String[] ccMail = getStringArray(cc, delim);
        String[] bccMail= getStringArray(bcc, delim);
        //String[] ret = new String[t.countTokens()];
        Set set = new HashSet();
        //int index = 0;
        for (int i = 0 ; i < toMail.length; i++) {
            set.add(toMail[i]);
        }
        for (int i = 0; i < ccMail.length; i++) {
            set.add(ccMail[i]);
        }
        for (int i = 0; i < bccMail.length; i++) {
            set.add(bccMail[i]);
        }
        return (String[])set.toArray(new String[0]);
    }

    public static String getEmptyStringIfNull(String str) {
        if (str == null) return "";
        return str;
    }

    /**
     * This method accepts name with char, number or '_' or '.'
     * <p>
     * This method should be used to check all LoginName input from user for security.
     * @todo: use StringBuffer
     */
    public static void checkGoodName(String str) throws BadInputException {
        int length = str.length();
        char c = 0;

        for (int i = 0; i < length; i++) {
            c = str.charAt(i);
            if ((c >= 'a') && (c <= 'z')) {
                // lower char
            } else if ((c >= 'A') && (c <= 'Z')) {
                // upper char
            } else if ((c >= '0') && (c <= '9')/* && (i != 0)*/) {
                // minhnn: as of 31 Jan 2004, i relax the LoginName checking
                // so that the LoginName can start with an numeric char
                // hopefully it does not introduce a security bug
                // because this value will be inserted into sql script

                // numeric char
            } else if (((c == '_') || (c == '.') || (c == '@')) && (i != 0)) {
                // minhnn: as of 12 Jan 2005, i relax the LoginName checking
                // so that it can have '@' because manyone use email as a LoginName

                // _ char

            // If you need to allow non-ASCII chars, please uncomment the below "else if"
            // However, this is not recommended since there will be potential security
            //} else if (c >= 0x80) {
                // by huxn allow NON-ASCII char
            } else {
                // not good char, throw an BadInputException
                //@todo : localize me
                throw new BadInputException("The string '" + DisableHtmlTagFilter.filter(str) + "' is not a good name. Reason: character '" + c + "' is not allowed.");
            }
        }// for
    }

    /**
     * Get the shorter string, the max length is defined as SHORT_STRING_LENGTH
     * @param str String the input string
     * @return String the sorter string, with the max length = SHORT_STRING_LENGTH
     */
    public static String getShorterString(String str) {
        return getShorterString(str, SHORT_STRING_LENGTH);
    }

    /**
     * Get the shorter string, the current implementation check the
     * last occurrence of Character.isWhitespace(currentChar) as the break
     * @param str String the input string
     * @param maxLength int the max length of the shorter string
     * @return String the string after being making shorter
     */
    public static String getShorterString(String str, int maxLength) {

        if (maxLength < 0) throw new IllegalArgumentException("The maxLength < 0 is not allowed.");
        if (str == null) {
            return "";
        }
        if (str.length() <= maxLength) {
            return str;
        }
        String s = str.substring(0, maxLength);
        char currentChar;
        int index;
        for (index = s.length() - 1; index >= 0; index--) {
            currentChar = s.charAt(index);
            if (Character.isWhitespace(currentChar)) {
                break;
            }
        }
        String shortString = s.substring(0, index + 1);
        return shortString + "...";
    }

    /**
     * Get the shorter string, this is the old implementation before 4 Otc, 2004.
     * This implementation does not check the space as the break one.
     * @param str String the input string
     * @param maxLength int the max length of the shorter string
     * @return String the string after being making shorter
     */
    public static String getShorterStringIgnoreSpace(String str, int maxLength) {
        if (maxLength < 0) throw new IllegalArgumentException("The maxLength < 0 is not allowed.");
        if (str == null) return "";
        if (str.length() <= maxLength) return str;
        return str.substring(0, maxLength) + "...";
    }

    /**
     * Replace the occured char to a String
     * @param input String the input string
     * @param from char the char that is used to search
     * @param to String the string that will replace the char
     * @return String the string after being replaced
     */
    public static String replace(String input, char from, String to) {
        if (input == null) {
            return null;
        }

        char[] s = input.toCharArray();
        int length = s.length;
        StringBuffer ret = new StringBuffer(length * 2);

        for (int i = 0; i < length; i++) {
            if (s[i] == from) {
                ret.append(to);
            } else {
                ret.append(s[i]);
            }
        }// for
        return ret.toString();
    }

    /**
     * This method can be replaced by getStringArray
     */
    public static Collection getSeparateString(String strContent, String pattern) {
        int beginIndex = 0;
        Collection coResult = new ArrayList();
        String result;
        int position = strContent.indexOf(pattern, beginIndex); // Get the first position
        while (position != -1) {
            result = strContent.substring(beginIndex, position);
            if (!result.trim().equals("")) {
                coResult.add(result);
            }
            beginIndex = position + pattern.length(); //we add the length of the partern such as ';'
            position = strContent.indexOf(pattern, beginIndex);
        }

        return coResult;
    }

    /**
     * Convert a password to a hidden format, usually the asterisk character is used,
     * such as 'secret' is converted to '******'
     *
     * @param password String the input password that need to convert to hidden format
     * @return String the password after being converted to the hidden format
     */
    public static String getHiddenPassword(String password) {
        password = getEmptyStringIfNull(password);
        int length = password.length();
        if (length == 0) return password;
        StringBuffer hiddenPassword = new StringBuffer(length);
        for (int i = 0; i < length; i++) {
            hiddenPassword.append('*');
        }
        return hiddenPassword.toString();
    }

    // for test only
    public static void main(String[] args) throws Exception {
        //String[] s = getStringArray("  fasg;,   zdgsag, ,,", ",");
//        String[] s = getStringArray("  fasg  ", ",");
//        System.out.println("length = " + s.length);
//        for (int i = 0; i < s.length; i++) {
//            System.out.println("" + i + " : " + s[i]);
//        }

        String s1 = "   abc das\n\n\n\n\ndasd    asd   adad   as   das   as   da    adas        da     sd    ad  as  sa  das  das   d a            .";
        System.out.println("r = [" + StringUtil.getShorterString(s1, 22) + "]");
    }

}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.