动态加载2

来源:互联网 发布:淘宝摄影室内布光 编辑:程序博客网 时间:2024/05/15 23:53

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class LoaderClazz {

 private String traceFile = "";// 写出文件路径
 private int traceType = 0;// 保存码流类型
 private OutputStream outPutStream = null;// 创建全局输出流
 private Object parser = null;// 解析数据对象RespDataParser
 private Object center = null;// MonitorMgrCenter
 private Object adapter = null;// MonitorItemAdapter
 private Object monitorAdapter = null;// BasicMonitorAdapter
 private Object dataStuct = null;// MonitorDataStruct
 private Map<String, Class> classMap = new HashMap<String, Class>(5);// 存放完整class
 private Object monitorFileParser = null;// 初始化调用response.xml消息流 对象(单态)
 private boolean writeHeader = false;

 /**
  * @desc 创建文件
  * @param traceType
  *            码流类型
  * @param jarFiles
  *            动态加载jar
  * @param tracefile
  *            写文件的路径
  * @return 文件创建是否成功? 成功 true: 失败false
  */
 public boolean createTraceFile(int traceType, String[] jarFiles,
   String tracefile) {
  this.traceFile = tracefile;
  this.traceType = traceType;

  /**
   * 1.先加载动态数据 2.解析 3.创建文件
   */

  /***********************************************************************
   * @步骤分解1:动态加载jar
   * @jarFiles:jar文件(绝对路径)
   * @备注:
   *
   **********************************************************************/
  URLClassLoader loader = getLoad(jarFiles);// 返回类加载器
  for (String file : jarFiles) {
   JarFile jar = null;
   try {
    jar = new JarFile(file);
   } catch (IOException e) {
    e.printStackTrace();
   }
   Enumeration<JarEntry> entries = jar.entries();
   String name;
   while (entries.hasMoreElements()) {
    JarEntry entry = entries.nextElement();
    if (isRequireClass(entry.getName())) {

     name = entry.getName();
     System.out.println(name);
     name = name.substring(0, name.length() - 6);
     name = name.replaceAll("/", ".");
     Class<?> clazz = null;
     try {
      clazz = loader.loadClass(name);
      String className = name.substring(
        name.lastIndexOf(".") + 1, name.length());
      classMap.put(className, clazz);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   }
  }
  try {
   initRequireClass();
  } catch (Exception e1) {
   e1.printStackTrace();
  }
  /** ************************ 初始化response.xml消息流 ******************** */

  this.classParseTree();// 开始加载response.xml消息数据

  /** ************************* 创建文件 ********************************** */
  File file = new File(tracefile);
  if (!file.exists()) {
   try {
    file.createNewFile();
    writeHeader = true;
    return true;
   } catch (IOException e) {
    return false;
   }
  }
  return true;
 }

 // 初始化response.xml消息流
 private void classParseTree() {
  try {
   Method method = monitorFileParser.getClass().getMethod("parseTree",
     null);
   method.invoke(monitorFileParser, null);
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 // 加载需要的类
 @SuppressWarnings( { "rawtypes", "unchecked" })
 private boolean initRequireClass() throws InstantiationException,
   IllegalAccessException, SecurityException, NoSuchMethodException,
   IllegalArgumentException, InvocationTargetException {
  // 获取parser对象
  Class clazz = classMap.get("RespDataParser");// com.swimap.lmt.util.parse.RespDataParser
  parser = clazz.newInstance();

  // 获取center对象
  clazz = classMap.get("MonitorMgrCenter");// com.swimap.lmt.monitor.ctrl.MonitorMgrCenter
  center = clazz.newInstance();

  // 获取monitorFileParser对象
  clazz = classMap.get("MonitorFileParser");// com.swimap.lmt.util.parse.MonitorFileParser
  Method methd = clazz.getMethod("getInstance", null);
  monitorFileParser = methd.invoke(clazz, new Object[] {});

  // 获取adapter对象
  clazz = classMap.get("MonitorItemAdapter");// com.swimap.lmt.monitor.ctrl.MonitorItemAdapter
  Constructor[] con = clazz.getConstructors();
  adapter = con[0].newInstance(traceType);
  Method[] methods = clazz.getMethods();
  for (Method method : methods) {
   if (method.getName().equals("getMonitorAdapter")) {
    monitorAdapter = method
      .invoke(adapter, new Object[] { center });
   }
  }

  // 获取DataStruct对象
  Constructor[] cons = clazz.getConstructors();
  clazz = classMap.get("MonitorDataStruct");// com.swimap.lmt.util.graphics.MonitorDataStruct
  cons = clazz.getConstructors();
  // dataStuct =
  // cons[2].newInstance("dataName","xValue","yValue","rptTime",0,0,0);

  // 判断对象是否为空
  if (parser == null || center == null || adapter == null
    || monitorAdapter == null || monitorFileParser == null
    || dataStuct == null) {
   return false;
  }
  return true;

 }

 private boolean isRequireClass(String name) {
  if (name.contains("RespDataParser.class")
    || name.contains("MonitorMgrCenter.class")
    || name.contains("MonitorItemAdapter.class")
    || name.contains("MonitorFileParser.class")
    || name.contains("MonitorDataStruct.class")) {
   return true;
  }
  return false;
 }

 /**
  * description:根据一个文件(jar),返回一个ClassLoader
  *
  * @param file
  *            *.jar,绝对路径
  * @return 返回一个ClassLoader(类记载器)
  */
 public static URLClassLoader getLoad(String[] files) {
  URL[] url = new URL[files.length];
  for (int i = 0; i < files.length; i++) {
   try {
    url[i] = new URL("file:" + files[i]);
   } catch (MalformedURLException e) {
    e.printStackTrace();
   }
  }
  URLClassLoader loader = new URLClassLoader(url);// 返回类加载器
  return loader;
 }

 /**
  * 自己学习用的,获得一个类加载器。
  *
  * @param jarPath
  * @return
  */
 public static URLClassLoader getLoad(String jarPath) {
  URLClassLoader loader = null;
  try {
   URL url = new URL(jarPath);
   loader = new URLClassLoader(new URL[] { url });
  } catch (MalformedURLException e) {
   e.printStackTrace();
  }
  return loader;
 }

 /**
  * @desc 解析完将结果写入指定路径 文件路径为创建的文件路径
  * @param bin_msg
  *            码流 第三方传过来
  * @return 文件是否写成功 ? 成功 true:失败 false
  */
 public boolean writeTraceFile(byte[] bin_msg) {

  System.out.println("解析消息数据");

  try {
   initRequireClass();
  } catch (Exception e1) {
   e1.printStackTrace();
  }
  ByteBuffer byteBuffer = ByteBuffer.wrap(bin_msg);// 创建ByteBuffer缓冲区
  Object map = parserDataMessage(byteBuffer.array(), traceType);// /////////////////////////////////////////////////////////////////////////////

  Map msgMap = (Map) map;
  StringBuffer stringBuffer = new StringBuffer();
  try {
   Method buildMethod = monitorAdapter.getClass().getMethod(
     "buildDataVector", new Class[] { Map.class });
   Object objectList = buildMethod.invoke(monitorAdapter, msgMap);
   List list = (List) objectList;
   // 下面两行是写dataName,每个文件只写一次
   for (Object obj : list) {
    Method getYMethod = obj.getClass().getMethod("getYValue", null);
    Method getDataMethod = obj.getClass().getMethod("getDataName",
      null);
    Object rptTimeValue = obj.getClass().getMethod("getRptTime",
      null).invoke(obj, null);
    Object yValue = getYMethod.invoke(obj, null);
    Object dataName = getDataMethod.invoke(obj, null);
    if (writeHeader) {
     stringBuffer.append(dataName + "\n" + yValue + ","
       + rptTimeValue + "\n");
    } else {
     stringBuffer.append(yValue + "," + rptTimeValue + "\n");
    }
   }
   if (outPutStream == null) {
    outPutStream = new FileOutputStream(traceFile, true);
   }
   outPutStream.write(stringBuffer.toString().getBytes());
   outPutStream.flush();// 清除缓存
   return true;// 文件写成功
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }

 }

 /**
  *
  * @param array
  *            码流
  * @param traceType2
  *            码流类型
  * @return
  */
 private Object parserDataMessage(byte[] array, int traceType2) {
  Object result = null;
  try {
   Method method = parser.getClass().getMethod("parseDataMsg",
     new Class[] { byte[].class, int.class });
   result = method.invoke(parser, new Object[] { array, traceType2 });
  } catch (Exception e) {
   e.printStackTrace();
  }
  return result;
 }

 /**
  * @desc 写完文件 将创建的文件进行关闭
  *
  */
 public void closeTraceFile() {
  if (outPutStream != null) {
   try {
    outPutStream.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

原创粉丝点击