JFinal加载arp和route的util类

原创
08/29 18:40
阅读数 51

这是很早以前就写好的, 主要是方便加载JFinal的数据库操作activerecord和路由信息router. 意义就是增加arp和route不需要改jfinal的core-config了.

很早以前我就写过一套基于java-rapidframework的代码生成器(在jfinal提供生成器之前), 每次生成一个entity的java代码都需要改core-config加入arp和route, 实在是不优雅,  于是就写了这个工具类, 用的十分好,虽然代码写的要不是很优雅. 

后来有了springboot的fatjar模式,就加入了能从jar里面加载arp的stream模式.  因为我感觉类似这些配置都不应该包含在jar里面(应该独立于程序[个人见解]).

如今很久过去了, 代码在gitee上也很久了, 这里就粘出来吧.

// https://gitee.com/wmhx/litt-tda/blob/master/src/main/java/util/JFinalUtil.java

package util;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Model;

import java.io.*;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class JFinalUtil {

    public static Map<String, Class<? extends Controller>> getRouteMap(File dir) {
        Map<String, Class<? extends Controller>> m = new HashMap<String, Class<? extends Controller>>();

        File[] files = dir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith("route.txt");
            }
        });
        if (null == files) {
            System.err.println("can't find route by " + dir);
            return new HashMap<String, Class<? extends Controller>>();
        }
        for (File f : files) {
            Properties p = null;
            if (f.isFile()) {
                p = PropKit.use(f).getProperties();
            } else {
                p = PropKit.use(new File(dir, f.getName())).getProperties();
            }
            Object temp = null;
            for (Object s : p.keySet()) {
                try {
                    String clazz = p.getProperty(s.toString().trim());
                    temp = Class.forName(clazz.trim()).getDeclaredConstructor().newInstance();
                    if (temp instanceof Controller) {
                        Controller new_name = (Controller) temp;
                        if (m.containsKey(s.toString().trim())) {
                            System.out.println("[warnning] instance of class: [" + temp + "] had routed by " + s.toString().trim()
                                    + "->" + m.get(s.toString().trim()));
                        } else {
                            m.put(s.toString().trim(), new_name.getClass());
                            System.out.println("getRouteMap:" + s.toString().trim() + "->" + new_name.getClass());
                        }
                    } else {
                        System.err.println("Can not create instance of class: [" + temp + "] Please check the config ["
                                + dir + File.separator + f.getName() + "]");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return m;
    }

    public static Map<String, Class<? extends Model<?>>> getArpTable(InputStream stream) throws IOException {
        Map<String, Class<? extends Model<?>>> m = new HashMap<String, Class<? extends Model<?>>>();
        Properties p = new Properties();
        p.load(stream);
        for (Object s : p.keySet()) {
            Object temp = null;
            try {
                String clazz = p.getProperty(s.toString().trim());
                temp = Class.forName(clazz.trim()).getDeclaredConstructor().newInstance();
                if (temp instanceof Model<?>) {
                    Model<?> new_name = (Model<?>) temp;
                    ParameterizedType parameterizedType = (ParameterizedType) new_name.getClass()
                            .getGenericSuperclass();
                    Class<Model<?>> entityClass = (Class<Model<?>>) (parameterizedType.getActualTypeArguments()[0]);
                    if (m.containsKey(s.toString().trim())) {
                        System.out.println("[warnning] instance of table: [" + temp + "] had maped by " + s.toString().trim()
                                + "->" + m.get(s.toString().trim()));
                    } else {
                        m.put(s.toString().trim(), entityClass);
                        System.out.println("getArpTable:" + s.toString().trim() + "->" + entityClass);
                    }
                } else {
                    System.err.println("Can not create instance of class: [" + temp + "] Please check the config []");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return m;
    }

    public static Map<String, Class<? extends Model<?>>> getArpTable(File dir) throws IOException {
        Map<String, Class<? extends Model<?>>> m = new HashMap<String, Class<? extends Model<?>>>();
        File[] files = null;
        if (dir.isFile()) {
            files = new File[]{dir};
        } else {
            files = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith("arpTable.txt") || name.endsWith("arp.txt");
                }
            });
        }
        if (null == files) {
            System.err.println("can't find arp by " + dir);
            return new HashMap<String, Class<? extends Model<?>>>();
        }
        for (File f : files) {
//            Properties p = null;
            if (f.isFile()) {
//                    p = PropKit.use(f).getProperties();
                m.putAll(getArpTable(new FileInputStream(f)));
            } else {
//                p = PropKit.use(new File(dir, f.getName())).getProperties();
                m.putAll(getArpTable(new FileInputStream(new File(dir, f.getName()))));
            }
        }
        return m;
    }
}

说说用法,

1,在jfinal的core-config类中,如下加载:

package ext.jfinal;


public class DemoConfig extends JFinalConfig {

	public final static String PRIMARYKEY = "id";
	private static HashMap < String , Class < ? extends Controller >> routeMap = new HashMap < String , Class < ? extends Controller >> ( );
  private static HashMap<String , Class<? extends Model<?>>> arpTableMap = new HashMap<String , Class<? extends Model<?>>>();
  
  	/**
	 * 配置常量
	 */
  	public void configConstant ( Constants me ) {
			routeMap.putAll ( JFinalUtil.getRouteMap ( getProperty ( "route" ) ) );
			arpTableMap.putAll( JFinalUtil.getArpTable( getProperty( "arpTable" ) ) );		
  	}
  	
	/**
	 * 配置路由
	 */
	public void configRoute ( Routes me ) {
		for ( String key : routeMap.keySet ( ) ) {
			me.add ( key , routeMap.get ( key ) );
		}
	}

	/**
	 * 配置插件
	 */
	@Override
	public void configPlugin ( Plugins me ) {
	 // 配置ActiveRecord插件
	 ActiveRecordPlugin arp = new ActiveRecordPlugin( c3p0Plugin );
	 me.add( arp );
	 for ( String key : arpTableMap.keySet() ) {
	 	arp.addMapping( key , PRIMARYKEY , arpTableMap.get( key ) );
	 }	
	}
	
}

2, 在a_little_config.txt里面写:

route=route
arpTable=arpTable

3,在resources目录建立  route 和 arpTable 这2个文件夹,

route 如下:

arp如下:

=================================

这样后续用生成器的时候每次新生成的代码copy过来就可以了,不需要改core-config了. 看起来比jfinal的_mapper要顺眼一些. 

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部