从0开始写JavaWeb框架系列(8)从0开始写SamrtFrameWork:项目使用的工具类一览

一、ArrayUtil

package org.smart4j.framework.util;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtil {

	/**
	 * 判断数组是否非空
	 * @param array
	 * @return
	 */
	public static boolean isNotEmpty(Object[] array){
		return !ArrayUtils.isEmpty(array);
	}
	
	/**
	 * 判断数组是否为空
	 * @param array
	 * @return
	 */
	public static boolean isEmpty(Object[] array){
		return ArrayUtils.isEmpty(array);
	}
	
}

二、CastUtil

package org.smart4j.framework.util;

/**
 * 转型操作工具类
 *
 * @author huangyong
 * @since 1.0.0
 */
public final class CastUtil {

    /**
     * 转为 String 型
     */
    public static String castString(Object obj) {
        return CastUtil.castString(obj, "");
    }

    /**
     * 转为 String 型(提供默认值)
     */
    public static String castString(Object obj, String defaultValue) {
        return obj != null ? String.valueOf(obj) : defaultValue;
    }

    /**
     * 转为 double 型
     */
    public static double castDouble(Object obj) {
        return CastUtil.castDouble(obj, 0);
    }

    /**
     * 转为 double 型(提供默认值)
     */
    public static double castDouble(Object obj, double defaultValue) {
        double doubleValue = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    doubleValue = Double.parseDouble(strValue);
                } catch (NumberFormatException e) {
                    doubleValue = defaultValue;
                }
            }
        }
        return doubleValue;
    }

    /**
     * 转为 long 型
     */
    public static long castLong(Object obj) {
        return CastUtil.castLong(obj, 0);
    }

    /**
     * 转为 long 型(提供默认值)
     */
    public static long castLong(Object obj, long defaultValue) {
        long longValue = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    longValue = Long.parseLong(strValue);
                } catch (NumberFormatException e) {
                    longValue = defaultValue;
                }
            }
        }
        return longValue;
    }

    /**
     * 转为 int 型
     */
    public static int castInt(Object obj) {
        return CastUtil.castInt(obj, 0);
    }

    /**
     * 转为 int 型(提供默认值)
     */
    public static int castInt(Object obj, int defaultValue) {
        int intValue = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    intValue = Integer.parseInt(strValue);
                } catch (NumberFormatException e) {
                    intValue = defaultValue;
                }
            }
        }
        return intValue;
    }

    /**
     * 转为 boolean 型
     */
    public static boolean castBoolean(Object obj) {
        return CastUtil.castBoolean(obj, false);
    }

    /**
     * 转为 boolean 型(提供默认值)
     */
    public static boolean castBoolean(Object obj, boolean defaultValue) {
        boolean booleanValue = defaultValue;
        if (obj != null) {
            booleanValue = Boolean.parseBoolean(castString(obj));
        }
        return booleanValue;
    }
}

三、ClassUtil

package org.smart4j.framework.util;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.helper.ConfigHelper;


/**
 * 类操作工具类
 * @author TS
 *
 */
public final class ClassUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class);

	/**
	 * 获取当前线程中的类加载器
	 * @return ClassLoader对象
	 */
	public static ClassLoader getClassLoader(){
		return Thread.currentThread().getContextClassLoader();
	}

	/**
	 * 加载类
	 * @param className 类的全限定名
	 * @param isInitialied 是否初始化的标志(是否执行类的静态代码块)TODO
	 * @return
	 */
	public static Class<?> loadClass(String className,boolean isInitialied){
		Class<?> cls;
		try {
			cls = Class.forName(className, isInitialied, getClassLoader());
		} catch (ClassNotFoundException e) {
			LOGGER.error("加载类初始化错误");
			throw new RuntimeException(e);
		}
		return cls;
	}
	
	/**
	 * 加载类
	 * @param className 类的全限定名
	 * @return
	 */
	public static Class<?> loadClass(String className){
		Class<?> cls;
		try {
			cls = Class.forName(className);
		} catch (ClassNotFoundException e) {
			LOGGER.error("加载类初始化错误");
			throw new RuntimeException(e);
		}
		return cls;
	}

	/**
	 * 获取指定包名下的所有类
	 * @param packageName 包名
	 * @return Set<Class>
	 * 1.根据包名将其转换为文件路径
	 * 2读取class或者jar包,获取指定的类名去加载类
	 */
	public static Set<Class<?>> getClassSet(String packageName){
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		try {

			Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
			

			if( urls.hasMoreElements() ){

				URL url = urls.nextElement();

				if(url != null ){
					
					String protocol =	url.getProtocol();		//协议名称
					if( protocol.equals("file") ){
							
						String packagePath = url.getPath().replace("%20", " ");
						//加载类
						addClass(classSet,packagePath,packageName);
					}else if( protocol.equals("jar") ){

						JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();

						if( jarURLConnection != null ){

							JarFile jarFile = jarURLConnection.getJarFile();

							if( jarFile != null ){

								Enumeration<JarEntry> jarEntries = jarFile.entries();

								while ( jarEntries.hasMoreElements() ) {
									JarEntry jarEntry = jarEntries.nextElement();
									String jarEntryName = jarEntry.getName();
									if( jarEntryName.endsWith(".class") ){

										String className = jarEntryName.substring(0,jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
										doAddClass(classSet,className);
									}
								}
							}
						}
					}
				}

			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		return classSet;
	}

	private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {

		File[] files = new File(packagePath).listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {
				return ( file.isFile() && file.getName().endsWith(".class") ) || file.isDirectory(); 
			}
		});

		for (File file : files) {

			String fileName = file.getName();
			System.out.println(fileName);

			if( file.isFile() ){

				String className = fileName.substring( 0,fileName.lastIndexOf(".") );

				if( StringUtils.isNotEmpty(packageName) ){
					className = packageName + "." + className;
				}
				doAddClass(classSet, className);

			} else {
				
				String subPackagePath = fileName;
				if( StringUtils.isNotEmpty(packagePath) ){
					subPackagePath = packagePath + "/" + subPackagePath;
				}
				String subPackageName = fileName;
				if(  StringUtils.isNotEmpty(subPackageName)  ){
					subPackageName = packageName + "." + subPackageName;
				}
				addClass(classSet, subPackagePath, subPackageName);
			
			}
		}

	}

	private static void doAddClass(Set<Class<?>> classSet, String className) {
		Class<?> cls = loadClass(className, false);
		classSet.add(cls);
	}

	public static void main(String[] args) {
		ClassUtil.getClassSet(ConfigHelper.getAppBasePackage());
	}
}

四、CodecUtil

package org.smart4j.framework.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 编码与解码操作工具类
 * @author TS
 *
 */
public class CodecUtil {

	/**
	 * 将URL编码
	 * @param source
	 * @return
	 */
	public static String encodeURL(String source){
		String target = null;
		try {
			target = URLEncoder.encode(source, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return target;
	}
	
	/**
	 * 将URL解码
	 * @param source
	 * @return
	 */
	public static String decodeURL(String source){
		String target = null;
		try {
			target = URLDecoder.decode(source, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return target;
	}
}

五、JsonUtil

package org.smart4j.framework.util;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 用于处理JSON与POJO之间的转换,基于Jackson实现
 * @author TS
 *
 */
public class JsonUtil {

	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
	
	/**
	 * 将POJO转化为JSON
	 * @param obj
	 * @return
	 */
	public static <T> String toJson(T obj){
		String json;
		try{
			json = OBJECT_MAPPER.writeValueAsString(obj);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		 
		 return json;
	}
	
	/**
	 * 将json转为pojo
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> T fromJson(String json,Class<T> type){
		T pojo;
		try{
			pojo = OBJECT_MAPPER.readValue(json, type);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		 
		return pojo;
	}
}

六、PropsUtil

package org.smart4j.framework.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Properties文件读取工具类
 * @author Admin
 *
 */
public class PropsUtil {

	/**
	 * 加载properties配置文件工具类
	 * @param fileConfig
	 * @return
	 */
	public static Properties loadProps(String fileConfig){
		Properties properties = new Properties();
		try {
			InputStream in = Object.class.getResourceAsStream("/" + fileConfig);
			properties.load(in);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return properties;
	}

	/**
	 * 根据传入的properties文件对象的key获得value
	 * @param properties
	 * @param key
	 * @return value
	 */
	public static String getString(Properties properties,String key){
		String value = properties.getProperty(key);
		return value;
	}

	/**
	 *  根据传入的properties文件对象的key获得value,提供可选的路径配置项pathCustom
	 * @param properties
	 * @param key
	 * @param pathCustom 自定义配置项,传入null默认加载配置文件key
	 * @return value
	 */
	public static String getString(Properties properties,String key,String pathCustom){
		if( pathCustom != null ){
			return pathCustom;
		}else{
			String value = properties.getProperty(key);
			return value;
		}
	}

}

七、ReflectionUtil

package org.smart4j.framework.util;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 反射工具类 
 * @author Admin
 *
 */
public final class ReflectionUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);

	/**
	 * 创建实例
	 * @param cls
	 * @return
	 */
	public static Object getInstance(Class<?> cls){
		Object instance;
		try {
			instance = cls.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			LOGGER.error("new instance failure",e);
			throw new RuntimeException(e);
		}
		return instance;
	}

	/**
	 * 调用方法
	 * @param obj
	 * @param method
	 * @param args
	 * @return
	 */
	public static Object invokeMethod(Object obj,Method method,Object ...args){
		Object result;
		try {
			method.setAccessible(true);
			result = method.invoke(obj, args);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			LOGGER.error("invoke method failure",e);
			throw new RuntimeException(e);
		}

		return result;

	}


	/**
	 * 设置成员变量的值
	 * @param obj
	 * @param field
	 * @param value
	 */
	public static void setField(Object obj,Field field,Object value){
		field.setAccessible(true);
		try {
			field.set(obj, value);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			LOGGER.error("set field failure",e);
			throw new RuntimeException(e);
		}
	}


}

八、StreamUtil

package org.smart4j.framework.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 流操作工具类
 * @author TS
 *
 */
public class StreamUtil {

	/**
	 * 获取流操作工具类
	 * @param in:输入流
	 * @return
	 */
	public static String getString(InputStream is){
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String line;
			while( (line = reader.readLine()) != null ){
				sb.append(line);
			}
		} catch (IOException e) {

			e.printStackTrace();
		}

		return sb.toString();
	}
}

九、StringUtil

package org.smart4j.framework.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

/**
 * 字符串工具类
 *
 * @author huangyong
 * @since 1.0.0
 */
public final class StringUtil {

    /**
     * 判断字符串是否为空
     */
    public static boolean isEmpty(String str) {
        if (str != null) {
            str = str.trim();
        }
        return StringUtils.isEmpty(str);
    }

    /**
     * 判断字符串是否非空
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 判断字符串是否为数字
     */
    public static boolean isNumeric(String str) {
        return NumberUtils.isDigits(str);
    }

    /**
     * 正向查找指定字符串
     */
    public static int indexOf(String str, String searchStr, boolean ignoreCase) {
        if (ignoreCase) {
            return StringUtils.indexOfIgnoreCase(str, searchStr);
        } else {
            return str.indexOf(searchStr);
        }
    }

    /**
     * 反向查找指定字符串
     */
    public static int lastIndexOf(String str, String searchStr, boolean ignoreCase) {
        if (ignoreCase) {
            return StringUtils.lastIndexOfIgnoreCase(str, searchStr);
        } else {
            return str.lastIndexOf(searchStr);
        }
    }

    /**
     * 截取字符串
     * @param body
     * @param string
     * @return
     */
	public static String[] splitString(String body, String regex) {
		
		return body.split(regex);
	}
    
    
   
}

 

转载于:https://my.oschina.net/tianshuo/blog/682273

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 《架构探险 从零开始JavaWeb框架》这本书是一本关于如何从零开始构建JavaWeb框架的实践指南。这本书详细介绍了构建JavaWeb框架的基本原理、核心功能以及框架设计的各个方面。下面我将简要回答这个问题。 在这本书中,作者首先介绍了JavaWeb框架的基本概念和开发背景,以及为什么需要自己去构建一个JavaWeb框架。接着,作者分析了现有的开源JavaWeb框架的优缺点,并提出了自己的设计思路。 在框架的设计方面,作者使用了简单、灵活、易扩展的原则。他详细解释了框架的各个组件的功能和交互方式,比如控制器、模型、视图和数据层等。除此之外,作者还介绍了如何实现框架的依赖注入和AOP等功能,以及如何处理请求和响应等核心功能。 在框架的实现过程中,作者采用了优秀的开源框架作为基础,例如使用Servlet作为底层容器,使用Freemarker作为模板引擎,使用MySQL作为数据库等。通过实际的代码示例和详细的解释,读者可以更好地理解每个组件的功能和实现方式。 总的来说,《架构探险 从零开始JavaWeb框架》这本书通过将复杂的JavaWeb框架的设计和实现分解成简单的组件和步骤,帮助读者理解并掌握JavaWeb框架的构建过程。通过学习这本书,读者可以了解到一个完整的JavaWeb框架所需的各个组件和功能,并能够根据自己的需求进行定制和扩展。无论是对于初学者还是有一定经验的开发人员而言,这本书都是一本难得的实践指南。 ### 回答2: 《架构探险:从零开始JavaWeb框架》是一本非常实用的书籍,主要介绍了如何从零开始开发一个完整的JavaWeb框架。这本书的作者对于JavaWeb开发有着丰富的经验,通过本书的学习,读者可以掌握开发框架所需的各种核心知识和技术。 在书中,作者首先介绍了JavaWeb框架的概念和作用,以及为什么要从零开始开发一个框架。接着,作者详细讲解了框架的基本原则和设计思路,包括MVC模式、依赖注入、AOP等核心概念和技术。作者通过清晰的代码示例和实际案例,展示了如何使用这些技术来搭建一个可靠、高效的框架。 随后,作者开始逐步实现一个简单的JavaWeb框架。他从处理HTTP请求开始,依次实现了路由解析、参数绑定、控制器调用、视图渲染等功能。在实现的过程中,作者注重详细讲解每个步骤的实现原理和技术细节,读者可以通过跟随书中的示例代码进行实践和理解。 除了核心功能的实现,作者还介绍了一些框架的扩展功能,如连接池、事务管理、日志记录等。这些扩展功能可以使框架更加完善和灵活,提供更好的开发体验和性能优化。 总而言之,此书通过一个完整的JavaWeb框架实例,全面而系统地介绍了框架的设计与实现。读者通过学习本书,不仅可以掌握JavaWeb开发的核心知识和技术,还可以提升自己的架构设计能力和编码水平。无论是初学者还是有一定经验的开发者,都能从中受益匪浅。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值