Helper 类,帮助处理个md5加密什么的

package com.gmail.chrnc0000;

import java.util.*;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.security.MessageDigest;


public class Helper {

    /**
     * 传入一个目标日期的long 值,传一个int的偏移量,计算出偏移日期.
     */
    public static long getNewDate(long originalDate, int dayForward) {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTimeInMillis(originalDate);
        cal.set(cal.DAY_OF_MONTH, cal.get(cal.DAY_OF_MONTH) + dayForward);
        return cal.getTimeInMillis();
    }


    /**
     * 取得 sourceString 的 baseType进制的md5值 ,加密用 ,多少用户能允许明文存放密码呢?除非他不知道或者是250
     *
     */
    public static String toMD5String(String sourceString, int baseType) throws Exception {
        String arg = "MD5";
        String tmp = sourceString + "";
        MessageDigest messagedigest = MessageDigest.getInstance(arg);
        byte abyte0[] = tmp.getBytes();
        for (int i = 0; i < tmp.length(); i++) {
            messagedigest.update(abyte0, 0, i);
        }

        byte abyte1[] = messagedigest.digest();
        BigInteger biginteger = new BigInteger(abyte1);
        return biginteger.toString(baseType);
    }


    /**
     * 检查字符串是不是为空,spring util类的写发,我直接copy过来的.
     */
    public static boolean hasLength(String str) {
        return (str != null && str.length() > 0);
    }


    private static void changeFieldAccessAttri(java.lang.reflect.Field[] objs) throws Exception {
        for (int i = 0; i < objs.length; i++) {
            objs[i].setAccessible(true);
        }
    }

    public static java.lang.reflect.Field[] getAllFields(java.lang.Class clazz) throws Exception {
        ArrayList list = new ArrayList();
        getAllFields(list, clazz);

        java.lang.reflect.Field[] retValue = (java.lang.reflect.Field[]) list.toArray(new java.lang.reflect.Field[list.size()]);
        changeFieldAccessAttri(retValue);
        return retValue;
    }


    public static HashMap getAllValue(Object obj) throws Exception {
        java.lang.reflect.Field[] fields = getAllFields(obj.getClass());
        HashMap<Field, Object> map = new HashMap<Field, Object>();
        for (int i = 0; i < fields.length; i++) {
            map.put(fields[i], fields[i].get(obj));
        }
        return map;
    }

    private static void getAllFields(ArrayList<Field> list, java.lang.Class clazz) {
        java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            list.add(fields[i]);
        }

        java.lang.Class supperClass = clazz.getSuperclass();
        if (!supperClass.equals(Object.class)) {
            getAllFields(list, supperClass);
        }
    }


    /**
     * 在两个range之间取得整型随即数值.
     */
    public static int getRandomValue(int startRange, int endValue) throws Exception {
        if (startRange < 0 || endValue < 0) {
            throw new IllegalArgumentException("start range and end value both must be positive");
        }

        if (startRange > endValue) {
            throw new IllegalArgumentException("start tange must be greater equal than end value.");

        }

//        endValue += 1;

        if (startRange == endValue) {
            return endValue;
        }

        Random rand = new Random();

        int retValue = -1;

        while (retValue < startRange) {
            retValue = rand.nextInt(endValue);
        }

        return retValue;

    }

    /**
     * 在多个Object里面随即取一个出来.不知道哪里能用上.
     */
    public static Object getRandomObject(Object[] objs) throws Exception {
        if (objs != null && objs.length > 0) {
            return objs[getRandomValue(0, objs.length)];
        } else {
            return null;
        }
    }

    /**
     * 返回给定的字符串反转过来后的字符串.
     */
    public static String reverseString(String str) throws Exception {
        StringBuffer sb = new StringBuffer(str);
        return sb.reverse().toString();
    }

    /**
     * 把一个字符串数组用给定的分隔符连接起来,JavaScript 里面默认是使用","连接的,这里没有.
     */
    public static String jionStringArray(String[] strs, String separator) throws Exception {
        if (strs == null || strs.length == 0) {
            return "";
        }


        if (!hasLength(separator)) {
         separator = "";
           
        }

        StringBuffer sb = new StringBuffer();

        boolean isFirst = true;

        for (int i = 0; i < strs.length; i++) {
            if (isFirst) {
                sb.append(strs[i]);
                isFirst = false;
            } else {
                sb.append(separator).append(strs[i]);
            }
        }
        return sb.toString();
    }

    /**
     * just for fun.
     */
    public static String[] getRandomStringArray(int wordMaxLength, int sectionMaxLength) throws Exception {
        String[] source = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};

        int sectionlength = getRandomValue(0, sectionMaxLength);
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < sectionlength; i++) {
            int wordLength = getRandomValue(0, wordMaxLength);
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < wordLength; j++) {
                String tmpValue = (String) getRandomObject(source);
                sb.append(tmpValue);
            }
            list.add(sb.toString());

        }

        String[] listValues = (String[]) list.toArray(new String[list.size()]);

        return listValues;

    }
    /**
     * 把数组里面的对象顺序放到 ArrayList里面返回.这个code写的有点磕碜啦~
     * @param objs
     * @return
     * @throws Exception
     */
    public static ArrayList fillToArray(Object[] objs) throws Exception {
        ArrayList<Object> array = new ArrayList<Object>();
        if(objs == null ){
            return array;
        }
        for (int i = 0; i < objs.length; i++) {
            array.add(objs[i]);
        }
        return array;
    }
   
    /**
     * 单纯给数字排序的业务逻辑并不多,这里给出了按照属性给VO等排序的方法,如方法名所描述,fieldName对应的属性需要是Number.
     */
    public static void sortByNumberField(ArrayList list,String fieldName) throws Exception{
     java.lang.reflect.Field[] fields = getAllFields(list.get(0).getClass());
     
     java.lang.reflect.Field field = null;
     for(int i=0;i<fields.length;i++){
      if(fields[i].getName().equals(fieldName)){
       field = fields[i];
       break;
      }
     }
     
     if(field == null){
      throw new Exception("field does not exist.");
     }
     

     com.gmail.chrnc0000.Comparator comp = new com.gmail.chrnc0000.Comparator(field);
     Collections.sort(list,comp);
     
     
    }
   
    /**
     * 返回给定的object的json 格式的字符串,当前版本只对java.lang.*的属性转换.
     */
    public static String toJSONString(Object obj) throws Exception{
     
     if(obj == null){
      return null;
     }
     
     StringBuffer sb = new StringBuffer("{");
     
     java.lang.reflect.Field[] fields = getAllFields(obj.getClass());
     HashMap valueMap = getAllValue(obj);
     boolean isFirst = true;
     for(int i=0;i<fields.length;i++){
      
      Object value = valueMap.get(fields[i]);
      if(value == null ) value = "";
      String valueClassName = value.getClass().getName();
      valueClassName = valueClassName.replace("[", "");
      
      if(valueClassName.startsWith("Ljava.lang.") || valueClassName.startsWith("java.lang.")){
          String fieldName = fields[i].getName();
          if(!isFirst){
           sb.append(",");
          }
          sb.append(fieldName).append(":");
          sb.append(getLongTypeJSONString(value));
          isFirst = false;
      }

     }
     return sb.append("}").toString();
    }
   

   
    private static String getLongTypeJSONString(Object obj) throws Exception{
     boolean isNull = false;
     if(obj == null) {
      obj = "null";
      isNull = true;
     }
     
     String valueClassName = obj.getClass().getName();
     valueClassName = valueClassName.replace("[", "");
     if(valueClassName.startsWith("java.lang.")){
      if(isNull){
       return obj.toString();
      }else{
       return "'"+obj.toString()+"'";
      }
      
     }
     
     if(valueClassName.startsWith("Ljava.lang.")){
      Object[] objs = (Object[])obj;
      StringBuffer sb = new StringBuffer("[");
      boolean isFirst = true;
      for(int i=0;i<objs.length;i++){
       if(!isFirst){
        sb.append(",");
       }
       sb.append(getLongTypeJSONString(objs[i]));
       isFirst = false;
      }
      
      return sb.append("]").toString();
     }
     return null;
    }
   
   


    public static void main(String[] args){

     VO vo = new VO();
     try {
   String str = toJSONString(vo);
   System.out.println(str);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
     
     
    }
   
    /**
     * test function.
     * @param test
     * @return
     */
    public static String getTestJSONStr(String test){
     System.out.println(test);
     VO vo = new VO();
     try {
      System.out.println(toJSONString(vo));
   return toJSONString(vo);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
    }
   
   
   

}

/**
 * just for test.
 * @author Administrator
 *
 */
final class VO {
 String strs[][] = {null,{"sdf",null},{"sdf","ggds"},{"wer","saw"}};
 Hashtable table = new Hashtable();
 String name = "name";
 int age = 12;
 String sysLoginID;
 String password = "sdf";
 
}


final class Comparator implements java.util.Comparator {
 
 java.lang.reflect.Field field = null;

 public Comparator(java.lang.reflect.Field field) {
  this.field = field;
 }

 public int compare(Object arg0, Object arg1) {

  try {
   Object fieldValue0 = field.get(arg0);
   Object fieldValue1 = field.get(arg1);
   if (Double.parseDouble(fieldValue0.toString()) > Double.parseDouble(fieldValue1.toString())) {
    return 1;
   } else if (Double.parseDouble(fieldValue0.toString()) < Double.parseDouble(fieldValue1.toString())) {
    return -1;
   }

  } catch (Exception ex) {
   ex.printStackTrace();
  }

  return 0;
 }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值