summaryrefslogtreecommitdiff
path: root/src/com/nis/nmsclient/util
diff options
context:
space:
mode:
Diffstat (limited to 'src/com/nis/nmsclient/util')
-rw-r--r--src/com/nis/nmsclient/util/CompressFileMgr.java135
-rw-r--r--src/com/nis/nmsclient/util/DESUtil.java83
-rw-r--r--src/com/nis/nmsclient/util/DateUtil.java142
-rw-r--r--src/com/nis/nmsclient/util/FileUtil.java477
-rw-r--r--src/com/nis/nmsclient/util/FileWrUtil.java285
-rw-r--r--src/com/nis/nmsclient/util/GzipUtil.java680
-rw-r--r--src/com/nis/nmsclient/util/MD5Util.java99
-rw-r--r--src/com/nis/nmsclient/util/ProcessUtil.java1341
-rw-r--r--src/com/nis/nmsclient/util/RarUtil.java125
-rw-r--r--src/com/nis/nmsclient/util/StringUtil.java528
-rw-r--r--src/com/nis/nmsclient/util/Utils.java323
-rw-r--r--src/com/nis/nmsclient/util/ZipUtil.java321
-rw-r--r--src/com/nis/nmsclient/util/file/BufferedRandomAccessFile.java313
-rw-r--r--src/com/nis/nmsclient/util/file/Res.java17
-rw-r--r--src/com/nis/nmsclient/util/io/UnicodeInputStream.java118
-rw-r--r--src/com/nis/nmsclient/util/io/UnicodeReader.java120
-rw-r--r--src/com/nis/nmsclient/util/log4j/MyDailyRollingFileAppender.java14
-rw-r--r--src/com/nis/nmsclient/util/log4j/MyRollingFileAppender.java14
18 files changed, 5135 insertions, 0 deletions
diff --git a/src/com/nis/nmsclient/util/CompressFileMgr.java b/src/com/nis/nmsclient/util/CompressFileMgr.java
new file mode 100644
index 0000000..3be2549
--- /dev/null
+++ b/src/com/nis/nmsclient/util/CompressFileMgr.java
@@ -0,0 +1,135 @@
+package com.nis.nmsclient.util;
+
+import java.io.File;
+
+import org.apache.log4j.Logger;
+
+import com.nis.nmsclient.util.GzipUtil;
+import com.nis.nmsclient.util.RarUtil;
+import com.nis.nmsclient.util.ZipUtil;
+
+/**
+ * 文件解压缩的统一处理
+ * @date Mar 20, 2012
+ * @version
+ */
+public class CompressFileMgr {
+ static Logger logger = Logger.getLogger(CompressFileMgr.class);
+
+ /**
+ * 文件压缩
+ * @param sourcePath 源文件或目录
+ * @param destFile 压缩后的文件
+ * @param excludes 源目录中不要压缩的文件列表
+ * @param isAbs 相对路径还是绝对路径压缩
+ * @return
+ * @throws Exception
+ */
+ public boolean compressFile(String sourcePath, String destFile,
+ String[] excludes, boolean isAbs) throws Exception {
+ boolean returnFlag = true;
+ File folder = new File(sourcePath);
+ if (!folder.exists()) {
+ return false;
+ }
+ if (destFile.length() == (destFile.lastIndexOf(".zip") + 4)) {// 判断是否zip包
+ ZipUtil.zip(sourcePath, destFile, excludes);
+ } else if (destFile.length() == (destFile.lastIndexOf(".gz") + 3)) {// 判断是否gzip包
+ GzipUtil.gzipByCmd(sourcePath, destFile, excludes, isAbs);
+ } else if (destFile.length() == (destFile.lastIndexOf(".tar") + 4)) {// 判断是否tar包
+ GzipUtil.tarByCmd(sourcePath, destFile, excludes, isAbs);
+ } else {
+ throw new Exception("unable to compress this compressed file");
+ }
+
+ return returnFlag;
+ }
+
+ /**
+ * 文件解压,如果sourcePath是一个目录,则解压它下面的所有压缩文件
+ * @param sourcePath 需要解压的文件或需要解压文件的目录
+ * @param destPath 解压到的目标路径
+ * @param isAbs 相对路径还是绝对路径解压
+ * @return
+ * @throws Exception
+ */
+ public boolean decompressFile(String sourcePath, String destPath, boolean isAbs)
+ throws Exception {
+ logger.debug("decompressFile start……");
+ boolean returnFlag = true;
+ logger.debug("decompressFile sourcePath-----" + sourcePath);
+ logger.debug("decompressFile destPath-----" + destPath);
+ File folder = new File(sourcePath);
+ if (!folder.exists()) {
+ return false;
+ }
+ if (folder.isDirectory()) {
+ String files[] = folder.list();
+ String fileAbs = null;
+ for (int i = 0; i < files.length; i++) {
+ fileAbs = sourcePath + File.separator + files[i];
+ decompressFile(fileAbs, destPath, isAbs);
+ }
+ } else {
+ decompress(sourcePath, destPath, isAbs);
+ }
+
+ logger.debug("decompressFile end!");
+ return returnFlag;
+ }
+
+ /**
+ * 解压文件,只针对单个压缩文件
+ * @param sourceFile 需要解压的文件
+ * @param destPath 解压到的目标路径
+ * @param isAbs 相对路径还是绝对路径解压
+ * @throws Exception
+ */
+ private void decompress(String sourceFile, String destPath, boolean isAbs)
+ throws Exception {
+ logger.debug("decompress start……");
+ logger.debug("decompress sourceFile---" + sourceFile);
+ logger.debug("decompress 1-----"+(sourceFile.length() == (sourceFile.lastIndexOf(".zip") + 4)));
+ logger.debug("decompress 2-----"+(sourceFile.length() == (sourceFile.lastIndexOf(".rar") + 4)));
+ logger.debug("decompress 3-----"+(sourceFile.length() == (sourceFile.lastIndexOf(".gz") + 3)));
+ if (sourceFile.length() == (sourceFile.lastIndexOf(".zip") + 4)) {// 判断是否zip包
+ ZipUtil.unZip(sourceFile, destPath);
+ } else if (sourceFile.length() == (sourceFile.lastIndexOf(".rar") + 4)) {// 判断是否rar包
+ RarUtil.unRar(sourceFile, destPath);
+ } else if (sourceFile.length() == (sourceFile.lastIndexOf(".gz") + 3)) {// 判断是否gzip包
+ GzipUtil.unGzipByCmd(sourceFile, destPath, isAbs);
+ } else if (sourceFile.length() == (sourceFile.lastIndexOf(".tar") + 4)) {// 判断是否tar包
+ GzipUtil.unTarByCmd(sourceFile, destPath, isAbs);
+ } else {
+ throw new Exception("unable to decompress this decompressed file");
+ }
+ logger.debug("decompress end!");
+ }
+
+ public static String getCompressSuffixByOs(boolean isAbs){
+ String suffix = ".zip";
+ //根据操作系统确定获取进程ID的方式
+ String os = System.getProperty("os.name");
+ if (os.startsWith("Windows")) {
+ suffix = ".zip";
+ }else if (os.startsWith("Linux")){
+ suffix = (isAbs ? "_absolute" : "_relative") + ".tar.gz";
+ }
+ return suffix;
+ }
+
+ public static boolean isCompressFile(File file){
+ boolean flag = false;
+ if(file.isFile()){
+ String fileName = file.getName();
+ if (".rar".equalsIgnoreCase(fileName.substring(fileName.length() - 4))
+ || ".zip".equalsIgnoreCase(fileName.substring(fileName.length() - 4))
+ || ".tar".equalsIgnoreCase(fileName.substring(fileName.length() - 4))
+ || ".gz".equalsIgnoreCase(fileName.substring(fileName.length() - 3))) {
+ flag = true;
+ }
+ }
+ return flag;
+
+ }
+}
diff --git a/src/com/nis/nmsclient/util/DESUtil.java b/src/com/nis/nmsclient/util/DESUtil.java
new file mode 100644
index 0000000..a93b11f
--- /dev/null
+++ b/src/com/nis/nmsclient/util/DESUtil.java
@@ -0,0 +1,83 @@
+package com.nis.nmsclient.util;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.DESKeySpec;
+import javax.crypto.spec.IvParameterSpec;
+
+import sun.misc.BASE64Decoder;
+import sun.misc.BASE64Encoder;
+
+/**
+ * 通过DES加密解密实现一个String字符串的加密和解密.
+ *
+ */
+public class DESUtil {
+ private final static String key = "longstar";
+
+ /**
+ * DES加密方法
+ *
+ */
+ public static String desEncrypt(String message) throws Exception {
+ Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
+
+ DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("ASCII"));
+
+ SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
+ SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
+ IvParameterSpec iv = new IvParameterSpec(key.getBytes("ASCII"));
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
+
+ byte data[] = message.getBytes("ASCII");
+ byte[] encryptedData = cipher.doFinal(data);
+
+ return getBASE64(encryptedData);
+ }
+
+ /**
+ * DES解密方法
+ *
+ */
+ public static String desDecrypt(String message) throws Exception {
+ Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
+
+ DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("ASCII"));
+
+ SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
+ SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
+ IvParameterSpec iv = new IvParameterSpec(key.getBytes("ASCII"));
+ cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
+
+ byte data[] = getFromBASE64(message);
+ byte[] encryptedData = cipher.doFinal(data);
+
+ return new String(encryptedData);
+ }
+
+ // 对base64编码的string解码成byte数组
+ private static byte[] getFromBASE64(String s) {
+ if (s == null)
+ return null;
+ BASE64Decoder decoder = new BASE64Decoder();
+ try {
+ byte[] b = decoder.decodeBuffer(s);
+ return b;
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ //将 byte数组 进行 BASE64 编码
+ private static String getBASE64(byte[] b) {
+ if (b == null)
+ return null;
+ try {
+ String returnstr = (new BASE64Encoder()).encode(b);
+ return returnstr;
+ } catch (Exception e) {
+ return null;
+ }
+ }
+}
diff --git a/src/com/nis/nmsclient/util/DateUtil.java b/src/com/nis/nmsclient/util/DateUtil.java
new file mode 100644
index 0000000..fbc9e0e
--- /dev/null
+++ b/src/com/nis/nmsclient/util/DateUtil.java
@@ -0,0 +1,142 @@
+package com.nis.nmsclient.util;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.apache.log4j.Logger;
+
+public class DateUtil {
+ static Logger logger = Logger.getLogger(DateUtil.class);
+ /**
+ * 处理日期时,用到参数。格式24小时制yyyy-MM-dd HH:mm:ss
+ */
+ public static final SimpleDateFormat YYYY_MM_DD_HH24_MM_SS = new SimpleDateFormat(
+ "yyyy-MM-dd HH:mm:ss");
+ /**
+ * 处理日期时,用到参数。格式24小时制yyyyMMddHHmmss
+ */
+ public static final SimpleDateFormat YYYYMMDDHH24MMSS = new SimpleDateFormat(
+ "yyyyMMddHHmmss");
+ /**
+ * 处理日期时,用到参数。格式为yyyy-MM-dd
+ */
+ public static final SimpleDateFormat YYYY_MM_DD = new SimpleDateFormat(
+ "yyyy-MM-dd");
+ /**
+ * 处理日期时,用到参数。格式为yyyyMMdd
+ */
+ public static final SimpleDateFormat YYYYMMDD = new SimpleDateFormat(
+ "yyyyMMdd");
+
+
+ /**
+ * 获得当前日期
+ *
+ * @return
+ */
+ public static String getCurrentDate(SimpleDateFormat sf) {
+ if(sf==null){
+ sf = YYYY_MM_DD;
+ }
+ return sf.format(new Date());
+ }
+
+ /**
+ * 获得某日期的指定格式的字符串
+ * @param sf
+ * @param date
+ * @return
+ */
+ public static String getStingDate(SimpleDateFormat sf, Date date) {
+ if(date==null){
+ date = new Date();
+ }
+ if(sf==null){
+ sf = YYYY_MM_DD;
+ }
+
+ return sf.format(date);
+ }
+
+ public static long getDaysFromBeginToEnd(SimpleDateFormat dateFormat,
+ String begin, String end) {
+ Date beginD = null;
+ Date endD = null;
+ long days = 0;
+ try {
+ if (begin != null && !"".equals(begin)) {
+ beginD = dateFormat.parse(begin);
+ } else {
+ beginD = new Date();
+ }
+ if (end != null && !"".equals(end)) {
+ endD = dateFormat.parse(end);
+ } else {
+ endD = new Date();
+ }
+ days = getDaysFromBeginToEnd(beginD, endD);
+ } catch (ParseException e) {
+ logger.error(Utils.printExceptionStack(e));
+ return days;
+ }
+
+ return days;
+
+ }
+
+ public static long getDaysFromBeginToEnd(Date begin, Date end) {
+ long days = 0;
+ if (begin != null && end != null) {
+ days = getDaysFromBeginToEnd(begin.getTime(), end.getTime());
+ }
+
+ return days;
+
+ }
+
+ public static long getDaysFromBeginToEnd(long begin, long end) {
+ return (end - begin) / (24 * 60 * 60 * 1000);
+ }
+
+ public static long getMinutesFromBeginToEnd(SimpleDateFormat dateFormat,
+ String begin, String end) {
+ Date beginD = null;
+ Date endD = null;
+ long days = 0;
+ try {
+ if (begin != null && !"".equals(begin)) {
+ beginD = dateFormat.parse(begin);
+ } else {
+ beginD = new Date();
+ }
+ if (end != null && !"".equals(end)) {
+ endD = dateFormat.parse(end);
+ } else {
+ endD = new Date();
+ }
+ days = getMinutesFromBeginToEnd(beginD, endD);
+ } catch (ParseException e) {
+ logger.error(Utils.printExceptionStack(e));
+ return days;
+ }
+
+ return days;
+
+ }
+
+ public static long getMinutesFromBeginToEnd(Date begin, Date end) {
+ long days = 0;
+ if (begin != null && end != null) {
+ days = getMinutesFromBeginToEnd(begin.getTime(), end.getTime());
+ }
+
+ return days;
+
+ }
+
+ public static long getMinutesFromBeginToEnd(long begin, long end) {
+ return (end - begin) / (60 * 1000);
+ }
+
+}
diff --git a/src/com/nis/nmsclient/util/FileUtil.java b/src/com/nis/nmsclient/util/FileUtil.java
new file mode 100644
index 0000000..7f8eee7
--- /dev/null
+++ b/src/com/nis/nmsclient/util/FileUtil.java
@@ -0,0 +1,477 @@
+package com.nis.nmsclient.util;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Comparator;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.log4j.Logger;
+
+import com.nis.nmsclient.common.Contants;
+
+/**
+ * 文件操作类:检索、排序
+ *
+ */
+public class FileUtil {
+ static Logger logger = Logger.getLogger(FileUtil.class);
+
+ /**
+ * 获取子目录列表
+ * @param file
+ * @return
+ */
+ public static File[] getDirectoryArray(File file) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).isDirectory()) {
+ return true;
+ } else
+ return false;
+ }
+ });
+ }
+
+
+ /**
+ * 获取指定全部或部分名称的文件
+ * @param file
+ * @param azz
+ * @return
+ */
+ public static File[] getFilesArray(File file, final String azz) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).isDirectory()) {
+ return false;
+ }
+ return name.indexOf(azz) != -1; // 过滤出指定全部名称或部分名称的文件
+ }
+ });
+ }
+
+ /**
+ * 获取指定前缀的文件
+ * @param file
+ * @param suffix
+ * @return
+ */
+ public static File[] getFilesStartWith(File file, final String prefix) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).isDirectory()) {
+ return false;
+ }
+ return name.startsWith(prefix); // 过滤出注定前缀名称的文件
+ }
+ });
+ }
+
+ /**
+ * 获取指定时间段指定前缀的文件
+ * @param file
+ * @param suffix
+ * @return
+ */
+ public static File[] getFilesStartWithByMillis(File file, final String prefix, final long sTimeMillis, final long eTimeMillis) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).isDirectory()) {
+ return false;
+ }
+ if (sTimeMillis > 0 && eTimeMillis > 0) {
+ if (new File(dir, name).lastModified() < sTimeMillis
+ || new File(dir, name).lastModified() > eTimeMillis) {// 不在指定时间段
+ return false;
+ }
+ }
+ return name.startsWith(prefix); // 过滤出注定前缀名称的文件
+ }
+ });
+ }
+
+ /**
+ * 获取指定后缀名的文件
+ * @param file
+ * @param suffix
+ * @return
+ */
+ public static File[] getFilesEndWith(File file, final String suffix) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).isDirectory()) {
+ return false;
+ }
+ return name.endsWith(suffix); // 过滤出注定后缀名称的文件
+ }
+ });
+ }
+
+ /**
+ * 获取指定时间修改的指定后缀名的文件
+ * @param file
+ * @param suffix
+ * @return
+ */
+ public static File[] getFilesEndWithBeforeMillis(File file, final String suffix, final long timeMillis) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).isDirectory() || new File(dir,name).lastModified() > timeMillis) {
+ return false;
+ }
+ return name.endsWith(suffix); // 过滤出注定后缀名称的文件
+ }
+ });
+ }
+
+ /**
+ * 获取指定时间修改的文件
+ * @return
+ */
+ public static File[] getFilesBeforeMillis(File file, final long timeMillis) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).isDirectory() || new File(dir,name).lastModified() > timeMillis) {
+ return false;
+ }
+ return true;
+ }
+ });
+ }
+
+ /**
+ * 获取指定毫秒之后修改过的文件
+ * @param file
+ * @param timeMillis
+ * @return
+ */
+ public static File[] getFilesAfterMillis(File file, final long timeMillis) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).lastModified() >= timeMillis) {
+ return true;
+ } else
+ return false;
+ }
+ });
+ }
+
+ /**
+ * 获取指定时间名称及之前的文件夹
+ * @param file
+ * @param suffix
+ * @return
+ */
+ public static File[] getDirsBeforeDateName(File file, final String yyyyMMddName) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).isDirectory() && name.compareTo(yyyyMMddName)<=0) {
+ return true;
+ }
+ return false;
+ }
+ });
+ }
+
+ /**
+ * 获取指定时间名称及之后的文件夹
+ * @param file
+ * @param suffix
+ * @return
+ */
+ public static File[] getDirsAfterDateName(File file, final String yyyyMMddName) {
+ if (!file.isDirectory()) {
+ new Exception(file.getAbsolutePath() + " Not A Directory");
+ }
+ return file.listFiles(new FilenameFilter() {
+ // 使用匿名内部类重写accept方法;
+ public boolean accept(File dir, String name) {
+ if (new File(dir, name).isDirectory() && name.compareTo(yyyyMMddName)>=0) {
+ return true;
+ }
+ return false;
+ }
+ });
+ }
+
+ /**
+ * 文件数组按最后修改日期排序,升序
+ * @param files
+ * @return
+ */
+ public static File[] sortASCByModify(File[] files) {
+ Arrays.sort(files, new Comparator<File>(){
+ public int compare(File arg0, File arg1) {
+ if(arg0.lastModified() > arg1.lastModified()){
+ return 1;
+ }else if (arg0.lastModified() < arg1.lastModified()){
+ return -1;
+ }else {
+ return 0;
+ }
+ }
+ });
+ return files;
+ }
+
+ /**
+ * 文件数组按最后修改日期排序,降序
+ * @param files
+ * @return
+ */
+ public static File[] sortDescByModify(File[] files) {
+ Arrays.sort(files, new Comparator<File>(){
+ public int compare(File arg0, File arg1) {
+ if(arg0.lastModified() > arg1.lastModified()){
+ return -1;
+ }else if (arg0.lastModified() < arg1.lastModified()){
+ return 1;
+ }else {
+ return 0;
+ }
+ }
+ });
+ return files;
+ }
+
+ /**
+ * 文件数组按名称排序,升序
+ * @param files
+ * @return
+ */
+ public static File [] sortASCByFileName(File[] files) {
+ Arrays.sort(files, new Comparator<File>(){
+ public int compare(File arg0, File arg1) {
+ return arg0.getName().compareTo(arg1.getName());
+ }
+ });
+ return files;
+ }
+ /**
+ * 文件数组按名称排序,降序
+ * @param files
+ * @return
+ */
+ public static File [] sortDescByFileName(File[] files) {
+ Arrays.sort(files, new Comparator<File>(){
+ public int compare(File arg0, File arg1) {
+ return arg1.getName().compareTo(arg0.getName());
+ }
+ });
+ return files;
+ }
+
+ /**
+ * 将文件移动到指定文件夹
+ *
+ * @param f
+ * 源文件
+ * @param newDir
+ * 新目录
+ * @param flag
+ * 是否覆盖 true:覆盖 false:不覆盖
+ */
+ public static void moveFile(File f, String newDir, boolean flag) {
+ if (!f.exists()) {
+ logger.debug("文件已不存在,无法移动!" + f.getAbsolutePath());
+ return;
+ }
+ File fileDir = new File(newDir); // 备份目录
+ if (!fileDir.exists()) { // 检查并创建新目录
+ fileDir.mkdirs();
+ }
+ File dtnFile = new File(fileDir.getAbsolutePath() + File.separator
+ + f.getName()); // 制定目标文件路径以及文件名
+ if (dtnFile.exists() && flag) { // 检查并删除已存在文件
+ //dtnFile.delete_bak();
+ //使用删除文件公共方法
+ FileUtil.delDir(dtnFile);
+ logger.debug("moveFile 删除已存在文件--" + dtnFile.getAbsolutePath());
+ //FileUtil.checkParentDirExist(dtnFile);
+ }
+ try {
+ FileUtils.copyFile(f, dtnFile); // 移动文件
+ logger.debug("文件 From 》 " + f.getAbsolutePath()
+ + "\n To 》 " + dtnFile.getAbsolutePath());
+ if (f.exists()) {
+ logger.debug("删除源文件" + f.getAbsolutePath());
+ //f.delete_bak();
+ //使用删除文件公共方法
+ FileUtil.delDir(f);
+ //FileUtil.checkParentDirExist(f);
+ } else {
+ logger.debug("源文件不存在!不用删了!" + f.getAbsolutePath());
+ return;
+ }
+ } catch (IOException e) {
+ logger.error(Utils.printExceptionStack(e));
+ }
+ }
+
+ /**
+ * 删除文件或文件夹
+ */
+ public static void delDir(File file) {
+ try {//文件在可删范围并且不在禁删范围
+ if (file.exists() && isIncludeDelRange(file) && !isExcludeDelRange(file)) {
+ if (!file.isDirectory()) {
+ file.delete();
+ logger.debug("FileUtil.delDir(File file)删除文件--" + file.getAbsolutePath());
+ FileUtil.checkParentDirExist(file);
+ } else if (file.isDirectory()) {
+ delDir2(file);
+ }
+ }
+ } catch (IOException e) {
+ logger.error(Utils.printExceptionStack(e));
+ }
+ }
+
+ /**
+ * 递归删除文件夹及其下的所有文件
+ */
+ private static void delDir2(File file) throws IOException {
+ if (!file.exists()) {
+ return;
+ }
+ if (!file.isDirectory()) {
+ file.delete();
+ logger.debug("FileUtil.delDir2(File file)删除文件--" + file.getAbsolutePath());
+ FileUtil.checkParentDirExist(file);
+ } else if (file.isDirectory()) {
+ if (!isExcludeDelRange(file)) {// 文件不在禁删范围
+ for (File f : file.listFiles()) {
+ delDir2(f);
+ }
+ file.delete();
+ logger.debug("FileUtil.delDir2(File file)删除文件夹--" + file.getAbsolutePath());
+ FileUtil.checkParentDirExist(file);
+ }
+ }
+ }
+
+ /**
+ * 检查文件是否在可删范围内
+ * @param file
+ * @return true:是,false:否
+ */
+ public static boolean isIncludeDelRange(File file) throws IOException{
+ boolean flag = false;
+ String path = file.getCanonicalPath();
+ if(Contants.COMMON_DEL_PATH_INCLUDE!=null){
+ for(String include : Contants.COMMON_DEL_PATH_INCLUDE){
+ if(path.startsWith(include)){
+ flag = true;
+ break;
+ }
+ }
+ }else{//删除范围参数为空,则返回在删除范围
+ flag = true;
+ }
+ return flag;
+ }
+
+ /**
+ * 检查文件是否在禁删范围内
+ * @param file
+ * @return true:是,false:否
+ */
+ public static boolean isExcludeDelRange(File file) throws IOException{
+ boolean flag = false;
+ String path = file.getCanonicalPath();
+ if(Contants.COMMON_DEL_PATH_EXCLUDE!=null){
+ for(String exclude : Contants.COMMON_DEL_PATH_EXCLUDE){
+ if(path.startsWith(exclude)){
+ flag = true;
+ break;
+ }
+ }
+ }else{//禁删参数为空,则返回不在禁删范围
+ flag = false;
+ }
+ return flag;
+ }
+
+ public static void checkParentDirExist(File file){
+ logger.debug("检查父目录是否存在---" +file.getParentFile().exists() + "---" + file.getParent());
+ }
+
+ /**
+ * 格式化处理路径
+ * @param path
+ * @return
+ */
+ public static String handlerPath(String path){
+ File file = new File(path);
+ try {
+ path = file.getCanonicalPath();
+ } catch (IOException e) {
+ logger.error(Utils.printExceptionStack(e));
+ }
+
+ return path;
+ }
+
+ public static File[] getAll(File dir, int level) {
+ logger.info(getLevel(level) + dir.getName());
+
+ level++;
+ File[] files = dir.listFiles();
+ for (int x = 0; x < files.length; x++) {
+ if (files[x].isDirectory())
+ getAll(files[x], level);
+ else
+ logger.debug(getLevel(level) + files[x].getName());
+ }
+ return files;
+ }
+
+ public static String getLevel(int level) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("|--");
+
+ for (int x = 0; x < level; x++) {
+ sb.insert(0, "| ");
+ }
+ return sb.toString();
+ }
+
+}
diff --git a/src/com/nis/nmsclient/util/FileWrUtil.java b/src/com/nis/nmsclient/util/FileWrUtil.java
new file mode 100644
index 0000000..8ebf75c
--- /dev/null
+++ b/src/com/nis/nmsclient/util/FileWrUtil.java
@@ -0,0 +1,285 @@
+package com.nis.nmsclient.util;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+import com.Ostermiller.util.ExcelCSVParser;
+import com.Ostermiller.util.ExcelCSVPrinter;
+import com.nis.nmsclient.util.io.UnicodeReader;
+
+public class FileWrUtil {
+ static Logger logger = Logger.getLogger(FileWrUtil.class);
+
+ /**
+ * 根据文件编码添加文件内容前缀
+ * @param file
+ * @param encoding
+ */
+ protected static boolean addFileHeadByEncoding(File file, String encoding) throws Exception{
+ FileOutputStream fos = null;
+ boolean flag = false;
+ try{
+ byte[] head = null;
+ if("UTF-8".equalsIgnoreCase(encoding)){
+ head = new byte[]{(byte)0xEF,(byte)0xBB,(byte)0xBF};
+ }else if("UTF-16BE".equalsIgnoreCase(encoding)){
+ head = new byte[]{(byte)0xFE,(byte)0xFF};
+ }else if("UTF-16LE".equalsIgnoreCase(encoding)){
+ head = new byte[]{(byte)0xFF,(byte)0xFE};
+ }else if("UTF-32BE".equalsIgnoreCase(encoding)){
+ head = new byte[]{(byte)0x00,(byte)0x00,(byte)0xFE,(byte)0xFF};
+ }else if("UTF-32LE".equalsIgnoreCase(encoding)){
+ head = new byte[]{(byte)0xFF,(byte)0xFF,(byte)0x00,(byte)0x00};
+ }
+
+ if(head!=null){
+ fos = new FileOutputStream(file);
+ fos.write(head);
+ fos.flush();
+
+ flag = true;
+ }
+ } catch (IOException e) {
+ throw e;
+ }finally {
+ if(fos!=null){
+ try {
+ fos.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ return flag;
+ }
+
+ /**
+ * 写入文件, .cfg\.ini\.txt
+ *
+ */
+ public static boolean cfgFilePrinter(File file, String charset, String[] values) throws Exception{
+ OutputStreamWriter fos = null;
+ try {
+ if(addFileHeadByEncoding(file, charset)){
+ fos = new OutputStreamWriter(
+ new FileOutputStream(file,true), charset);
+ }else{
+ fos = new OutputStreamWriter(
+ new FileOutputStream(file), charset);
+ }
+ for(String val : values){
+ fos.write(val);
+ fos.write("\n");
+ }
+ fos.flush();
+ } catch (IOException e) {
+ throw e;
+ }finally {
+ if(fos!=null){
+ try {
+ fos.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * 追加内容到文件, .cfg\.ini\.txt
+ *
+ */
+ public static boolean cfgFileAppender(File file, String charset, String[] values) throws Exception{
+ OutputStreamWriter fos = null;
+ try {
+ fos = new OutputStreamWriter(
+ new FileOutputStream(file, true), charset);
+ for(String val : values){
+ fos.write(val);
+ fos.write("\n");
+ }
+ fos.flush();
+ } catch (IOException e) {
+ throw e;
+ }finally {
+ if(fos!=null){
+ try {
+ fos.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * 根据文件的编码读取文件内容, .cfg\.ini\.txt
+ *
+ */
+ public static String[] cfgFileReader(File file) throws Exception{
+ BufferedReader br = null;
+ ArrayList<String> list = new ArrayList<String>();
+ try {
+
+ br = new BufferedReader(new UnicodeReader(new FileInputStream(
+ file), Charset.defaultCharset().name()));
+ String str = null;
+ while((str=br.readLine())!=null){
+ list.add(str);
+ }
+ } catch (IOException e) {
+ throw e;
+ }finally {
+ if(br!=null){
+ try {
+ br.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ String[] values = new String[list.size()];
+ return list.toArray(values);
+ }
+
+ /**
+ * 写CSV文件,只写入一行
+ *
+ */
+ public static boolean csvFilePrinter(File file, String charset, String[] values) throws Exception{
+ OutputStreamWriter fos = null;
+ try {
+ fos = new OutputStreamWriter(
+ new FileOutputStream(file), charset);
+
+
+ ExcelCSVPrinter ecsvp = new ExcelCSVPrinter(fos);
+ ecsvp.changeDelimiter(',');
+ ecsvp.setAutoFlush(true);
+ ecsvp.writeln(values);
+
+ fos.flush();
+ } catch (IOException e) {
+ throw e;
+ }finally {
+ if(fos!=null){
+ try {
+ fos.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * 写CSV文件,写入多行
+ *
+ */
+ public static boolean csvFilePrinter(File file, String charset, List<String[]> values) throws Exception{
+ OutputStreamWriter fos = null;
+ try {
+ fos = new OutputStreamWriter(
+ new FileOutputStream(file), charset);
+
+
+ ExcelCSVPrinter ecsvp = new ExcelCSVPrinter(fos);
+ ecsvp.changeDelimiter(',');
+ ecsvp.setAutoFlush(true);
+ for(String[] val : values){
+ ecsvp.writeln(val);
+ }
+
+ fos.flush();
+ } catch (IOException e) {
+ throw e;
+ }finally {
+ if(fos!=null){
+ try {
+ fos.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * 解析CSV文件中的指定行
+ *
+ */
+ public static String[] csvFileParser(File file, String charset, int rowNum) throws Exception{
+ Reader in = null;
+ String[] currLine = null;
+ try {
+ //创建解析信息流
+ in = new InputStreamReader(new FileInputStream(file),charset);
+
+ ExcelCSVParser csvParser = new ExcelCSVParser(in);
+ while((currLine=csvParser.getLine())!=null){
+ if(rowNum != csvParser.getLastLineNumber()){
+ currLine = null;
+ }
+ }
+
+ } catch (IOException e) {
+ throw e;
+ }finally {
+ if(in!=null){
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ return currLine;
+ }
+
+ /**
+ * 解析CSV文件的所有行
+ *
+ */
+ public static List<String[]> csvFileParser(File file, String charset) throws Exception{
+ Reader in = null;
+ List<String[]> allLineList = new ArrayList<String[]>();
+ try {
+ //创建解析信息流
+ in = new InputStreamReader(new FileInputStream(file),charset);
+
+ ExcelCSVParser csvParser = new ExcelCSVParser(in);
+ String[] currLine = null;
+ while((currLine=csvParser.getLine())!=null){
+ allLineList.add(currLine);
+ }
+
+ } catch (IOException e) {
+ throw e;
+ }finally {
+ if(in!=null){
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ return allLineList;
+ }
+
+}
diff --git a/src/com/nis/nmsclient/util/GzipUtil.java b/src/com/nis/nmsclient/util/GzipUtil.java
new file mode 100644
index 0000000..75dce1b
--- /dev/null
+++ b/src/com/nis/nmsclient/util/GzipUtil.java
@@ -0,0 +1,680 @@
+package com.nis.nmsclient.util;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.log4j.Logger;
+
+import com.ice.tar.TarEntry;
+import com.ice.tar.TarInputStream;
+import com.ice.tar.TarOutputStream;
+import com.nis.nmsclient.common.Contants;
+
+/**
+ * gzip文件压缩与解压缩,对文件tar归档与解归档工具类
+ *
+ */
+public class GzipUtil {
+ static Logger logger = Logger.getLogger(GzipUtil.class);
+
+ /**
+ * 使用命令对单个gz压缩包解压
+ * @param srcFileStr 需要解压的gz文件
+ * @param destDir 解压后的目标路径
+ * @param isAbs 解压文件时 true 按绝对路径解压, false 进入目标路径后解压
+ * @throws Exception
+ */
+ public static void unGzipByCmd(String srcFileStr, String destDir, boolean isAbs) throws Exception{
+ logger.debug("unGzip start……");
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ try {
+ logger.debug("unGzipByCmd srcFile---" + srcFileStr);
+ logger.debug("unGzipByCmd destDir---" + destDir);
+
+ File srcFile = new File(srcFileStr);
+ File descFile = new File(destDir);
+ if(!srcFile.exists()){
+ throw new Exception("source file not exist");
+ }
+ if(!srcFile.isFile()){
+ throw new Exception("source file is not a file");
+ }
+ if(!descFile.exists()){
+ descFile.mkdirs();
+ }
+ if(!descFile.isDirectory()){
+ throw new Exception("compress destination path is not a directory");
+ }
+ String tarFile = srcFile.getParent() + File.separator + srcFile.getName().substring(0, srcFile.getName().length()-3);
+ StringBuffer sb = new StringBuffer();
+ sb.append("gunzip " + srcFileStr);
+ sb.append(";tar xvpPf " + tarFile);
+ if(!isAbs){
+ sb.append(" -C " + destDir);
+ }else{
+ sb.append(" -C /");
+ }
+ sb.append(";gzip " + tarFile);
+ logger.debug("unGzipByCmd cmd--->" + sb.toString());
+
+ String[] shellCmd = new String[] { "/bin/bash", "-c", sb.toString() };
+ process = Runtime.getRuntime().exec(shellCmd);
+ process.getOutputStream().close();
+
+ bReader = new BufferedReader(new InputStreamReader(process
+ .getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ while ((line = bReader.readLine()) != null) {
+ logger.debug("unGzipByCmd--->" + line);
+ }
+ while ((line = errorReader.readLine()) != null) {
+ logger.debug("unGzipByCmd error--->" + line);
+ throw new IOException(line);
+ }
+
+ logger.debug("unGzipByCmd end……");
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ try {
+ if (bReader != null) {
+ bReader.close();
+ }
+ if (errorReader != null) {
+ errorReader.close();
+ }
+ if (process != null) {
+ process.destroy();
+ }
+ } catch (Exception e) {
+ }
+ }
+
+ }
+
+ /**
+ * 使用命令将单个文件或一个目录压缩成Gzip格式
+ * @param srcPath 需要压缩的文件目录或文件
+ * @param destFileStr 压缩后的目标文件
+ * @param excludes 排除的目录或文件(全是绝对路径),不包含到压缩包的
+ * @param isAbs 压缩文件时 true 按绝对路径压缩(含有完成的路径压缩包), false 进入目标路径后压缩
+ * @throws Exception
+ */
+ public static void gzipByCmd(String srcPath, String destFileStr, String[] excludes, boolean isAbs) throws Exception{
+ logger.debug("gzipByCmd start……");
+ OutputStreamWriter fos = null;
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ File excludeFile = null;
+ boolean flag = true;
+ try {
+ logger.debug("gzipByCmd srcPath---" + srcPath);
+ logger.debug("gzipByCmd destFileStr---" + destFileStr);
+
+ File srcFile = new File(srcPath);
+ File descFile = new File(destFileStr);
+ if(!srcFile.exists()){
+ throw new Exception("decompress file not exist");
+ }
+ if(!descFile.getParentFile().exists()){
+ descFile.getParentFile().mkdirs();
+ }
+ StringBuffer sb = new StringBuffer();
+ if(!isAbs){
+ if(srcFile.isFile()){
+ sb.append("cd " + srcFile.getParentFile().getCanonicalPath() + ";");
+ }else{
+ sb.append("cd " + srcFile.getCanonicalPath() + ";");
+ }
+ }
+ sb.append("tar -czvpPf " + destFileStr);
+ if(excludes!=null && excludes.length>0){
+ if(!isAbs){
+ for (int i = 0; i < excludes.length; i++) {
+ int index = excludes[i].indexOf(srcFile
+ .getCanonicalPath());
+ logger.debug("gzipByCmd index--->" + index + "---src=" +srcFile
+ .getCanonicalPath());
+ int start = index + srcFile.getCanonicalPath().length() + 1;
+ logger.debug("gzipByCmd start--->" + start + "--length=" + excludes[i].length() +"---exclude=" + excludes[i]);
+ if (index != -1 && start <= excludes[i].length()) {
+ excludes[i] = excludes[i].substring(start,
+ excludes[i].length());
+ logger.debug("gzipByCmd exclude--->" + excludes[i]);
+ }
+ }
+ }
+ excludeFile = new File(Contants.localTempPath + File.separator + "excludelist_" + System.currentTimeMillis() + ".temp");
+ // 2012-11-21 修改 由于使用FileWrUtil写的文件(有文件头的),Linux下无法正确识别
+ fos = new OutputStreamWriter(
+ new FileOutputStream(excludeFile, true), System.getProperty("file.encoding"));
+ logger.debug("gzipByCmd ---- " + System.getProperty("file.encoding"));
+ for(String val : excludes){
+ fos.write(val);
+ fos.write("\n");
+ }
+ fos.flush();
+ //FileWrUtil.cfgFilePrinter(excludeFile, Contants.charset, excludes);
+ sb.append(" -X " + excludeFile.getCanonicalPath());
+ }
+ if(!isAbs){
+ if(srcFile.isFile()){
+ sb.append(" " + srcFile.getName());
+ }else{
+ sb.append(" *");
+ }
+ }else{
+ sb.append(" " + srcFile.getCanonicalPath());
+ }
+ logger.debug("gzipByCmd cmd--->" + sb.toString());
+
+ String[] shellCmd = new String[] { "/bin/bash", "-c", sb.toString() };
+ process = Runtime.getRuntime().exec(shellCmd);
+ process.getOutputStream().close();
+
+ bReader = new BufferedReader(new InputStreamReader(process
+ .getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ while ((line = bReader.readLine()) != null) {
+ logger.debug("gzipByCmd--->" + line);
+ }
+ while ((line = errorReader.readLine()) != null) {
+ logger.debug("gzipByCmd error--->" + line);
+ flag = false;
+ throw new IOException(line);
+ }
+
+ logger.debug("gzipByCmd end……");
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ try {
+ if(fos!=null){
+ fos.close();
+ }
+ if(excludeFile!=null && excludeFile.exists()){
+ //excludeFile.delete_bak();
+ //使用删除文件公共方法
+ FileUtil.delDir(excludeFile);
+ logger.debug("GzipUtil.gzipByCmd()--delete excludeFile=" + excludeFile.getAbsolutePath());
+ //FileUtil.checkParentDirExist(excludeFile);
+ }
+ if (bReader != null) {
+ bReader.close();
+ }
+ if (errorReader != null) {
+ errorReader.close();
+ }
+ if (process != null) {
+ process.destroy();
+ }
+ if(!flag){
+ File destFile = new File(destFileStr);
+ if(destFile.exists()){
+ //destFile.delete_bak();
+ //使用删除文件公共方法
+ FileUtil.delDir(destFile);
+ logger.debug("GzipUtil.gzipByCmd()--delete destFile=" + destFile.getAbsolutePath());
+ //FileUtil.checkParentDirExist(destFile);
+ }
+ }
+ } catch (Exception e) {
+ }
+ }
+
+ }
+
+ /**
+ * 使用命令对单个tar压缩包解压
+ * @param srcFileStr 需要解压的gz文件
+ * @param destDir 解压后的目标路径
+ * @param isAbs 解压文件时 true 按绝对路径解压, false 进入目标路径后解压
+ * @throws Exception
+ */
+ public static void unTarByCmd(String srcFileStr, String destDir, boolean isAbs) throws Exception{
+ logger.debug("unTarByCmd start……");
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ try {
+ logger.debug("unTarByCmd srcFile---" + srcFileStr);
+ logger.debug("unTarByCmd destDir---" + destDir);
+
+ File srcFile = new File(srcFileStr);
+ File descFile = new File(destDir);
+ if(!srcFile.exists()){
+ throw new Exception("source file not exist");
+ }
+ if(!srcFile.isFile()){
+ throw new Exception("source file is not a file");
+ }
+ if(!descFile.exists()){
+ descFile.mkdirs();
+ }
+ if(!descFile.isDirectory()){
+ throw new Exception("compress destination path is not a directory");
+ }
+ StringBuffer sb = new StringBuffer();
+ sb.append("tar xvpPf " + srcFileStr);
+ if(!isAbs){
+ sb.append(" -C " + destDir);
+ }else{
+ sb.append(" -C /");
+ }
+ logger.debug("unTarByCmd cmd--->" + sb.toString());
+
+ String[] shellCmd = new String[] { "/bin/bash", "-c", sb.toString() };
+ process = Runtime.getRuntime().exec(shellCmd);
+ process.getOutputStream().close();
+
+ bReader = new BufferedReader(new InputStreamReader(process
+ .getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ while ((line = bReader.readLine()) != null) {
+ logger.debug("unTarByCmd--->" + line);
+ }
+ while ((line = errorReader.readLine()) != null) {
+ logger.debug("unTarByCmd--->" + line);
+ throw new IOException(line);
+ }
+
+ logger.debug("unTarByCmd end……");
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ try {
+ if (bReader != null) {
+ bReader.close();
+ }
+ if (errorReader != null) {
+ errorReader.close();
+ }
+ if (process != null) {
+ process.destroy();
+ }
+ } catch (Exception e) {
+ }
+ }
+
+ }
+
+ /**
+ * 使用命令将单个文件或一个目录压缩成tar格式
+ * @param srcPath 需要压缩的文件目录或文件
+ * @param destFileStr 压缩后的目标文件
+ * @param excludes 排除的目录或文件(全是绝对路径),不包含到压缩包的
+ * @param isAbs 压缩文件时 true 按绝对路径压缩(含有完成的路径压缩包), false 进入目标路径后压缩
+ * @throws Exception
+ */
+ public static void tarByCmd(String srcPath, String destFileStr, String[] excludes, boolean isAbs) throws Exception{
+ logger.debug("tarByCmd start……");
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ File excludeFile = null;
+ boolean flag = true;
+ try {
+ logger.debug("tarByCmd srcPath---" + srcPath);
+ logger.debug("tarByCmd destFileStr---" + destFileStr);
+
+ File srcFile = new File(srcPath);
+ File descFile = new File(destFileStr);
+ if(!srcFile.exists()){
+ throw new Exception("decompress file not exist");
+ }
+ if(!descFile.getParentFile().exists()){
+ descFile.getParentFile().mkdirs();
+ }
+ StringBuffer sb = new StringBuffer();
+ if(!isAbs){
+ if(srcFile.isFile()){
+ sb.append("cd " + srcFile.getParentFile().getCanonicalPath() + ";");
+ }else{
+ sb.append("cd " + srcFile.getCanonicalPath() + ";");
+ }
+ }
+ sb.append("tar -cvpPf " + destFileStr);
+ if(excludes!=null && excludes.length>0){
+ if(!isAbs){
+ for (int i = 0; i < excludes.length; i++) {
+ int index = excludes[i].indexOf(srcFile
+ .getCanonicalPath());
+ logger.debug("tarByCmd index--->" + index + "---src=" +srcFile
+ .getCanonicalPath());
+ int start = index + srcFile.getCanonicalPath().length() + 1;
+ logger.debug("tarByCmd start--->" + start + "--length=" + excludes[i].length() +"---exclude=" + excludes[i]);
+ if (index != -1 && start <= excludes[i].length()) {
+ excludes[i] = excludes[i].substring(start,
+ excludes[i].length());
+ logger.debug("tarByCmd exclude--->" + excludes[i]);
+ }
+ }
+ }
+ excludeFile = new File(Contants.localTempPath + File.separator + "excludelist_" + System.currentTimeMillis() + ".temp");
+ FileWrUtil.cfgFilePrinter(excludeFile, Contants.charset, excludes);
+ sb.append(" -X " + excludeFile.getCanonicalPath());
+ }
+ if(!isAbs){
+ if(srcFile.isFile()){
+ sb.append(" " + srcFile.getName());
+ }else{
+ sb.append(" *");
+ }
+ }else{
+ sb.append(" " + srcFile.getCanonicalPath());
+ }
+ logger.debug("tarByCmd cmd--->" + sb.toString());
+
+ String[] shellCmd = new String[] { "/bin/bash", "-c", sb.toString() };
+ process = Runtime.getRuntime().exec(shellCmd);
+ process.getOutputStream().close();
+
+ bReader = new BufferedReader(new InputStreamReader(process
+ .getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ while ((line = bReader.readLine()) != null) {
+ logger.debug("tarByCmd--->" + line);
+ }
+ while ((line = errorReader.readLine()) != null) {
+ logger.debug("tarByCmd error--->" + line);
+ flag = false;
+ throw new IOException(line);
+ }
+
+ logger.debug("tarByCmd end……");
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ try {
+ if(excludeFile!=null && excludeFile.exists()){
+ //excludeFile.delete_bak();
+ //使用删除文件公共方法
+ FileUtil.delDir(excludeFile);
+ logger.debug("GzipUtil.tarByCmd()--delete excludeFile=" + excludeFile.getAbsolutePath());
+ //FileUtil.checkParentDirExist(excludeFile);
+ }
+ if (bReader != null) {
+ bReader.close();
+ }
+ if (errorReader != null) {
+ errorReader.close();
+ }
+ if (process != null) {
+ process.destroy();
+ }
+ if(!flag){
+ File destFile = new File(destFileStr);
+ if(destFile.exists()){
+ //destFile.delete_bak();
+ //使用删除文件公共方法
+ FileUtil.delDir(destFile);
+ logger.debug("GzipUtil.tarByCmd()--delete destFile=" + destFile.getAbsolutePath());
+ //FileUtil.checkParentDirExist(destFile);
+ }
+ }
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ /**
+ * 对单个gz压缩包解压
+ * @param srcFile 需要解压的gz文件
+ * @param destDir 解压后的目标路径
+ * @throws Exception
+ */
+ public static void unGzip(String srcFile, String destDir) throws Exception{
+ logger.debug("unGzip start……");
+ OutputStream out = null;
+ GZIPInputStream gis = null;
+ File tempFile = new File(destDir + File.separator + System.currentTimeMillis() + ".tar");
+ try {
+ logger.debug("unGzip tempFile----" + tempFile.getAbsolutePath());
+ logger.debug("unGzip srcFile---" + srcFile);
+ logger.debug("unGzip destDir---" + destDir);
+ gis = new GZIPInputStream(new FileInputStream(new File(srcFile)));
+
+ if(!tempFile.getParentFile().exists()){
+ tempFile.getParentFile().mkdirs();
+ }
+ out = new FileOutputStream(tempFile);
+ logger.debug("unGzip tempFile---------" + tempFile.getAbsolutePath());
+ byte[] buf = new byte[1024 * 2];
+ int len = 0;
+ while ((len = gis.read(buf)) != -1) {
+ logger.debug("unGzip len---------" + len);
+ out.write(buf, 0, len);
+ }
+ out.flush();
+
+ //tar包解归档
+ GzipUtil.unTar(tempFile.getAbsolutePath(), destDir);
+
+ logger.debug("unGzip end……");
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ try {
+ if(gis!=null) gis.close();
+ if(out!=null) out.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ logger.debug("tempFile.delete() start……" + tempFile.getAbsolutePath());
+ if(tempFile.exists()){
+ //tempFile.delete_bak();
+ //使用删除文件公共方法
+ FileUtil.delDir(tempFile);
+ logger.debug("unGzip delete file --" + tempFile.getAbsolutePath());
+ //FileUtil.checkParentDirExist(tempFile);
+ }
+ logger.debug("tempFile.delete() end……" + tempFile.getAbsolutePath());
+ }
+
+ }
+
+ /**
+ * 将单个文件或一个目录压缩成Gzip格式
+ *
+ * @param srcPath 需要压缩的文件目录或文件
+ * @param destFile 压缩后的目标文件
+ * @throws Exception
+ */
+ public static void gzip(String srcPath, String destFile) throws Exception {
+ File tempFile = new File(new File(destFile).getParent() + File.separator + System.currentTimeMillis() + ".tar");
+ GZIPOutputStream gzout = null;
+ FileInputStream tarin = null;
+ try{
+ //tar包归档
+ GzipUtil.tar(srcPath, tempFile.getAbsolutePath());
+
+ //建立gzip压缩输出流
+ gzout = new GZIPOutputStream(new FileOutputStream(destFile));
+ //打开需压缩文件作为文件输入流
+ tarin = new FileInputStream(tempFile);
+ int len;
+ byte[] buf = new byte[1024 * 2];
+ while ((len = tarin.read(buf)) != -1) {
+ gzout.write(buf, 0, len);
+ }
+ gzout.flush();
+
+ }catch (Exception e) {
+ throw e;
+ }finally {
+ if(tarin!=null) tarin.close();
+ if(gzout!=null) gzout.close();
+ if(tempFile.exists()){
+ //tempFile.delete_bak();
+ //使用删除文件公共方法
+ FileUtil.delDir(tempFile);
+ logger.debug("GzipUtil.gzip()--delete tempFile=" + tempFile.getAbsolutePath());
+ //FileUtil.checkParentDirExist(tempFile);
+ }
+ }
+ }
+
+
+ /**
+ * 对单个tar压缩包解压,即解归档
+ *
+ * @param srcFile 需要解压的tar文件
+ * @param outpath 解压后的目标路径
+ * @throws Exception
+ */
+ public static void unTar(String srcFile, String outpath) throws Exception{
+ logger.debug("unTar start……");
+ TarInputStream tis = null;
+ try {
+ logger.debug("unTar srcFile---" + srcFile);
+ logger.debug("unTar outpath---" + outpath);
+ File file = new File(srcFile);
+ if(!file.exists()){
+// throw new Exception("解压源文件不存在: " + file.getAbsolutePath());
+ throw new Exception("Unzip source file does not exist: " + file.getAbsolutePath());
+ }
+ tis = new TarInputStream(new FileInputStream(file));
+ /*关键在于这个TarEntry 的理解, 实际你的tar包里有多少文件就有多少TarEntry*/
+ TarEntry tarEntry = null;
+ while ((tarEntry = tis.getNextEntry()) != null) {
+ logger.debug("unTar tarEntry---" + tarEntry);
+ String tempFileName = (outpath + File.separator + tarEntry.getName()).replaceAll("\\\\", "/");
+ logger.debug("unTar tempFileName---" + tempFileName);
+ if (tarEntry.isDirectory()) {
+ logger.debug("unTar tarEntry is Dir");
+ int end = tempFileName.lastIndexOf("/");
+ if (end != -1) {
+ File dir = new File(tempFileName.substring(0, end));
+ if (!dir.exists()) {
+ dir.mkdirs();
+ }
+ }
+ } else {
+ logger.debug("unTar tarEntry is file");
+ File tempFile = new File(tempFileName);
+ if(!tempFile.getParentFile().exists()){
+ tempFile.getParentFile().mkdirs();
+ }
+ tempFile.createNewFile();
+ OutputStream out = new FileOutputStream(tempFile);
+ IOUtils.copy(tis, out);
+ out.close();
+ }
+ }
+ logger.debug("unTar end……");
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ try {
+ if(tis!=null) tis.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ }
+
+ /**
+ * 将单个文件或一个目录打成tar包,即归档
+ *
+ * @param srcDir 需要压缩的文件目录或文件
+ * @param destFile 压缩后的目标文件
+ * @throws Exception
+ */
+ public static void tar(String srcDir, String destFile) throws Exception {
+ TarOutputStream tout = null;
+ try{
+ //建立tar压缩输出流
+ tout = new TarOutputStream(new FileOutputStream(destFile));
+ File srcFile = new File(srcDir);
+ if (!srcFile.exists()) {
+// throw new Exception("压缩目录或文件不存在: " + srcFile.getAbsolutePath());
+ throw new Exception("Compressed directories or files do not exist: " + srcFile.getAbsolutePath());
+ }
+ if(srcFile.isDirectory()){
+ tar(tout,srcFile,srcFile.getName());
+ }else{
+ tar(tout,srcFile,"");
+ }
+ }catch (Exception e) {
+ throw e;
+ }finally {
+ if(tout!=null) tout.close();
+ }
+ }
+
+ /**
+ * tar压缩
+ * @param out: tar压缩流
+ * @param srcFile: 需要压缩的目录或文件
+ * @param base: 需要压缩的文件在压缩后的tar包内的路径
+ * @throws Exception
+ */
+ public static void tar(TarOutputStream tout, File srcFile, String base) throws Exception{
+ if (!srcFile.exists()) {
+// throw new Exception("压缩目录或文件不存在: " + srcFile.getAbsolutePath());
+ throw new Exception("Compressed directories or files do not exist: " + srcFile.getAbsolutePath());
+ }
+ if (srcFile.isDirectory()) {
+ File[] files = srcFile.listFiles();
+ base = base.length() == 0 ? "" : base + "/";
+ if (base.length() > 0) {
+ TarEntry tarEn = new TarEntry(srcFile); //此处必须使用new TarEntry(File file);
+ tarEn.setName(base); //此处需重置名称,默认是带全路径的,否则打包后会带全路径
+ tout.putNextEntry(tarEn);
+ }
+ for (int i = 0; i < files.length; i++) {
+ tar(tout, files[i], base + files[i].getName());
+ }
+ } else {
+ base = base.length() == 0 ? srcFile.getName() : base;
+ TarEntry tarEn = new TarEntry(srcFile);
+ tarEn.setName(base);
+ tout.putNextEntry(tarEn);
+ FileInputStream fis = null;
+ try{
+ fis = new FileInputStream(srcFile);
+ IOUtils.copy(fis, tout);
+ }catch (IOException e) {
+ throw e;
+ }finally{
+ if(fis!=null) fis.close();
+ }
+ }
+ tout.closeEntry();
+ }
+
+
+ public static void main(String[] args) {
+ try {
+ long tt = System.currentTimeMillis();
+ //tar("D:\\temp\\test", "d:\\temp\\t1.tar");
+ //unTar("D:\\temp\\t1.tar", "D:\temp\\t1");
+
+ //gzip("D:\\temp\\t1\\gd-2.0.350000", "d:\\temp\\test\\t1.tar.gz");
+ unGzip("d:\\temp\\nms.tar.gz", "D:\\temp\\t1");
+ System.out.println(System.currentTimeMillis()-tt);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+}
+
diff --git a/src/com/nis/nmsclient/util/MD5Util.java b/src/com/nis/nmsclient/util/MD5Util.java
new file mode 100644
index 0000000..7d2ac4f
--- /dev/null
+++ b/src/com/nis/nmsclient/util/MD5Util.java
@@ -0,0 +1,99 @@
+package com.nis.nmsclient.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+public class MD5Util {
+ /**
+ * 默认的密码字符串组合,apache校验下载的文件的正确性用的就是默认的这个组合
+ */
+ protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
+ '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+ protected static MessageDigest messagedigest = null;
+ static {
+ try {
+ messagedigest = MessageDigest.getInstance("MD5");
+ } catch (NoSuchAlgorithmException nsaex) {
+ System.err.println(MD5Util.class.getName()
+ + "初始化失败,MessageDigest不支持MD5Util。");
+ nsaex.printStackTrace();
+ }
+ }
+
+ public static void main(String[] args) throws IOException {
+ long begin = System.currentTimeMillis();
+
+ // 2EA3E66AC37DF7610F5BD322EC4FFE48 670M 11s kuri双核1.66G 2G内存
+ File big = new File("I:/大型安装程序的压缩版本/Rational rose 2003.rar");
+
+ String md5 = getFileMD5String(big);
+
+ long end = System.currentTimeMillis();
+ System.out.println("md5:" + md5 + " time:" + ((end - begin) / 1000)
+ + "s");
+ }
+
+ /**
+ * 适用于上G大的文件
+ *
+ * @param file
+ * @return
+ * @throws IOException
+ */
+ public static String getFileMD5String(File file) throws IOException {
+ FileInputStream in = null;
+ try {
+ in = new FileInputStream(file);
+ FileChannel ch = in.getChannel();
+ MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
+ file.length());
+ messagedigest.update(byteBuffer);
+ return bufferToHex(messagedigest.digest());
+ } catch (Exception e) {
+ throw new IOException(e.getCause());
+ }finally{
+ if(in!=null){
+ in.close();
+ }
+ }
+ }
+
+ public static String getMD5String(String s) {
+ return getMD5String(s.getBytes());
+ }
+
+ public static String getMD5String(byte[] bytes) {
+ messagedigest.update(bytes);
+ return bufferToHex(messagedigest.digest());
+ }
+
+ private static String bufferToHex(byte bytes[]) {
+ return bufferToHex(bytes, 0, bytes.length);
+ }
+
+ private static String bufferToHex(byte bytes[], int m, int n) {
+ StringBuffer stringbuffer = new StringBuffer(2 * n);
+ int k = m + n;
+ for (int l = m; l < k; l++) {
+ appendHexPair(bytes[l], stringbuffer);
+ }
+ return stringbuffer.toString();
+ }
+
+ private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
+ char c0 = hexDigits[(bt & 0xf0) >> 4];
+ char c1 = hexDigits[bt & 0xf];
+ stringbuffer.append(c0);
+ stringbuffer.append(c1);
+ }
+
+ public static boolean checkPassword(String password, String md5PwdStr) {
+ String s = getMD5String(password);
+ return s.equals(md5PwdStr);
+ }
+}
diff --git a/src/com/nis/nmsclient/util/ProcessUtil.java b/src/com/nis/nmsclient/util/ProcessUtil.java
new file mode 100644
index 0000000..461a8d1
--- /dev/null
+++ b/src/com/nis/nmsclient/util/ProcessUtil.java
@@ -0,0 +1,1341 @@
+package com.nis.nmsclient.util;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.log4j.Logger;
+import com.nis.nmsclient.common.Contants;
+
+public class ProcessUtil
+{
+
+ static Logger logger = Logger.getLogger(ProcessUtil.class);
+ private static final String EXEC_CMD_FILE = Contants.LOCAL_SCRIPT_PATH + "/execCmdBySu.sh";
+ private static final String CHECK_USERPASS_FILE = Contants.LOCAL_SCRIPT_PATH
+ + "/check_userpass.sh";
+ private static Byte[] oWin = new Byte[0];
+ private static Byte[] oLinux = new Byte[0];
+
+ /**
+ * 从文件读取PID值
+ *
+ * @param pidFile
+ * 存放PID的文件
+ * @return PID数组
+ * @throws Exception
+ */
+ public static String[] getProcessIdByFile(File pidFile) throws Exception
+ {
+ String[] pids = null;
+ if (pidFile.exists())
+ {
+ String[] values = FileWrUtil.cfgFileReader(pidFile);
+ if (values != null && values.length > 0 && values[0].trim().length() > 0)
+ {
+ pids = values[0].trim().split(",");
+ }
+
+ }
+ return pids;
+ }
+
+ /**
+ * 根据PID按不同操作系统判断进程是否存在
+ *
+ * @param pid
+ * @return true 存在,false 不存在
+ * @throws Exception
+ */
+ public static boolean isProcessExistByPid(String pid) throws Exception
+ {
+ boolean flag = false;
+ // 根据操作系统确定获取进程ID的方式
+ String os = System.getProperty("os.name");
+ if (os.startsWith("Windows"))
+ {
+ flag = isWinProcessExistByPid(pid.trim());
+ } else if (os.startsWith("Linux"))
+ {
+ flag = isLinuxProcessExistByPid(pid.trim());
+ } else
+ {
+ throw new IOException("unknown operating system: " + os);
+ }
+
+ return flag;
+ }
+
+ /**
+ * 根据PID判断Linux下进程是否存在
+ *
+ * @param pid
+ * @return
+ */
+ public static boolean isLinuxProcessExistByPid(String pid)
+ {
+ String cmd = "ps -p " + pid.trim() + " | grep " + pid.trim()
+ + " | grep -v defunct | awk '{print $1}'";
+ String[] shellCmd1 = new String[] { "/bin/bash", "-c", cmd };
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ boolean flag = false;
+ logger.info("isLinuxProcessExistByPid cmd-----" + cmd);
+ synchronized (oLinux)
+ {
+ try
+ {
+ // 找到根据进程名获取到的进程号列表
+ process = Runtime.getRuntime().exec(shellCmd1);
+ process.getOutputStream().close();
+
+ bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ while ((line = bReader.readLine()) != null)
+ {
+ logger.debug("isLinuxProcessExistByPid line-----" + line);
+ flag = true;
+ }
+ while ((line = errorReader.readLine()) != null)
+ {
+ logger.debug("isLinuxProcessExistByPid error line--->" + line);
+ }
+
+ } catch (IOException e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ } finally
+ {
+ try
+ {
+ if (bReader != null)
+ {
+ bReader.close();
+ }
+ if (errorReader != null)
+ {
+ errorReader.close();
+ }
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (IOException e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ }
+ }
+
+ }
+ return flag;
+ }
+
+ /**
+ * 根据PID判断Windows下进程是否存在
+ *
+ * @param pid
+ * @return
+ */
+ public static boolean isWinProcessExistByPid(String pid)
+ {
+ String[] cmd = new String[] { "cmd.exe", "/C",
+ "wmic process where processId=" + pid.trim() + " get processId" };
+ logger.info("isWinProcessExistByPid cmd-----" + cmd[2]);
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ boolean flag = false;
+ try
+ {
+ synchronized (oWin)
+ {
+ process = Runtime.getRuntime().exec(cmd);
+ process.getOutputStream().close();
+ bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ while ((line = bReader.readLine()) != null)
+ {
+ logger.debug("isWinProcessExistByPid line-----" + line);
+ if (line.trim().equals(pid.trim()))
+ {
+ flag = true;
+ }
+ }
+ while ((line = errorReader.readLine()) != null)
+ {
+ logger.debug("isWinProcessExistByPid error line--->" + line);
+ }
+ }
+
+ } catch (IOException e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ } finally
+ {
+ try
+ {
+ if (bReader != null)
+ {
+ bReader.close();
+ }
+ if (errorReader != null)
+ {
+ errorReader.close();
+ }
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (IOException e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ }
+ }
+
+ return flag;
+ }
+
+ /**
+ * Linux下执行命令
+ *
+ * @param cmd
+ * @return
+ * @throws Exception
+ */
+ public static String execLinuxCmd(String cmd) throws Exception
+ {
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ try
+ {
+ // logger.debug("execLinuxCmd start-------" + cmd);
+ String[] shellCmd = new String[] { "/bin/bash", "-c", cmd };
+ process = Runtime.getRuntime().exec(shellCmd);
+ process.getOutputStream().close();
+
+ bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ while ((line = bReader.readLine()) != null)
+ {
+ logger.debug("execLinuxCmd line--->" + line);
+ }
+ StringBuffer errorSb = new StringBuffer();
+ while ((line = errorReader.readLine()) != null)
+ {
+ logger.debug("execLinuxCmd error line--->" + line);
+ errorSb.append(line + ",");
+ }
+
+ if (errorSb.toString().length() > 0)
+ {
+ errorSb.deleteCharAt(errorSb.length() - 1);
+ return errorSb.toString();
+ }
+
+ // logger.debug("execLinuxCmd end-------" + cmd);
+ } catch (Exception e)
+ {
+ throw e;
+ } finally
+ {
+ try
+ {
+ if (bReader != null)
+ {
+ bReader.close();
+ }
+ if (errorReader != null)
+ {
+ errorReader.close();
+ }
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (Exception e1)
+ {
+ }
+ }
+ return null;
+ }
+
+ /**
+ * windows下执行命令
+ *
+ * @param cmd
+ * @return
+ * @throws Exception
+ */
+ public static String execWinCmd(String cmd) throws Exception
+ {
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ try
+ {
+ logger.debug("execWinCmd start-------" + cmd);
+ //cmd = handlerWinSpace(cmd);
+ String[] cmdArr = new String[] { "cmd.exe", "/C", cmd };
+ process = Runtime.getRuntime().exec(cmdArr);
+ if (cmd.endsWith(".exe"))
+ {
+ synchronized (process)
+ {
+ process.wait(1000 * 5);
+ }
+ process.getOutputStream().close();
+ process.getInputStream().close();
+ process.getErrorStream().close();
+ } else
+ {
+ process.getOutputStream().close();
+ Charset platform = Charset.forName(System.getProperty("sun.jnu.encoding"));
+ bReader = new BufferedReader(new InputStreamReader(process.getInputStream(), platform));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), platform));
+ String line = null;
+ while ((line = bReader.readLine()) != null)
+ {
+ logger.debug("execWinCmd line--->" + line);
+ }
+ StringBuffer errorSb = new StringBuffer();
+ while ((line = errorReader.readLine()) != null)
+ {
+ logger.debug("execWinCmd error--->" + line);
+ errorSb.append(line + ",");
+ }
+ if (errorSb.length() > 0)
+ {
+ errorSb.deleteCharAt(errorSb.length() - 1);
+ return errorSb.toString();
+ }
+ }
+
+ logger.debug("execWinCmd end-------" + cmd);
+
+ } catch (Exception e)
+ {
+ throw e;
+ } finally
+ {
+ try
+ {
+ if (bReader != null)
+ {
+ bReader.close();
+ }
+ if (errorReader != null)
+ {
+ errorReader.close();
+ }
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (Exception e1)
+ {
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * 执行文件或命令,不同的操作系统按相应方式执行
+ *
+ * @param cmd
+ * 文件全路径或执行命令
+ * @param cmdParams
+ * 执行参数
+ * @param username
+ * 执行用户
+ * @param passwd
+ * 执行用户的密码
+ * @return 返回错误输出:若有返回,则执行失败;若返回null,则执行成功
+ * @throws IOException
+ */
+ public static String runExec(String cmd, String[] cmdParams, String username, String passwd)
+ throws IOException
+ {
+ return runExec(cmd, cmdParams, username, passwd, false);
+ }
+
+ /**
+ * 执行文件或命令,不同的操作系统按相应方式执行
+ *
+ * @param isDaemon
+ * 若为true, NC守护进程, 不读取输出;若为false, 执行文件或命令,读取输出
+ * @return
+ * @throws IOException
+ */
+ public static String runExec(String cmd, String[] cmdParams, String username, String passwd,
+ boolean isDaemon) throws IOException
+ {
+ // 根据操作系统确定运行方式
+ String os = System.getProperty("os.name");
+ Process process = null;
+ try
+ {
+ logger.debug("runExec start-------" + cmd);
+ String error = null;
+ if (os.startsWith("Windows"))
+ {
+ StringBuffer sb = new StringBuffer();
+ if (isDaemon)
+ {// -- 执行NC守护进程脚本
+ sb.append("start /b " + handlerWinSpace(cmd));
+ if (cmdParams != null && cmdParams.length > 0)
+ {
+ // 如果执行参数为数组类型时使用
+ for (String param: cmdParams)
+ {
+ // 带空格参数的特殊处理
+ sb.append(" " + handlerWinSpace(param));
+ }
+ }
+ sb.append(" >nul 2>&1");
+ logger.info("runExec Windows-------" + sb.toString());
+ String[] cmdArr = new String[] { "cmd.exe", "/C", sb.toString() };
+ process = Runtime.getRuntime().exec(cmdArr);
+ synchronized (process)
+ {
+ process.wait(1000 * 5);
+ }
+ process.getOutputStream().close();
+ process.getInputStream().close();
+ process.getErrorStream().close();
+ } else
+ {
+ sb.append(handlerWinSpace(cmd));
+ if (cmdParams != null && cmdParams.length > 0)
+ {
+ // 如果执行参数为数组类型时使用
+ for (String param: cmdParams)
+ {
+ // 带空格参数的特殊处理
+ sb.append(" " + handlerWinSpace(param));
+ }
+ }
+ logger.info("runExec Windows-------" + sb.toString());
+ error = execWinCmd(sb.toString());
+ }
+ } else if (os.startsWith("Linux"))
+ {
+ StringBuffer sb = new StringBuffer();
+ sb.append("nohup " + cmd.trim());
+ if (cmdParams != null && cmdParams.length > 0)
+ {
+ // 如果执行参数为数组类型时使用
+ for (String param: cmdParams)
+ {
+ // 带空格参数的特殊处理
+ sb.append(" " + handlerLinuxSpace(param));
+ }
+ }
+ sb.append(" >/dev/null 2>&1 &");
+ logger.info("runExec Linux-------" + sb.toString());
+ if (username != null && username.trim().length() > 0)
+ {
+ // -- 有密码调用execCmdBySu.sh文件执行
+ if (passwd != null && passwd.trim().length() > 0)
+ {
+ File file = new File(EXEC_CMD_FILE);
+ // 执行结果标识参数1、0 表示执行命令后是否添加:echo $?
+ String temp = file.getCanonicalPath() + " 1 \"" + sb.toString() + "\" "
+ + username.trim();
+ logger.info("runExec-->" + temp);
+ temp += " " + DESUtil.desDecrypt(passwd.trim());
+ sb.delete(0, sb.length());
+ sb.append("nohup " + temp + " >/dev/null 2>&1 &");
+ } else
+ {
+ // -- 无密码自己拼命令
+ String temp = "su - -c \"" + sb.toString() + "\" " + username.trim();
+ logger.info("runExec-->" + temp);
+ sb.delete(0, sb.length());
+ sb.append(temp);
+ }
+ }
+ error = execLinuxCmd(sb.toString());
+ } else
+ {
+ throw new IOException("unknown operating system: " + os);
+ }
+
+ logger.debug("sleep: 10 seconds");
+ Thread.sleep(10 * 1000);
+
+ logger.debug("runExec end-------" + cmd);
+
+ return error;
+ } catch (Exception e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+// return "出现异常:" + e.getMessage();
+ return "Abnormality:" + e.getMessage();
+ } finally
+ {
+ try
+ {
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (Exception e1)
+ {
+ }
+ }
+
+ }
+
+ /**
+ * 赋权限:若path是目录,给目录下所有文件赋指定的权限
+ *
+ * @param permit
+ * 权限的整数值
+ * @param path
+ * 需要赋权限的文件或目录
+ */
+ public static void permit(long permit, File path)
+ {
+ // 根据操作系统确定运行方式
+ String os = System.getProperty("os.name");
+ logger.debug("permit-----path=" + path.getAbsolutePath());
+ try
+ {
+ if (os.startsWith("Linux") && path != null && path.exists())
+ {
+ if (path.isDirectory() && path.listFiles().length > 0)
+ {
+ execLinuxCmd("chmod " + permit + " "
+ + handlerLinuxSpace(path.getCanonicalPath()) + File.separator + "*");
+ File[] files = path.listFiles();
+ for (File file: files)
+ {
+ if (file.isDirectory())
+ {
+ permit(permit, file);
+ }
+ }
+ } else
+ {
+ execLinuxCmd("chmod " + permit + " "
+ + handlerLinuxSpace(path.getCanonicalPath()));
+ }
+ }
+ } catch (Exception e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ }
+ }
+
+ /**
+ * 杀进程:根据操作系统以不同的方式停用进程
+ *
+ * @param processId
+ * @throws IOException
+ */
+ public static void killProcess(String processId) throws IOException
+ {
+ // 根据操作系统确定运行方式
+ String os = System.getProperty("os.name");
+ try
+ {
+ if (os.startsWith("Windows"))
+ {
+ String cmd = "wmic process where processId=" + processId + " delete";
+ logger.debug("killProcess win cmd-------" + cmd);
+ execWinCmd(cmd);
+ } else if (os.startsWith("Linux"))
+ {
+ String cmd = "kill -9 " + processId;
+ logger.debug("killProcess linux cmd-------" + cmd);
+ execLinuxCmd(cmd);
+ } else
+ {
+ throw new IOException("unknown operating system: " + os);
+ }
+ Thread.sleep(5 * 1000);
+ } catch (Exception e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ }
+ }
+
+ /**
+ * 只能用来运行命令,取得运行命令的输出结果,根据错误输出流来判断命令运行成功与否 如果需切换用户,调用execCmdBySu.sh执行
+ *
+ * @param cmd
+ * @param username
+ * @return 成功:0|命令输出信息;失败:1|失败信息
+ * @throws Exception
+ */
+ public static String runExecGetResult(String cmd, String username, String passwd)
+ throws Exception
+ {
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ String seprator = "|";
+ try
+ {
+ logger.debug("runExecGetResult start-------" + cmd);
+ String os = System.getProperty("os.name");// 根据操作系统确定运行方式
+ String result = "0" + seprator;
+ String[] cmdArr = null;
+ if (os.startsWith("Windows"))
+ {
+ // 【&& echo 0 || echo 1】 执行成功输出0,执行失败输出1,为了与Linux下的一致来取执行结果
+ String tempCmd = handlerWinSpace(cmd) + " && echo 0 || echo 1";
+ logger.info("runExecGetResult-->" + tempCmd);
+ cmdArr = new String[] { "cmd.exe", "/C", tempCmd };
+ } else if (os.startsWith("Linux"))
+ {
+ String tempCmd = cmd.trim();
+ if (username != null && username.trim().length() > 0)
+ {
+ // -- 有密码调用execCmdBySu.sh文件执行
+ if (passwd != null && passwd.trim().length() > 0)
+ {
+ File file = new File(EXEC_CMD_FILE);
+ // 执行结果标识参数1、0 表示执行命令后是否添加:echo $?
+ tempCmd = file.getCanonicalPath() + " 0 \"" + cmd.trim() + "\" "
+ + username.trim();
+ logger.info("runExecGetResult-->" + tempCmd);
+ tempCmd += " " + DESUtil.desDecrypt(passwd.trim());
+ } else
+ {
+ // -- 无密码自己拼命令
+ tempCmd = "su - -c \"" + cmd.trim() + ";echo $?\" " + username.trim();
+ logger.info("runExecGetResult-->" + tempCmd);
+ }
+ } else
+ {
+ tempCmd += ";echo $?";// 为了与脚本中的echo $?运行命令保持一致
+ logger.info("runExecGetResult-->" + tempCmd);
+ }
+ cmdArr = new String[] { "/bin/bash", "-c", tempCmd };
+ } else
+ {
+ throw new IOException("unknown operating system: " + os);
+ }
+ process = Runtime.getRuntime().exec(cmdArr);
+ process.getOutputStream().close();
+ bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ StringBuffer sb = new StringBuffer();
+ while ((line = bReader.readLine()) != null)
+ {
+ sb.append(line + ",");
+ logger.debug("runExecGetResult right-->" + line);
+ }
+ StringBuffer errorSb = new StringBuffer();
+ while ((line = errorReader.readLine()) != null)
+ {
+ errorSb.append(line + ",");
+ logger.debug("runExecGetResult error-->" + line);
+ }
+ if (errorSb.length() > 0)
+ {
+ errorSb.deleteCharAt(errorSb.length() - 1);
+ result = "1" + seprator + errorSb.toString();
+ } else if (sb.length() > 0)
+ {
+ sb.deleteCharAt(sb.length() - 1);// 去掉最后一个逗号
+ int lastIndex = sb.lastIndexOf(",");
+ String flag = "";
+ logger.debug("runExecGetResult lastIndex-->" + lastIndex);
+ if (lastIndex != -1)
+ {
+ // 配合运行命令(echo $?),最后一行为结果标识
+ flag = sb.substring(lastIndex + 1, sb.length()).trim();
+ sb.delete(lastIndex, sb.length());// 删除结果标识和其前面的逗号
+ } else
+ {
+ flag = sb.toString().trim();
+ sb.delete(0, sb.length());
+ }
+ logger.debug("runExecGetResult flag-->" + flag);
+ // 配合运行命令(echo $?):最后一行若是0,则执行成功,若非0,则失败
+ if ("0".equals(flag))
+ {
+ result = "0" + seprator + sb.toString();
+ } else
+ {
+ result = "1" + seprator + sb.toString();
+ }
+ }
+ logger.debug("runExecGetResult result-->" + result);
+ logger.debug("runExecGetResult end-------" + cmd);
+
+ return result;
+ } catch (Exception e)
+ {
+ throw e;
+ } finally
+ {
+ try
+ {
+ if (bReader != null)
+ {
+ bReader.close();
+ }
+ if (errorReader != null)
+ {
+ errorReader.close();
+ }
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (Exception e1)
+ {
+ }
+ }
+ }
+
+ /**
+ * 验证用户名或用户组是否存在
+ *
+ * @param username
+ * @param userGroup
+ * @return
+ * @throws Exception
+ */
+ public static boolean checkUserOrGroupExist(String username, String userGroup) throws Exception
+ {
+ try
+ {
+ boolean flag = false;
+ logger.debug("checkUserOrGroupExist start-------");
+ String os = System.getProperty("os.name");// 根据操作系统确定运行方式
+ if (os.startsWith("Windows"))
+ {
+ flag = true;
+ } else if (os.startsWith("Linux"))
+ {
+ if (username == null && userGroup == null)
+ {
+ flag = true;
+ } else
+ {
+ StringBuffer sb = new StringBuffer();
+ if (username != null)
+ {
+ sb.append("su " + username.trim() + ";");
+ }
+ if (userGroup != null)
+ {
+ sb.append("groups " + userGroup.trim() + ";");
+ }
+ if (execLinuxCmd(sb.toString()) == null)
+ {// 没有返回值,验证通过
+ flag = true;
+ }
+ }
+ } else
+ {
+ throw new IOException("unknown operating system: " + os);
+ }
+
+ logger.debug("checkUserOrGroupExist end-------");
+
+ return flag;
+ } catch (Exception e)
+ {
+ throw e;
+ }
+
+ }
+
+ /**
+ * 验证用户名和密码是否正确,调用check_userpass.sh脚本
+ *
+ * @param username
+ * @param passwd
+ */
+ public static boolean checkUserPass(String username, String passwd) throws Exception
+ {
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ try
+ {
+ boolean flag = false;
+ logger.debug("checkUserPass start-------");
+ String os = System.getProperty("os.name");// 根据操作系统确定运行方式
+ if (os.startsWith("Windows"))
+ {
+ flag = true;
+ } else if (os.startsWith("Linux"))
+ {
+ File file = new File(CHECK_USERPASS_FILE);
+ StringBuffer sb = new StringBuffer();
+ sb.append(file.getCanonicalPath() + " " + Utils.getLocalIp());
+ if (username != null)
+ {
+ sb.append(" " + username.trim());
+ if (passwd != null)
+ {
+ sb.append(" " + DESUtil.desDecrypt(passwd.trim()));
+ }
+ }
+ sb.append(" >/dev/null 2>&1;");
+ sb.append("echo $?");
+
+ String[] cmdArr = new String[] { "/bin/bash", "-c", sb.toString() };
+ process = Runtime.getRuntime().exec(cmdArr);
+ process.getOutputStream().close();
+ bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ while ((line = bReader.readLine()) != null)
+ {
+ logger.debug("checkUserPass line-------" + line);
+ if (line.trim().equals("0"))
+ {
+ flag = true;
+ }
+ }
+ while ((line = errorReader.readLine()) != null)
+ {
+ logger.debug("checkUserPass error line--->" + line);
+ }
+ } else
+ {
+ throw new IOException("unknown operating system: " + os);
+ }
+
+ logger.debug("runExecGetResult end-------");
+
+ return flag;
+ } catch (Exception e)
+ {
+ throw e;
+ } finally
+ {
+ try
+ {
+ if (bReader != null)
+ {
+ bReader.close();
+ }
+ if (errorReader != null)
+ {
+ errorReader.close();
+ }
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (Exception e1)
+ {
+ }
+ }
+ }
+
+ /**
+ * 检查文件或命令是否存在且可执行
+ *
+ * @param cmd
+ * @return true 是,false 否
+ * @throws IOException
+ */
+ public static boolean isFileOrCmdExist(String cmd) throws IOException
+ {
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ boolean flag = false;
+ logger.debug("isFileOrCmdExist start-------" + cmd);
+ try
+ {
+ // 根据操作系统确定运行方式
+ String os = System.getProperty("os.name");
+ if (os.startsWith("Windows"))
+ {
+ logger.debug("isFileOrCmdExist Windows-------" + cmd);
+ // 待实现: 目前只处理了文件,执行命令未实现判断
+ File startFile = new File(cmd);
+ if (startFile.exists() && startFile.canExecute())
+ {
+ flag = true;
+ }
+ } else if (os.startsWith("Linux"))
+ {
+ String cmd1 = "[ -x " + cmd + " ] || which " + cmd + ";echo $?";
+ logger.debug("isFileOrCmdExist linux-------" + cmd1);
+ String[] shellCmd = new String[] { "/bin/bash", "-c", cmd1 };
+ process = Runtime.getRuntime().exec(shellCmd);
+ process.getOutputStream().close();
+
+ bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ while ((line = bReader.readLine()) != null)
+ {
+ logger.debug("isFileOrCmdExist linux--->" + line);
+ if (line.trim().equals("0"))
+ {
+ flag = true;
+ }
+ }
+ while ((line = errorReader.readLine()) != null)
+ {
+ logger.debug("isFileOrCmdExist linux error--->" + line);
+ }
+ } else
+ {
+ throw new IOException("unknown operating system: " + os);
+ }
+
+ } catch (Exception e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ return false;
+ } finally
+ {
+ try
+ {
+ if (bReader != null)
+ {
+ bReader.close();
+ }
+ if (errorReader != null)
+ {
+ errorReader.close();
+ }
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (Exception e1)
+ {
+ }
+ }
+ logger.debug("isFileOrCmdExist end-------" + cmd);
+
+ return flag;
+ }
+
+ /**
+ *
+ * TODO 处理路径中带有空格 括号的问题 在外部加入""
+ *
+ * @author jinshujuan May 30, 2013
+ * @version 1.0
+ * @param str
+ * @return
+ */
+ public static String handlerWinPath(String str)
+ {
+
+ if (str != null && !str.equals(""))
+ {
+ if (str.indexOf(" ") != -1 || str.indexOf("(") != -1 || str.indexOf(")") != -1)
+ {
+ str = "\"" + str + "\"";
+ }
+ }
+ logger.debug("handlerWinPath---str=" + str);
+ return str;
+ }
+
+ /**
+ * 对Windows下路径中带空格的特殊处理
+ *
+ * @param str
+ * @return
+ */
+ public static String handlerWinSpace(String str)
+ {
+ /*
+ * 注意::若最后一级路径出现空格,处理上的存在Bug -- 需要在最后一级也加上\\或/ 如:xcopy /y D:\\Program
+ * Files\\Test 1\\ D:\\Program Files\\Test 2\\ /s/e 可以正常替换空格 xcopy /y
+ * D:\\Program Files\\Test 1 D:\\Program Files\\Test 2 /s/e
+ * 不能正常替换空格,最后一级Test 1和Test 2中的空格替换不了。
+ */
+ if (str != null)
+ {
+ if (str.indexOf(":\\") != -1)
+ {
+ // 针对这样的命令, 如:
+ // D:\Program Files\Test\test.bat >> D:\Program Files\test.log;
+ // xcopy /y D:\Program Files\Test D:\Program Files\Test2 /s/e
+ // 先取第一个:\之后,每次再取与\之间的串循环替换空格
+ // 若与\之间的串中有:\(/test.bat >> D:/, /Test D:/)则不用替换空格
+ int index = str.indexOf(":\\");
+ String start = str.substring(0, index + 2);
+ String end = str.substring(index + 2, str.length());
+ while (end.indexOf("\\") != -1)
+ {
+ index = end.indexOf("\\");
+ String middle = end.substring(0, index + 1);
+ if (middle.endsWith(":\\"))
+ {
+ start += middle;
+ } else
+ {
+ start += middle.replace(" ", "\" \"");
+ }
+ end = end.substring(index + 1, end.length());
+ }
+ start += end;
+ str = start;
+ } else if (str.indexOf(":/") != -1)
+ {
+ // 针对这样的命令, 如:
+ // D:/Program Files/Test/test.bat >> D:/Program Files/test.log;
+ // xcopy /y D:/Program Files/Test D:/Program Files/Test2 /s/e
+ // 先取第一个:/之后,每次再取与/之间的串循环替换空格
+ // 若与/之间的串中有:/(/test.bat >> D:/, /Test D:/)或 /(/Test2 /)则不用替换空格
+ int index = str.indexOf(":/");
+ String start = str.substring(0, index + 2);
+ String end = str.substring(index + 2, str.length());
+ while (end.indexOf("/") != -1)
+ {
+ index = end.indexOf("/");
+ String middle = end.substring(0, index + 1);
+ if (middle.endsWith(":/") || middle.endsWith(" /"))
+ {
+ start += middle;
+ } else
+ {
+ start += middle.replace(" ", "\" \"");
+ }
+ end = end.substring(index + 1, end.length());
+ }
+ start += end;
+ str = start;
+ }
+ }
+ logger.debug("handlerWinSpace---str=" + str);
+ return str;
+ }
+
+ /**
+ * 对Linux下路径中带空格的特殊处理
+ *
+ * @param str
+ * @return
+ */
+ public static String handlerLinuxSpace(String str)
+ {
+ if (str != null)
+ {
+ str = str.trim().replace(" ", "\\ ");
+ }
+ return str;
+ }
+
+ /**
+ * 根据关键字查找进程PID
+ *
+ * @param procSearchKey
+ * @return pid列表
+ * @throws Exception
+ */
+ public static List<String> getProcessIdBySearchKey(String procSearchKey) throws Exception
+ {
+ List<String> value = null;
+ // 根据操作系统确定获取进程ID的方式
+ String os = System.getProperty("os.name");
+ if (os.startsWith("Windows"))
+ {
+ value = getWindowsProcessId(procSearchKey);
+ } else if (os.startsWith("Linux"))
+ {
+ value = getLinuxProcessId(procSearchKey);
+ } else
+ {
+ throw new IOException("unknown operating system: " + os);
+ }
+
+ return value;
+ }
+
+ /**
+ * Windows下根据关键字查找进程,关键字不区分大小写
+ *
+ * @param procSearchKey
+ * @return
+ */
+ public static List<String> getWindowsProcessId(String procSearchKey)
+ {
+ // "wmic process get
+ // Caption,commandLine,Description,ExecutablePath,Name,processId|findstr
+ // /i " + procSearchKey + "|findstr /v findstr"
+ String[] cmd = new String[] {
+ "cmd.exe",
+ "/C",
+ "wmic process where \"Caption like '%%" + procSearchKey
+ + "%%' or CommandLine like '%%" + procSearchKey
+ + "%%' or Description like '%%" + procSearchKey
+ + "%%' or ExecutablePath like '%%" + procSearchKey + "%%' or Name like '%%"
+ + procSearchKey
+ + "%%'\" get Name,ProcessId,CommandLine|findstr /v wmic|findstr /v findstr" };
+ logger.info("getWindowsProcessId-----" + cmd[2]);
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ List<String> processIDList = null;
+ try
+ {
+ synchronized (oWin)
+ {
+ process = Runtime.getRuntime().exec(cmd);
+ process.getOutputStream().close();
+ bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ processIDList = new ArrayList<String>();
+ while ((line = bReader.readLine()) != null)
+ {
+ logger.debug("getWindowsProcessId ---- line >> " + line);
+ String[] tmp = line.split("\\s{2,}");
+ if (tmp == null)
+ {
+ continue;
+ }
+ for (int i = 0; i < tmp.length; i++)
+ {
+ if (tmp[i].matches("\\d+"))
+ {
+ processIDList.add(tmp[i]);
+ }
+ }
+ }
+ while ((line = errorReader.readLine()) != null)
+ {
+ logger.debug("getWindowsProcessId error line--->" + line);
+ }
+ }
+
+ } catch (IOException e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ return null;
+ } finally
+ {
+ try
+ {
+ if (bReader != null)
+ {
+ bReader.close();
+ }
+ if (errorReader != null)
+ {
+ errorReader.close();
+ }
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (IOException e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ }
+ }
+
+ return processIDList;
+ }
+
+ /**
+ * Linux下根据关键字查找进程,关键字不区分大小写
+ *
+ * @param procSearchKey
+ * @return
+ */
+ public static List<String> getLinuxProcessId(String procSearchKey)
+ {
+ String cmd = "ps -ef | grep -i '" + procSearchKey.trim()
+ + "' | grep -v grep | awk '{print $2}'";
+ logger.info("getLinuxProcessId-----" + cmd);
+ String[] shellCmd1 = new String[] { "/bin/bash", "-c", cmd };
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ List<String> processIDList = null;
+ synchronized (oLinux)
+ {
+ try
+ {
+ // 找到根据进程名获取到的进程号列表
+ process = Runtime.getRuntime().exec(shellCmd1);
+ process.getOutputStream().close();
+
+ bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String line = null;
+ processIDList = new ArrayList<String>();
+ while ((line = bReader.readLine()) != null)
+ {
+ processIDList.add(line);
+ logger.debug("getLinuxProcessId ---- line >> " + line);
+ }
+ while ((line = errorReader.readLine()) != null)
+ {
+ logger.debug("getLinuxProcessId error line--->" + line);
+ }
+ } catch (IOException e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ } finally
+ {
+ try
+ {
+ if (bReader != null)
+ {
+ bReader.close();
+ }
+ if (errorReader != null)
+ {
+ errorReader.close();
+ }
+ if (process != null)
+ {
+ process.destroy();
+ }
+ } catch (IOException e)
+ {
+ logger.error(Utils.printExceptionStack(e));
+ }
+ }
+
+ }
+ return processIDList;
+ }
+
+ /**
+ * 检查PID是否存在,存在返回PID,不存在返回描述信息
+ * 检查逻辑:先检查PID文件,取出PID,验证PID指定进程是否存在,不存在再使用搜索关键字查找进程 isExistFlag: 0 进程不存在,1
+ * 进程存在且仅找到一个,2 进程存在且找到多个
+ *
+ * @return 数组:{进程是否存在的标识(0|1|2), 进程PID或者描述信息}
+ */
+ public static Object[] checkPidAndGetPid(String pidFile, String procSearchKey) throws Exception
+ {
+ int isExistFlag = 0;
+ String pidInfo = "";
+ if (pidFile != null && !"".equals(pidFile))
+ {
+ File file = new File(pidFile);
+ if (file.exists())
+ {
+ String[] pidArr = ProcessUtil.getProcessIdByFile(file);
+ if (pidArr != null && pidArr.length > 0)
+ {// 目前考虑只有一个PID的情况
+ boolean isExist = ProcessUtil.isProcessExistByPid(pidArr[0]);
+ if (isExist)
+ {
+ pidInfo = pidArr[0];
+ isExistFlag = 1;
+ } else
+ {
+// pidInfo = "进程PID\"" + pidArr[0] + "\"不存在";
+ pidInfo = "i18n_client.ProcessUtil.processPid_n81i\"" + pidArr[0] + "\"i18n_client.ProcessUtil.notExists_n81i";
+ }
+ }
+ } else
+ {
+// pidInfo = "PID文件\"" + file.getAbsolutePath() + "\"不存在";
+ pidInfo = "i18n_client.ProcessUtil.pidFile_n81i\"" + file.getAbsolutePath() + "\"i18n_client.ProcessUtil.notExists_n81i";
+ }
+ } else
+ {
+// pidInfo = "PID文件字段为空";
+ pidInfo = "i18n_client.ProcessUtil.pidFieldNull_n81i";
+ }
+
+ if (isExistFlag == 0 && procSearchKey != null && !"".equals(procSearchKey))
+ {
+ // PID文件或PID文件中的PID不存在,则使用进程搜索关键字查找PID
+ List<String> pidList = ProcessUtil.getProcessIdBySearchKey(procSearchKey);
+ if (pidList == null || pidList.size() == 0)
+ {
+// pidInfo += (pidInfo.length() > 0 ? ", " : "") + "进程搜索关键字" + procSearchKey + "未找到进程";
+ pidInfo += (pidInfo.length() > 0 ? ", " : "") + "i18n_client.ProcessUtil.searchKey_n81i" + procSearchKey + "i18n_client.ProcessUtil.noProcess_n81i";
+ } else if (pidList.size() > 1)
+ {
+ pidInfo += (pidInfo.length() > 0 ? ", " : "") + "i18n_client.ProcessUtil.searchKey_n81i" + procSearchKey
+ + " i18n_client.ProcessUtil.findTooMuch_n81i";
+ isExistFlag = 2;
+ } else
+ {// 只找到一个进程
+ pidInfo = pidList.get(0);
+ isExistFlag = 1;
+ }
+ }
+
+ return new Object[] { isExistFlag, pidInfo };
+ }
+
+ /*
+ * public static String getProcessId(String processName, String processPath)
+ * throws Exception{ String value = null; //根据操作系统确定获取进程ID的方式 String os =
+ * System.getProperty("os.name"); if (os.startsWith("Windows")) { value =
+ * getWindowsProcessId(processName, processPath); }else if
+ * (os.startsWith("Linux")){ value = getLinuxProcessId(processName,
+ * processPath); } else { throw new IOException("unknown operating system: " +
+ * os); }
+ *
+ * return value; }
+ *
+ * public static String getWindowsProcessId(String procName, String
+ * procPath) { String[] cmd = new String[] { "cmd.exe", "/C", "wmic process
+ * where \"name='" + procName.trim() + "' and executablepath='" +
+ * procPath.trim().replace("\\", "\\\\") + "'\" get processid" };// list
+ * full logger.debug("cmd-----"+cmd[2]); BufferedReader bReader = null;
+ * Process process = null; String processId = null; try { synchronized
+ * (oWin) { process = Runtime.getRuntime().exec(cmd);
+ * process.getOutputStream().close(); bReader = new BufferedReader(new
+ * InputStreamReader(process .getInputStream())); String line = null; while
+ * ((line = bReader.readLine()) != null) { logger.debug("line-----" + line);
+ * if (line.trim().matches("\\d+")) { processId = line.trim(); } } } } catch
+ * (IOException e) { logger.error(Utils.printExceptionStack(e)); return
+ * processId; }finally{ try { if (bReader != null) { bReader.close(); } if
+ * (process != null) { process.destroy(); } } catch (IOException e) {
+ * logger.error(Utils.printExceptionStack(e)); } }
+ *
+ * return processId; }
+ *
+ * public static String getLinuxProcessId(String procName, String procPath) {
+ * String cmd = "ps -ef | grep '" + procName.trim() + "' | grep -v grep |
+ * awk '{print $2}'"; String[] shellCmd1 = new String[] { "/bin/bash", "-c",
+ * cmd }; String[] shellCmd2 = new String[] { "/bin/bash", "-c", cmd };
+ * BufferedReader bReader = null; List<String> processIDList = null;
+ * Process process = null; synchronized (oLinux) { try { // 找到根据进程名获取到的进程号列表
+ * process = Runtime.getRuntime().exec(shellCmd1);
+ * process.getOutputStream().close();
+ *
+ * bReader = new BufferedReader(new InputStreamReader(process
+ * .getInputStream())); String line = null; processIDList = new ArrayList<String>();
+ * while ((line = bReader.readLine()) != null) { processIDList.add(line); } }
+ * catch (IOException e) { logger.error(Utils.printExceptionStack(e)); }
+ * finally { try { if (bReader != null) { bReader.close(); } if (process !=
+ * null) { process.destroy(); } } catch (IOException e) {
+ * logger.error(Utils.printExceptionStack(e)); } }
+ *
+ * for (int i = 0; i < processIDList.size(); i++) { shellCmd2 = new String[] {
+ * "/bin/bash", "-c", "lsof -p " + processIDList.get(i) + " | grep 'txt'
+ * |grep -v grep | awk '{print $NF}'" }; try { process =
+ * Runtime.getRuntime().exec(shellCmd2); process.getOutputStream().close();
+ * bReader = new BufferedReader(new InputStreamReader(process
+ * .getInputStream())); String line = null; while ((line =
+ * bReader.readLine()) != null) { if (line.trim().equals(procPath.trim()))
+ * return processIDList.get(i); } } catch (IOException e) {
+ * logger.error(Utils.printExceptionStack(e)); } finally { try { if (bReader !=
+ * null) { bReader.close(); } if (process != null) { process.destroy(); } }
+ * catch (IOException e) { logger.error(Utils.printExceptionStack(e)); } }
+ * }//for end } return null; }
+ */
+
+}
diff --git a/src/com/nis/nmsclient/util/RarUtil.java b/src/com/nis/nmsclient/util/RarUtil.java
new file mode 100644
index 0000000..d394411
--- /dev/null
+++ b/src/com/nis/nmsclient/util/RarUtil.java
@@ -0,0 +1,125 @@
+package com.nis.nmsclient.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.log4j.Logger;
+
+import de.innosystec.unrar.Archive;
+import de.innosystec.unrar.rarfile.FileHeader;
+
+/**
+ * 对rar进行解压缩
+ *
+ */
+public class RarUtil {
+ static Logger logger = Logger.getLogger(RarUtil.class);
+ /**
+ * 对单个rar压缩包解压
+ * @param rarFileName 需要解压的rar文件
+ * @param destDir 解压后的目标目录
+ * @throws Exception
+ */
+ public static void unRar(String rarFileName, String destDir)
+ throws Exception {
+ logger.debug("unRar start……");
+ Archive archive = null;
+ FileHeader fh = null;
+ try {
+ logger.debug("unRar rarFileName---" + rarFileName);
+ logger.debug("unRar destDir---" + destDir);
+ File file = new File(rarFileName);
+ if(!file.exists()){
+// throw new Exception("解压源文件不存在: " + file.getAbsolutePath());
+ throw new Exception("Unzip source file does not exist: " + file.getAbsolutePath());
+ }
+ logger.debug("unRar: get archive……");
+ archive = new Archive(file);
+ logger.debug("unRar: archive =" + archive);
+ if (archive != null) {
+ logger.debug("unRar: while start");
+ int index = 0;
+ while ((fh = archive.nextFileHeader()) != null) {
+ logger.debug("unRar: " + ++index + " start");
+ String fileName = fh.getFileNameW().trim();
+ if (!existZH(fileName)) {
+ fileName = fh.getFileNameString().trim();
+ }
+ String path = (destDir + File.separator + fileName)
+ .replaceAll("\\\\", "/");
+
+ logger.debug("unRar: path---" + path);
+ if (fh.isDirectory()) {
+ //logger.debug("unRar: FileHeader is directory");
+ int end = path.lastIndexOf("/");
+ if (end != -1) {
+ File dir = new File(path.substring(0, end));
+ if (!dir.exists()) {
+ dir.mkdirs();
+ }
+ }
+ }else{
+ //logger.debug("unRar: FileHeader is file");
+ FileOutputStream os = null;
+ try{
+ File out = new File(path);
+ if(!out.getParentFile().exists()){
+ out.getParentFile().mkdirs();
+ }
+ os = new FileOutputStream(out);
+ archive.extractFile(fh, os);
+ }catch (Exception e) {
+ throw e;
+ }finally{
+ fh = null;
+ if (os != null) {
+ os.close();
+ os = null;
+ }
+ }
+ }
+ logger.debug("unRar: " + index + " end");
+ }
+ logger.debug("unRar: while end");
+ }
+ logger.debug("unRar end……");
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ fh = null;
+ try {
+ if (archive != null) {
+ archive.close();
+ archive = null;
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ }
+
+ public static boolean existZH(String str) {
+ String regEx = "[\\u4e00-\\u9fa5]";
+ Pattern p = Pattern.compile(regEx);
+ Matcher m = p.matcher(str);
+ while (m.find()) {
+ return true;
+ }
+ return false;
+ }
+
+ public static void main(String[] args) {
+ try {
+ unRar("D:\\temp\\logs.rar", "D:\\temp\\log");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/src/com/nis/nmsclient/util/StringUtil.java b/src/com/nis/nmsclient/util/StringUtil.java
new file mode 100644
index 0000000..cf0b551
--- /dev/null
+++ b/src/com/nis/nmsclient/util/StringUtil.java
@@ -0,0 +1,528 @@
+/*
+ * @(#)StringUtil.java 1.0
+ *
+ * Copyright 2010 NIS, Inc. All rights reserved.
+ *
+ */
+package com.nis.nmsclient.util;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.util.Collection;
+import java.util.Map;
+import java.util.UUID;
+
+import sun.misc.BASE64Encoder;
+
+
+/**
+*
+* <p>字符串处理工具类.</p>
+* @author 中科智源育成信息有限公司 E-mail: [email protected]
+* @version 1.0 创建时间:Nov 2, 2010 2:57:56 PM
+*
+*/
+public final class StringUtil {
+ /**
+ * ISO8859_1 编码集
+ */
+ public static final String CODE_ISO8859_1 = "ISO8859_1";
+ /**
+ * GB2312 编码集
+ */
+ public static final String CODE_GB2312 = "GB2312";
+ /**
+ * GBK 编码集
+ */
+ public static final String CODE_GBK = "GBK";
+ /**
+ * UTF-8 编码集
+ */
+ public static final String CODE_UTF_8 = "UTF-8";
+
+ private static int size = 0;
+
+ private static final String[] SIMPLIFIED_CASE = { "O", "一", "二", "三", "四", "五",
+ "六", "七", "八", "九", "十" };
+// private static final String[] SIMPLIFIED_CASE = { "Zero", "One", "Two", "Three", "Four", "Five",
+// "Six", "Seven", "Eight", "Nine", "Ten" };
+
+ private static final String[] TRADITIONAL_CASE = { "零", "壹", "贰", "叁", "肆", "伍",
+ "陆", "柒", "捌", "玖", "拾" };
+// private static final String[] TRADITIONAL_CASE = { "Zero", "One", "Two", "Three", "Four", "Five",
+// "Six", "Seven", "Eight", "Nine", "Ten" };
+
+ /**
+ *<p>Description:抑制默认的构造器,避免实例化对象 </p>
+ */
+ private StringUtil() {
+
+ }
+
+ /**
+ *
+ * <p>判断一个对象是否为空</p>
+ * <p>
+ * <code>object</code>元素判断所有对象是否为空.
+ * 另外对{@link String}、{@link Collection} 、{@link Map} 进行长度验证,如果长度为0,视为空对象.
+ * </p>
+ * <pre>
+ * String aa = " ";
+ * List list = new ArrayList()
+ * LinkedHashSet set = new LinkedHashSet();
+ * StringUtil.isEmpty(aa) = true
+ * StringUtil.isEmpty(list) = true
+ * StringUtil.isEmpty(set) = true
+ * StringUtil.isEmpty("\t") = true
+ * </pre>
+ * @param object 对象元素
+ * @return <code>true</code> 对象为<code>null</code>,<code>false</code> 对象不为<code>null</code>.
+ */
+ public static boolean isEmpty(Object object) {
+ initSize(object);
+ return size==0;
+
+ }
+
+
+ /**
+ *
+ * 判断对象是否有数据存在? 不存在为0、存在不为0的值.
+ * @param object 对象值
+ */
+ private static void initSize(Object object){
+
+ if (object == null) {
+ size = 0;
+ } else {
+ if (object instanceof String) {
+ size = ((String)object).trim().length();
+ } else if (object instanceof Collection) {
+ size = ((Collection)object).size();
+ } else if (object instanceof Map) {
+ size = ((Map)object).size();
+ //其他数据类型
+ } else {
+ size = 1;
+ }
+
+ }
+
+ }
+
+ /**
+ *
+ * <p>如果对象为空时,返回默认值.</p>
+ * @param object 要判断是否为空的对象
+ * @param defaultValue 为空时设的默认值
+ * @see #isEmpty(Object)
+ * @return 获取处理后的数据
+ */
+ public static Object setDefaultValueIfNull(Object object,Object defaultValue){
+ if(isEmpty(object)){
+ return defaultValue;
+ }
+ return object;
+ }
+
+ /**
+ *
+ * <p>对字符串进行MD5加密.</p>
+ * <p>
+ * 一般作为密码的处理方式,首先通过MD5进行加密,然后将字符串进行Base64编码获得所需字符.
+ * </p>
+ * <pre>
+ * String str = "ceshi";
+ * StringUtil.md5(str) = "zBfDDNERxyFfyPUfh5Dg4Q=="
+ * </pre>
+ * @param msg 要加密的字符串
+ * @return 返回加密后的25位字符,如果解析出现异常将返回<code>null</code>.
+ */
+ public static String md5(String msg) {
+ try {
+ MessageDigest md = MessageDigest.getInstance("MD5");
+ byte[] b = md.digest(msg.getBytes());
+ BASE64Encoder encoder = new BASE64Encoder();
+ String code = encoder.encode(b);
+ return code;
+ } catch (Exception e) {
+ return null;
+ }
+
+ }
+
+ /**
+ * <p>截取处理字符串,当字符串超过指定的截取长度时,用“......”补充</p>
+ * <pre>
+ * String str = "中华人民共和国";
+ * StringUtil.getMoreString(str, 6) = "中华人民共和......"
+ * </pre>
+ * @param text 字符串数据
+ * @param length 截取的长度值
+ * @return 返回处理后字符
+ */
+ public static String getMoreString(String text,int length){
+ StringBuilder textBuilder = new StringBuilder();
+
+ if(isEmpty(text)){
+ return null;
+ }
+ if(text.length()>length){
+ text = text.substring(0,length);
+ textBuilder.append(text).append("......");
+ }else {
+ textBuilder.append(text);
+ }
+
+
+ return textBuilder.toString();
+ }
+
+
+ /**
+ *
+ * <p>通过给定url获取域名地址.</p>
+ * <p>
+ * 获得域名信息需去除 http/https/ftp 与 www 一些头信息,获取有效地址.
+ * </p>
+ * <pre>
+ * StringUtil.getDomain("http://www.baidu.com") = "baidu.com"
+ * </pre>
+ * @param webSiteUrl url 地址
+ * @return 返回截取后的域名地址
+ */
+ public static String getDomain(String webSiteUrl) {
+ String url = "";
+
+ if(isEmpty(webSiteUrl)){
+ return url;
+ }
+
+
+ if (webSiteUrl.indexOf("http://") >= 0) {
+ url = webSiteUrl.substring("http://".length(), webSiteUrl.length());
+ } else if (webSiteUrl.indexOf("https://", 0) >= 0) {
+ url = webSiteUrl.substring("https://".length(), webSiteUrl.length());
+ } else if (webSiteUrl.indexOf("ftp://", 0) >= 0) {
+ url = webSiteUrl.substring("ftp://".length(), webSiteUrl.length());
+ } else {
+ url = webSiteUrl;
+ }
+
+ if (url.indexOf("/", 0) >= 0) {
+ url = url.substring(0, url.indexOf("/", 1));
+ }
+ if (url.indexOf("www.") == 0) {
+ url = url.substring(url.indexOf(".") + 1, url.length());
+ }
+ if (url.indexOf("?") >= 0) {
+ url = url.substring(0, url.indexOf("?"));
+ }
+
+ return url;
+ }
+
+ /**
+ *
+ * <p>按照给定规则分隔字符串</p>
+ * <pre>例子说明:</pre>
+ * @param str 需要分隔的字符串
+ * @param regex 分隔规则
+ * @return 返回字符串数组,如果分隔字符串为空返回<code>null</code>.
+ */
+ public static String[] Split(String str,String regex) {
+
+ if(StringUtil.isEmpty(str)){
+ return null;
+ }
+
+ return str.split(regex);
+
+ }
+
+ /**
+ *
+ * <p>字符编码转换,需要提供字符串的源编码格式.</p>
+ * <p>
+ * 字符串工具类中提供一些字符编码常量:
+ * {@link #CODE_GB2312}\{@link #CODE_GBK}\{@link #CODE_ISO8859_1}\{@link #CODE_UTF_8}
+ * </p>
+ * @param value 要编码的值
+ * @param sourceCodingFormat 字符的原始编码格式,具体编码格式可看本类提供的编码样式.
+ * @param destCodingFormat 要转换字符的编码格式,具体编码格式可看本类提供的编码样式.
+ * @return 返回编码后的字符串.
+ * @throws UnsupportedEncodingException
+ */
+ public static String getCodingConversionResult(String value,String sourceCodingFormat,
+ String destCodingFormat ) throws UnsupportedEncodingException{
+
+ if(isEmpty(value)){
+ return null;
+ }
+
+
+ return new String(value.getBytes(sourceCodingFormat), destCodingFormat);
+ }
+
+ /**
+ *
+ * <p>将url转为utf编码格式url,当url符合utf8格式,不会转换.</p>
+ * <pre>
+ * StringUtil.getUTF8URLEncode("http://www.baidu.com/s?param='中国'") =
+ * "http%3A%2F%2Fwww.baidu.com%2Fs%3Fparam%3D%27%E4%B8%AD%E5%9B%BD%27"
+ * </pre>
+ * @see #getUTF8URLDecode(String)
+ * @param url 字符串url
+ * @return 返回utf8转换后的字符url
+ * @throws UnsupportedEncodingException
+ */
+ public static String getUTF8URLEncode(String url)throws UnsupportedEncodingException{
+ if(isUtf8Url(url)){
+ return url;
+ }
+
+ return URLEncoder.encode(url, StringUtil.CODE_UTF_8);
+
+ }
+
+ /**
+ *
+ * <p>将utf8编码的url解析为原始url.当url不符合utf8格式时,不转换.</p>
+ * <pre>例子说明:</pre>
+ * @see #getUTF8URLEncode(String)
+ * @param url 字符串url
+ * @return 返回解析后字符url
+ * @throws UnsupportedEncodingException
+ */
+
+ public static String getUTF8URLDecode(String url)throws UnsupportedEncodingException{
+
+ /*if(!isUtf8Url(url)){
+ return url;
+ }*/
+
+ return URLDecoder.decode(url, StringUtil.CODE_UTF_8);
+
+ }
+
+
+ /** * 编码是否有效
+ * @param text
+ * @return
+ */
+ private static boolean Utf8codeCheck(String text){
+ String sign = "";
+ if (text.startsWith("%e")){
+
+ for (int i = 0, p = 0; p != -1; i++) {
+ p = text.indexOf("%", p);
+
+ if (p != -1){
+ p++;
+ }
+ sign += p;
+ }
+ }
+
+ return sign.equals("147-1");
+ }
+
+ /**
+ * 是否Utf8Url编码
+ * @param text
+ * @return true or false
+ */
+ private static boolean isUtf8Url(String text) {
+ text = text.toLowerCase();
+ int p = text.indexOf("%");
+
+ if (p != -1 && text.length() - p > 9) {
+ text = text.substring(p, p + 9);
+ }
+
+ return Utf8codeCheck(text);
+ }
+
+
+ /**
+ *
+ * <p>判断字符串是否是数字格式(包括小数形式).</p>
+ * <pre>
+ * String a1 = "12";
+ * String a2 = "0.01";
+ * String a3 = "0.0.1";
+ * String a4 = "123a";
+ * StringUtil.isNumeric(a1) = true
+ * StringUtil.isNumeric(a2) = true
+ * StringUtil.isNumeric(a3) = false
+ * StringUtil.isNumeric(a4) = false
+ * </pre>
+ * @param numberString 数字格式字符串
+ * @return <code>true</code> 符合数字格式(包括小数),<code>false</code> 不符合数字格式.
+ */
+ public static boolean isNumeric(String numberString){
+
+ if(isEmpty(numberString)){
+ return false;
+ }
+
+ if(numberString.startsWith(".")||numberString.endsWith(".")){
+ return false;
+ }
+
+ int length = numberString.split("\\.").length-1; //判断小数点在字符串中出现的次数。
+
+
+ if(length>1) { //小数点大于1次,不符合数字规范
+
+ return false;
+ }
+
+
+ for(int i=0; i<numberString.length(); i++){
+ if(!Character.isDigit(numberString.charAt(i))&&!".".equals(String.valueOf(numberString.charAt(i)))){
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ *
+ * <p>将字符串数字转换为简体大写中文格式.</p>
+ * <pre>
+ * StringUtil.convertSimplifiedCase("325") = ”三二五"
+ * </pre>
+ * @param numberString 数字字符串
+ * @return 返回简体大写后的数字
+ */
+ public static String convertSimplifiedCase(String numberString) {
+
+ StringBuilder simplifiedBuilder = new StringBuilder();
+
+ if(isEmpty(numberString)){
+ return null;
+ }
+
+
+ for (int i = 0; i < numberString.length(); i++) {
+ String tempNumberString = String.valueOf(numberString.charAt(i));
+ if ("0123456789".indexOf(tempNumberString) >= 0) {
+ int number = Integer.parseInt(tempNumberString);
+ simplifiedBuilder.append(SIMPLIFIED_CASE[number]);
+ } else {
+ simplifiedBuilder.append(tempNumberString);
+ }
+ }
+
+ return simplifiedBuilder.toString();
+ }
+
+
+ /**
+ *
+ * <p>把字符串中的数字转换成繁体大写中文的格式.</p>
+ * <pre>
+ * StringUtil.convertTraditionalCase("325") = "叁贰伍"
+ * </pre>
+ * @param numberString 数字字符串
+ * @return 返回繁体大写后的数字
+ */
+ public static String convertTraditionalCase(String numberString) {
+
+ StringBuilder simplifiedBuilder = new StringBuilder();
+
+ if(isEmpty(numberString)){
+ return null;
+ }
+
+
+ for (int i = 0; i < numberString.length(); i++) {
+ String tempNumberString = String.valueOf(numberString.charAt(i));
+ if ("0123456789".indexOf(tempNumberString) >= 0) {
+ int number = Integer.parseInt(tempNumberString);
+ simplifiedBuilder.append(TRADITIONAL_CASE[number]);
+ } else {
+ simplifiedBuilder.append(tempNumberString);
+ }
+ }
+
+ return simplifiedBuilder.toString();
+ }
+
+ /**
+ *
+ * <p>创建唯一标识字符串.</p>
+ * <pre>
+ * StringUtil.createUUID() = "00000DAF3CFC4E0B8DF2D5BEACB14D75"
+ * </pre>
+ * @return 返回标识符字符串
+ */
+ public static String createUUID() {
+ String uuid = UUID.randomUUID().toString();
+ uuid = uuid.replace("-", "");
+ return uuid.toUpperCase();
+ }
+
+
+ /**
+ *
+ * <p>字符串过滤,负责将html的textarea属性获得的字符转换成html格式的字符集.</p>
+ * @param str 要解析的字符串
+ * @return 是解析后的字符串
+ */
+ public static String htmlFilter(String str) {
+ StringBuffer stringbuffer = new StringBuffer();
+ for (int i = 0; i < str.length(); i++) {
+ char c = str.charAt(i);
+ switch (c) {
+
+ case 39:
+ stringbuffer.append("&#039;");
+ break;
+
+ case 34:
+ stringbuffer.append("&quot;");
+ break;
+
+ case 60:
+ stringbuffer.append("&lt;");
+ break;
+
+ case 62:
+ stringbuffer.append("&gt;");
+ break;
+
+ case 38:
+ stringbuffer.append("&amp;");
+ break;
+
+ case 32:
+ stringbuffer.append("&#32;");
+ break;
+
+ case 10:
+ stringbuffer.append("<br>");
+ break;
+
+ case 8220:
+ stringbuffer.append("&ldquo;");
+ break;
+
+ case 8221:
+ stringbuffer.append("&rdquo;");
+ break;
+
+ default:
+ stringbuffer.append(c);
+ break;
+ }
+ }
+
+ return stringbuffer.toString();
+ }
+
+}
diff --git a/src/com/nis/nmsclient/util/Utils.java b/src/com/nis/nmsclient/util/Utils.java
new file mode 100644
index 0000000..97d5497
--- /dev/null
+++ b/src/com/nis/nmsclient/util/Utils.java
@@ -0,0 +1,323 @@
+package com.nis.nmsclient.util;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.util.Enumeration;
+import java.util.regex.Pattern;
+
+import org.apache.log4j.Logger;
+
+public class Utils {
+ static Logger logger = Logger.getLogger(Utils.class);
+
+ /**
+ * 获得本机IP
+ *
+ * @return
+ */
+ public static String getLocalIp() {
+ String nativeip = "";
+ try {
+ //根据操作系统确定获取进程ID的方式
+ String os = System.getProperty("os.name");
+ if (os.startsWith("Windows")) {
+ InetAddress ipv4 = InetAddress.getLocalHost();
+ nativeip = ipv4.getHostAddress().toString();
+ logger.debug("------getLocalIp--nativeip=" + nativeip);
+ }else if (os.startsWith("Linux")){
+ InetAddress ip = null;
+ boolean findIp = false;
+ // 根据网卡取本机配置的IP
+ Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
+ while (netInterfaces.hasMoreElements()) {
+ if (findIp) {
+ break;
+ }
+ NetworkInterface ni = netInterfaces.nextElement();
+ logger.debug("------getLocalIp--NetWorkName=" + ni.getName());
+ Enumeration<InetAddress> ips = ni.getInetAddresses();
+ while (ips.hasMoreElements())
+ ip = ips.nextElement();
+ logger.debug("------getLocalIp--ip.isSiteLocalAddress()="
+ + ip.isSiteLocalAddress());
+ logger.debug("------getLocalIp--ip.isLoopbackAddress()="
+ + ip.isLoopbackAddress());
+ logger.debug("------getLocalIp--HostAddress="
+ + ip.getHostAddress());
+ if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
+ && ip.getHostAddress().indexOf(":") == -1) {
+ findIp = true;
+ logger.debug("------findIp--" + ip.getHostAddress());
+ break;
+ }
+ }
+ if (ip != null) {
+ nativeip = ip.getHostAddress();
+ }
+ } else {
+ throw new IOException("unknown operating system: " + os);
+ }
+
+ } catch (Exception e) {
+ logger.error(Utils.printExceptionStack(e));
+ }
+
+ return nativeip;
+ }
+
+ public static String getOperateSystem() {
+ BufferedReader bReader = null;
+ BufferedReader errorReader = null;
+ Process process = null;
+ try {
+ String os = System.getProperty("os.name");//根据操作系统确定运行方式
+ String[] cmdArr = null;
+ if (os.startsWith("Windows")) {
+ cmdArr = new String[] { "cmd.exe", "/C", "ver"};
+ } else if (os.startsWith("Linux")) {
+ cmdArr = new String[] { "/bin/bash", "-c", "uname -r;uname -i;lsb_release -d| cut -d: -f2| cut -f2" };
+ } else {
+ throw new IOException("unknown operating system: " + os);
+ }
+ process = Runtime.getRuntime().exec(cmdArr);
+ process.getOutputStream().close();
+ bReader = new BufferedReader(new InputStreamReader(process
+ .getInputStream()));
+ errorReader = new BufferedReader(new InputStreamReader(process
+ .getErrorStream()));
+ String line = null;
+ StringBuffer sb = new StringBuffer();
+ while ((line = bReader.readLine()) != null) {
+ if(line.trim().length()>0){
+ sb.append(line.trim() + ",");
+ logger.debug("getOperateSystem right-->" + line);
+ }
+ }
+ while ((line = errorReader.readLine()) != null) {
+ logger.debug("getOperateSystem error-->" + line);
+ }
+ if(sb.length() > 0) {
+ if (os.startsWith("Windows")) {
+ String osInfo = System.getProperty("sun.arch.data.model");//32位 or 64 位
+ sb.append(osInfo+"i18n_client.Utils.bit_n81i");
+ }else {
+ sb.deleteCharAt(sb.length()-1);//去掉最后一个逗号
+ }
+ }
+
+
+ return sb.toString();
+ } catch (Exception e) {
+ logger.error("Get the exception of the operating system and the release version", e);
+ } finally {
+ try {
+ if (bReader != null) {
+ bReader.close();
+ }
+ if (errorReader != null) {
+ errorReader.close();
+ }
+ if (process != null) {
+ process.destroy();
+ }
+ } catch (Exception e1) {
+ }
+ }
+
+ return null;
+ }
+
+ public static boolean checkIP(String checkStr) {
+ try {
+ String number = checkStr.substring(0, checkStr.indexOf('.'));
+ if (Integer.parseInt(number) > 255 || Integer.parseInt(number) < 0) {
+ return false;
+ }
+ checkStr = checkStr.substring(checkStr.indexOf('.') + 1);
+ number = checkStr.substring(0, checkStr.indexOf('.'));
+ if (Integer.parseInt(number) > 255 || Integer.parseInt(number) < 0) {
+ return false;
+ }
+
+ checkStr = checkStr.substring(checkStr.indexOf('.') + 1);
+ number = checkStr.substring(0, checkStr.indexOf('.'));
+ if (Integer.parseInt(number) > 255 || Integer.parseInt(number) < 0) {
+ return false;
+ }
+ number = checkStr.substring(checkStr.indexOf('.') + 1);
+ if (Integer.parseInt(number) > 255 || Integer.parseInt(number) < 0) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ //测试IP地址是否合法
+ public static boolean isIp(String ipAddress){
+// String test = "([1-9]|[1-9]\\d|1\\d{2}|2[0-1]\\d|22[0-3])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
+// Pattern pattern = Pattern.compile(test);
+// Matcher matcher = pattern.matcher(ipAddress);
+// return matcher.matches();
+ String regex0 = "(2[0-4]\\d)" + "|(25[0-5])";
+ String regex1 = "1\\d{2}";
+ String regex2 = "[1-9]\\d";
+ String regex3 = "\\d";
+ String regex = "(" + regex0 + ")|(" + regex1 + ")|(" + regex2 + ")|(" + regex3 + ")";
+ regex = "(" + regex + ").(" + regex + ").(" + regex + ").(" + regex + ")";
+ String[] str = ipAddress.split("\\.");//根据@拆分IP地址
+ if (!Pattern.matches(regex, ipAddress))
+ return false;
+ else if(str!=null && str.length!=4){//如果IP地址拆分后的数组长度不为4则不是正确的IP地址
+ return false;
+ }else{
+ return true;
+ }
+ }
+ public static long ipToLong(String strIP)
+ //将127.0.0.1 形式的IP地址转换成10进制整数,这里没有进行任何错误处理
+ {
+ int j=0;
+ int i=0;
+ long [] ip=new long[4];
+ int position1=strIP.indexOf(".");
+ int position2=strIP.indexOf(".",position1+1);
+ int position3=strIP.indexOf(".",position2+1);
+ ip[0]=Long.parseLong(strIP.substring(0,position1));
+ ip[1]=Long.parseLong(strIP.substring(position1+1,position2));
+ ip[2]=Long.parseLong(strIP.substring(position2+1,position3));
+ ip[3]=Long.parseLong(strIP.substring(position3+1));
+ return (ip[0]<<24)+(ip[1]<<16)+(ip[2]<<8)+ip[3];
+ }
+ public static String longToIP(long longIP)
+ //将10进制整数形式转换成127.0.0.1形式的IP地址,按主机序
+ {
+ StringBuffer sb=new StringBuffer("");
+ sb.append(String.valueOf(longIP>>>24&0xFF));//直接右移24位
+ sb.append("."); //将高8位置0,然后右移16位
+ sb.append(String.valueOf((longIP&0x00FFFFFF)>>>16));
+ sb.append(".");
+ sb.append(String.valueOf((longIP&0x0000FFFF)>>>8));
+ sb.append(".");
+ sb.append(String.valueOf(longIP&0x000000FF));
+ //sb.append(".");
+ return sb.toString();
+ }
+ //将10进制整数形式转换成127.0.0.1形式的IP地址,按网络序
+ public static String longToNetIp(long longIP){
+ StringBuffer sb=new StringBuffer("");
+ sb.append(String.valueOf(longIP&0x000000FF));
+ sb.append(".");
+ sb.append(String.valueOf((longIP&0x0000FFFF)>>>8));
+ sb.append(".");//将高8位置0,然后右移16位
+ sb.append(String.valueOf((longIP&0x00FFFFFF)>>>16));
+ sb.append(".");
+ sb.append(String.valueOf(longIP>>>24&0xFF));//直接右移24位
+ //sb.append(".");
+ return sb.toString();
+ }
+ public static long netIpToLong(String strIP)
+ //将127.0.0.1 形式的IP地址转换成10进制整数,这里没有进行任何错误处理
+ {
+ int j=0;
+ int i=0;
+ long [] ip=new long[4];
+ int position1=strIP.indexOf(".");
+ int position2=strIP.indexOf(".",position1+1);
+ int position3=strIP.indexOf(".",position2+1);
+ ip[0]=Long.parseLong(strIP.substring(0,position1));
+ ip[1]=Long.parseLong(strIP.substring(position1+1,position2));
+ ip[2]=Long.parseLong(strIP.substring(position2+1,position3));
+ ip[3]=Long.parseLong(strIP.substring(position3+1));
+ return (ip[0])+(ip[1]<<8)+(ip[2]<<16)+(ip[3]<<24);
+ }
+ public static void main(String argus[]){
+ System.out.println(Utils.checkIP("10.a.1.1"));
+ System.out.println(Utils.isIp("10.1.1.1"));
+ }
+
+
+ public static String printExceptionStack(Exception e){
+ StackTraceElement[] ste = e.getStackTrace();
+ StringBuffer sb = new StringBuffer();
+ sb.append("\n\t" + e.toString() + "\n");
+ for(StackTraceElement element : ste){
+ sb.append("\t" + element.toString() + "\n");
+ }
+
+ return sb.toString();
+ }
+
+
+ /**
+ * 根据网口名称获取此网口的Ip地址
+ * @param ethName
+ * @return
+ */
+ public static String getIpAddressByEthName(String ethName) {
+ String ip = null;
+ try {
+ //根据端口名称获取网卡信息
+ NetworkInterface netWork = NetworkInterface.getByName(ethName);
+ //获取此网卡的ip地址,可能包含ipv4和ipv6
+ Enumeration<InetAddress> adds = netWork.getInetAddresses();
+ while (adds.hasMoreElements()) {
+ InetAddress add = adds.nextElement();
+ String ipStirng = add.getHostAddress();
+ // 如果Ip地址长度大于16,说明是ipv6格式地址
+ if (ipStirng.length() > 16) {
+ continue;
+ }
+ ip = ipStirng;
+ }
+ } catch (Exception e) {
+ logger.error("Getting IP address failure based on port name",e);
+ }
+ return ip;
+ }
+
+ /**
+ * 根据ip地址查找端口的名字
+ *
+ * @param ip
+ * @return
+ */
+ public static String getNetInterfaceNameByIp(String ip) {
+ byte[] ipArr = Utils.ipStringToByte(ip);
+ String name = null;
+ try {
+ NetworkInterface local = NetworkInterface
+ .getByInetAddress(InetAddress.getByAddress(ipArr));
+ name = local.getName();
+ } catch (Exception e) {
+ logger.error("Getting port name failure based on IP address", e);
+ }
+ return name;
+ }
+
+ /**
+ * 将string类型的ip地址,转换成数组类型,只支持ipv4
+ *
+ * @param ip
+ * @return
+ */
+ public static byte[] ipStringToByte(String ip) {
+ if (!Utils.isIp(ip)) {
+ logger.error("IP is not legal, can not be converted!");
+ return null;
+ }
+ String[] ipArr = ip.split("\\.");
+ byte[] result = new byte[4];
+ for (int i = 0; i < ipArr.length; i++) {
+ int tem = Integer.parseInt(ipArr[i]);
+ result[i] = (byte) tem;
+ }
+ return result;
+ }
+
+}
diff --git a/src/com/nis/nmsclient/util/ZipUtil.java b/src/com/nis/nmsclient/util/ZipUtil.java
new file mode 100644
index 0000000..ee8e984
--- /dev/null
+++ b/src/com/nis/nmsclient/util/ZipUtil.java
@@ -0,0 +1,321 @@
+package com.nis.nmsclient.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Enumeration;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.log4j.Logger;
+import org.apache.tools.zip.ZipEntry;
+import org.apache.tools.zip.ZipFile;
+import org.apache.tools.zip.ZipOutputStream;
+
+import com.nis.nmsclient.thread.socket.CommonSocket;
+import com.nis.nmsclient.thread.socket.ServerCollectData;
+
+public class ZipUtil {
+ static Logger logger = Logger.getLogger(ZipUtil.class);
+ /**
+ * java 解压缩单个zip压缩包 存在文件和目录的汉字处理问题
+ *
+ * @param zipFileName 需要解压的压缩包文件
+ * @param destDir 解压缩后的目标路径
+ * @throws Exception
+ */
+ public static void unZip(String zipFileName, String destDir) throws Exception {
+ logger.debug("unZip start……");
+ ZipFile zipFile = null;
+ try{
+ zipFile = new ZipFile(zipFileName);
+ Enumeration en = zipFile.getEntries();
+ ZipEntry zipEntry = null;
+ while (en.hasMoreElements()) {
+ zipEntry = (ZipEntry) en.nextElement();
+ String path = (destDir + File.separator + zipEntry.getName()).replaceAll("\\\\", "/");
+ if (zipEntry.isDirectory()) {// 如果得到的是目录
+ int end = path.lastIndexOf("/");
+ if (end != -1) {
+ File dir = new File(path.substring(0, end));
+ if (!dir.exists()) {
+ dir.mkdir();
+ }
+ }
+ } else {
+ InputStream in = null;
+ FileOutputStream out = null;
+ try{
+ File f = new File(path);
+ if(!f.getParentFile().exists()){
+ f.getParentFile().mkdirs();
+ }
+ f.createNewFile();
+ in = zipFile.getInputStream(zipEntry);
+ out = new FileOutputStream(f);
+ IOUtils.copy(in, out);
+ }catch (Exception e) {
+ throw e;
+ }finally{
+ if(in!=null) in.close();
+ if(out!=null) out.close();
+ }
+ }
+ }// while end
+ } catch (Exception e) {
+ throw e;
+ }finally {
+ if(zipFile != null){
+ zipFile.close();
+ zipFile = null;
+ }
+ }
+ logger.debug("unZip end……");
+ }
+
+ /**
+ * 将单个文件或一个目录打成zip包
+ *
+ * @param srcDir 需要压压缩的文件目录
+ * @param destFile 压缩后的目标文件
+ * @throws Exception
+ */
+ public static void zip(String srcDir, String destFile, String[] excludes) throws Exception {
+ ZipOutputStream out = null;
+ try{
+ out = new ZipOutputStream(new FileOutputStream(destFile));
+ //out.setEncoding("GBK");//解决linux乱码
+ File srcFile = new File(srcDir);
+ if (!srcFile.exists()) {
+// throw new Exception("压缩目录或文件不存在: " + srcFile.getAbsolutePath());
+ throw new Exception("Compressed directories or files do not exist: " + srcFile.getAbsolutePath());
+ }
+ if(excludes!=null && excludes.length>0){
+ for (int i=0; i<excludes.length; i++) {
+ File excudeFile = new File(excludes[i]);
+ excludes[i] = excudeFile.getCanonicalPath();
+ }
+ }
+
+ /* if(srcFile.isDirectory()){
+ zip(out,srcFile,srcFile.getName(), excludes);
+ }else{
+ zip(out,srcFile,"", excludes);
+ }*/
+ zip(out,srcFile,"", excludes);
+ }catch (Exception e) {
+ throw e;
+ }finally {
+ if(out!=null) out.close();
+ }
+ }
+
+ /**
+ * zip压缩
+ * @param out: Zip压缩流
+ * @param srcFile: 要压缩的目录或文件
+ * @param base: 要压缩文件在zip包内的路径
+ * @throws Exception
+ */
+ protected static void zip(ZipOutputStream out, File srcFile, String base, String[] excludes) throws Exception{
+ if (!srcFile.exists()) {
+// throw new Exception("压缩目录或文件不存在: " + srcFile.getAbsolutePath());
+ throw new Exception("Compressed directories or files do not exist: " + srcFile.getAbsolutePath());
+ }
+
+ if(excludes!=null && excludes.length>0){
+ for(String exclude : excludes){
+ if(exclude.equalsIgnoreCase(srcFile.getCanonicalPath())){
+ return;
+ }
+ }
+ }
+
+ if (srcFile.isDirectory()) {
+ File[] files = srcFile.listFiles();
+ base = base.length() == 0 ? "" : base + "/";
+ if (base.length() > 0) {
+ out.putNextEntry(new ZipEntry(base));
+ /* ZipEntry zipEntry = new ZipEntry(base);
+ zipEntry.setUnixMode(755);// 解决linux乱码
+ out.putNextEntry(zipEntry);*/
+ }
+ for (int i = 0; i < files.length; i++) {
+ zip(out, files[i], base + files[i].getName(), excludes);
+ }
+ } else {
+ base = base.length() == 0 ? srcFile.getName() : base;
+ out.putNextEntry(new ZipEntry(base));
+ /*ZipEntry zipEntry=new ZipEntry(base);
+ zipEntry.setUnixMode(644);//解决linux乱码
+ out.putNextEntry(zipEntry);*/
+ FileInputStream fis = null;
+ try{
+ fis = new FileInputStream(srcFile);
+ IOUtils.copy(fis, out);
+ }catch (IOException e) {
+ throw e;
+ }finally{
+ if(fis!=null) fis.close();
+ }
+ }
+ out.closeEntry();
+ }
+
+ /**
+ * 将单个文件或一个目录打成zip包,并将原文件删除
+ *
+ * @param srcFiles 需要压压缩的文件列表
+ * @param destFile 压缩后的目标文件
+ * @param isAddPrefix 是否要添加文件前缀
+ * @throws Exception
+ */
+ public static void zipWithDelFile(File[] srcFiles, String destFile, boolean isAddPrefix) throws Exception {
+ logger.debug("pass ZipUtil zipWithDelFile(File[] srcFiles, String destFile, boolean isAddPrefix):");
+ if(srcFiles!=null){
+ logger.debug("ZipUtil zipWithDelFile(File[] srcFiles, String destFile, boolean isAddPrefix) srcFiles:"+srcFiles.length);
+ }
+ ZipOutputStream out = null;
+ try{
+ out = new ZipOutputStream(new FileOutputStream(destFile));
+ //out.setEncoding("GBK");//解决linux乱码
+ if (srcFiles==null || srcFiles.length==0) {
+// throw new Exception("压缩文件列表为空");
+ throw new Exception("The list of compressed files is empty");
+ }
+ for(File file : srcFiles){
+ zip(out,file,"", true, isAddPrefix, null);
+ }
+ }catch (Exception e) {
+ throw e;
+ }finally {
+ if(out!=null) out.close();
+ }
+ }
+
+ /**
+ * 将单个文件或一个目录打成zip包,并将原文件删除或移动
+ *
+ * @param srcFiles 需要压压缩的文件列表
+ * @param destFile 压缩后的目标文件
+ * @param isAddPrefix 是否要添加文件前缀
+ * @throws Exception
+ */
+ public static void zipWithMoveFile(File[] srcFiles, String destFile, boolean isAddPrefix) throws Exception {
+ ZipOutputStream out = null;
+ try{
+ out = new ZipOutputStream(new FileOutputStream(destFile));
+ //out.setEncoding("GBK");//解决linux乱码
+ if (srcFiles==null || srcFiles.length==0) {
+// throw new Exception("压缩文件列表为空");
+ throw new Exception("The list of compressed files is empty");
+ }
+ // 2013-03-22 由于DC再次获取未保存任务结果这个功能的实现,现修改将任务结果和回传文件压缩时不删除文件,而是将其移动到相应的日期目录
+ String dataType = null;
+ String destFileName = new File(destFile).getName();
+ if(destFileName.startsWith(CommonSocket.BP_TYPE_TASK_RESULT)){
+ dataType = CommonSocket.BP_TYPE_TASK_RESULT;
+ }else if(destFileName.startsWith(CommonSocket.BP_TYPE_TASK_RETURN)){
+ dataType = CommonSocket.BP_TYPE_TASK_RETURN;
+ }else if(destFileName.startsWith(CommonSocket.BP_TYPE_DETECT_DATA)){
+ dataType = CommonSocket.BP_TYPE_DETECT_DATA;
+ }
+ logger.debug("zipWithMoveFile --- dataType = " + dataType);
+ for(File file : srcFiles){
+ // 2013-5-6 针对监测数据打包文件个数的限制,即srcFiles传来的是一定个数的文件,不是所有监测的目录,所以压缩文件中的文件名要加上文件的父目录名
+ if(CommonSocket.BP_TYPE_DETECT_DATA.equalsIgnoreCase(dataType) && file.isFile()){
+ zip(out, file, file.getParentFile().getName() + "_" + file.getName(), true, isAddPrefix, dataType);
+ }else{
+ zip(out,file,"", true, isAddPrefix, dataType);
+ }
+ }
+ }catch (Exception e) {
+ throw e;
+ }finally {
+ if(out!=null) out.close();
+ }
+ }
+
+ /**
+ * zip压缩
+ * @param out: Zip压缩流
+ * @param srcFile: 要压缩的文件或目录
+ * @param base: 要压缩文件在zip包内的路径
+ * @param isDel 是否删除压缩的文件, 若dataType为null,则直接删除,若dataType不为null, 则移动到指定目录
+ * @param isAddPrefix 是否要添加文件前缀,true 如果是文件则将父文件夹的名称加到文件名的前缀,作为压缩后的文件名
+ * @throws Exception
+ */
+ protected static void zip(ZipOutputStream out, File srcFile, String base, boolean isDel, boolean isAddPrefix, String dataType) throws Exception{
+ if (!srcFile.exists()) {
+// throw new Exception("压缩目录或文件不存在: " + srcFile.getAbsolutePath());
+ throw new Exception("Compressed directories or files do not exist: " + srcFile.getAbsolutePath());
+ }
+ logger.debug("pass ZipUtil zip");
+
+ if (srcFile.isDirectory()) {
+ File[] files = srcFile.listFiles();
+ base = base.length() == 0 ? "" : base + "/";
+ if (base.length() > 0) {
+ out.putNextEntry(new ZipEntry(base));
+ /* ZipEntry zipEntry = new ZipEntry(base);
+ zipEntry.setUnixMode(755);// 解决linux乱码
+ out.putNextEntry(zipEntry);*/
+ }
+ for (int i = 0; i < files.length; i++) {
+ String fileName = files[i].getName();
+ if(isAddPrefix){
+ fileName = files[i].getParentFile().getName() + "_" + files[i].getName();
+ }
+ zip(out, files[i], base + fileName, isDel, isAddPrefix, dataType);
+ }
+ } else{
+ base = base.length() == 0 ? srcFile.getName() : base;
+ out.putNextEntry(new ZipEntry(base));
+ /*ZipEntry zipEntry=new ZipEntry(base);
+ zipEntry.setUnixMode(644);//解决linux乱码
+ out.putNextEntry(zipEntry);*/
+ FileInputStream fis = null;
+ try{
+ fis = new FileInputStream(srcFile);
+ IOUtils.copy(fis, out);
+ }catch (IOException e) {
+ throw e;
+ }finally{
+ if(fis!=null) fis.close();
+ }
+ if(srcFile.exists() && isDel){
+ // 2013-03-22 由于DC再次获取未保存任务结果这个功能的实现,现修改将任务结果和回传文件压缩时不删除文件,而是将其移动到相应的日期目录
+ if(CommonSocket.BP_TYPE_TASK_RESULT.equalsIgnoreCase(dataType)){
+ ServerCollectData.moveTaskResultToDateDir(srcFile);
+ }else if(CommonSocket.BP_TYPE_TASK_RETURN.equalsIgnoreCase(dataType)){
+ ServerCollectData.moveTaskReturnToDateDir(srcFile, null);
+ }else if(CommonSocket.BP_TYPE_DETECT_DATA.equalsIgnoreCase(dataType)){
+ ServerCollectData.moveDetecDataToDateDir(srcFile);
+ }else {
+ FileUtil.delDir(srcFile);
+ logger.debug("ZipUtil.zip()----delete srcFile=" + srcFile.getAbsolutePath());
+ }
+ }
+ }
+ out.closeEntry();
+ }
+
+ public static void main(String[] args) {
+ try {
+ File f = new File("D:/work/create_tablespace");
+ System.out.println(f.getPath());
+ long tt = System.currentTimeMillis();
+ /*String[] excludes = new String[3];
+ excludes[0] = "D:\\temp\\t1\\test\\src";
+ excludes[1] = "D:\\temp\\t1\\test\\WebRoot\\WEB-INF\\lib\\jdom.jar";
+ excludes[2] = "D:\\temp\\t1\\test\\ziptest_code.zip";
+ ZipUtil.zip("D:\\temp\\t1", "D:\\temp\\test\\t1.zip", excludes);
+ //ZipUtil.unZip("D:\\temp\\test\\ziptest_code.zip", "D:\\temp");
+ System.out.println(System.currentTimeMillis()-tt);*/
+ ZipUtil.zipWithDelFile(new File("D:\\nmstest\\logs\\").listFiles(), "D:\\test\\nmsserver.log.zip", true);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/src/com/nis/nmsclient/util/file/BufferedRandomAccessFile.java b/src/com/nis/nmsclient/util/file/BufferedRandomAccessFile.java
new file mode 100644
index 0000000..ca78182
--- /dev/null
+++ b/src/com/nis/nmsclient/util/file/BufferedRandomAccessFile.java
@@ -0,0 +1,313 @@
+package com.nis.nmsclient.util.file;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.ResourceBundle;
+
+/**
+ * <p>Title: BufferedRandomAccessFile</p>
+ * <p>Description: this class provide Buffered Read & Write by extend RandomAccessFile</p>
+ * <p>Copyright: Copyright (c) 2002 Cui Zhixiang </p>
+ * <p>Company: soho </p>
+ * @author Cui Zhixiang
+ * @version 1.0, 2002/10/12
+ */
+
+public class BufferedRandomAccessFile extends RandomAccessFile {
+
+ static ResourceBundle res = ResourceBundle.getBundle(Res.class.getName());
+ private static final int DEFAULT_BUFFER_BIT_LEN = 10;
+ private static final int DEFAULT_BUFFER_SIZE = 1 << DEFAULT_BUFFER_BIT_LEN;
+
+ protected byte buf[];
+ protected int bufbitlen;
+ protected int bufsize;
+ protected long bufmask;
+ protected boolean bufdirty;
+ protected int bufusedsize;
+ protected long curpos;
+
+ protected long bufstartpos;
+ protected long bufendpos;
+ protected long fileendpos;
+
+ protected boolean append;
+ protected String filename;
+ protected long initfilelen;
+
+ public BufferedRandomAccessFile(String name) throws IOException {
+ this(name, res.getString("r"), DEFAULT_BUFFER_BIT_LEN);
+ }
+
+ public BufferedRandomAccessFile(File file) throws IOException, FileNotFoundException {
+ this(file.getPath(), res.getString("r"), DEFAULT_BUFFER_BIT_LEN);
+ }
+
+ public BufferedRandomAccessFile(String name, int bufbitlen) throws IOException {
+ this(name, res.getString("r"), bufbitlen);
+ }
+
+ public BufferedRandomAccessFile(File file, int bufbitlen) throws IOException, FileNotFoundException {
+ this(file.getPath(), res.getString("r"), bufbitlen);
+ }
+
+ public BufferedRandomAccessFile(String name, String mode) throws IOException {
+ this(name, mode, DEFAULT_BUFFER_BIT_LEN);
+ }
+
+ public BufferedRandomAccessFile(File file, String mode) throws IOException, FileNotFoundException {
+ this(file.getPath(), mode, DEFAULT_BUFFER_BIT_LEN);
+ }
+
+ public BufferedRandomAccessFile(String name, String mode, int bufbitlen) throws IOException {
+ super(name, mode);
+ this.init(name, mode, bufbitlen);
+ }
+
+ public BufferedRandomAccessFile(File file, String mode, int bufbitlen) throws IOException, FileNotFoundException {
+ this(file.getPath(), mode, bufbitlen);
+ }
+
+ private void init(String name, String mode, int bufbitlen) throws IOException {
+ if (mode.equals(res.getString("r")) == true) {
+ this.append = false;
+ } else {
+ this.append = true;
+ }
+
+ this.filename = name;
+ this.initfilelen = super.length();
+ this.fileendpos = this.initfilelen - 1;
+ this.curpos = super.getFilePointer();
+
+ if (bufbitlen < 0) {
+ throw new IllegalArgumentException(res.getString("bufbitlen_size_must_0"));
+ }
+
+ this.bufbitlen = bufbitlen;
+ this.bufsize = 1 << bufbitlen;
+ this.buf = new byte[this.bufsize];
+ this.bufmask = ~((long)this.bufsize - 1L);
+ this.bufdirty = false;
+ this.bufusedsize = 0;
+ this.bufstartpos = -1;
+ this.bufendpos = -1;
+ }
+
+ private void flushbuf() throws IOException {
+ if (this.bufdirty == true) {
+ if (super.getFilePointer() != this.bufstartpos) {
+ super.seek(this.bufstartpos);
+ }
+ super.write(this.buf, 0, this.bufusedsize);
+ this.bufdirty = false;
+ }
+ }
+
+ private int fillbuf() throws IOException {
+ super.seek(this.bufstartpos);
+ this.bufdirty = false;
+ return super.read(this.buf);
+ }
+
+ public byte read(long pos) throws IOException {
+ if (pos < this.bufstartpos || pos > this.bufendpos) {
+ this.flushbuf();
+ this.seek(pos);
+
+ if ((pos < this.bufstartpos) || (pos > this.bufendpos)) {
+ throw new IOException();
+ }
+ }
+ this.curpos = pos;
+ return this.buf[(int)(pos - this.bufstartpos)];
+ }
+
+ public boolean write(byte bw) throws IOException {
+ return this.write(bw, this.curpos);
+ }
+
+ public boolean append(byte bw) throws IOException {
+ return this.write(bw, this.fileendpos + 1);
+ }
+
+ public boolean write(byte bw, long pos) throws IOException {
+
+ if ((pos >= this.bufstartpos) && (pos <= this.bufendpos)) { // write pos in buf
+ this.buf[(int)(pos - this.bufstartpos)] = bw;
+ this.bufdirty = true;
+
+ if (pos == this.fileendpos + 1) { // write pos is append pos
+ this.fileendpos++;
+ this.bufusedsize++;
+ }
+ } else { // write pos not in buf
+ this.seek(pos);
+
+ if ((pos >= 0) && (pos <= this.fileendpos) && (this.fileendpos != 0)) { // write pos is modify file
+ this.buf[(int)(pos - this.bufstartpos)] = bw;
+
+ } else if (((pos == 0) && (this.fileendpos == 0)) || (pos == this.fileendpos + 1)) { // write pos is append pos
+ this.buf[0] = bw;
+ this.fileendpos++;
+ this.bufusedsize = 1;
+ } else {
+ throw new IndexOutOfBoundsException();
+ }
+ this.bufdirty = true;
+ }
+ this.curpos = pos;
+ return true;
+ }
+
+ public void write(byte b[], int off, int len) throws IOException {
+
+ long writeendpos = this.curpos + len - 1;
+
+ if (writeendpos <= this.bufendpos) { // b[] in cur buf
+ System.arraycopy(b, off, this.buf, (int)(this.curpos - this.bufstartpos), len);
+ this.bufdirty = true;
+ this.bufusedsize = (int)(writeendpos - this.bufstartpos + 1);//(int)(this.curpos - this.bufstartpos + len - 1);
+
+ } else { // b[] not in cur buf
+ super.seek(this.curpos);
+ super.write(b, off, len);
+ }
+
+ if (writeendpos > this.fileendpos)
+ this.fileendpos = writeendpos;
+
+ this.seek(writeendpos+1);
+ }
+
+ public int read(byte b[], int off, int len) throws IOException {
+
+ long readendpos = this.curpos + len - 1;
+
+ if (readendpos <= this.bufendpos && readendpos <= this.fileendpos ) { // read in buf
+ System.arraycopy(this.buf, (int)(this.curpos - this.bufstartpos), b, off, len);
+ } else { // read b[] size > buf[]
+
+ if (readendpos > this.fileendpos) { // read b[] part in file
+ len = (int)(this.length() - this.curpos + 1);
+ }
+
+ super.seek(this.curpos);
+ len = super.read(b, off, len);
+ readendpos = this.curpos + len - 1;
+ }
+ this.seek(readendpos + 1);
+ return len;
+ }
+
+ public void write(byte b[]) throws IOException {
+ this.write(b, 0, b.length);
+ }
+
+ public int read(byte b[]) throws IOException {
+ return this.read(b, 0, b.length);
+ }
+
+ public void seek(long pos) throws IOException {
+
+ if ((pos < this.bufstartpos) || (pos > this.bufendpos)) { // seek pos not in buf
+ this.flushbuf();
+
+ if ((pos >= 0) && (pos <= this.fileendpos) && (this.fileendpos != 0)) { // seek pos in file (file length > 0)
+ this.bufstartpos = pos & this.bufmask;
+ this.bufusedsize = this.fillbuf();
+
+ } else if (((pos == 0) && (this.fileendpos == 0)) || (pos == this.fileendpos + 1)) { // seek pos is append pos
+
+ this.bufstartpos = pos;
+ this.bufusedsize = 0;
+ }
+ this.bufendpos = this.bufstartpos + this.bufsize - 1;
+ }
+ this.curpos = pos;
+ }
+
+ public long length() throws IOException {
+ return this.max(this.fileendpos + 1, this.initfilelen);
+ }
+
+ public void setLength(long newLength) throws IOException {
+ if (newLength > 0) {
+ this.fileendpos = newLength - 1;
+ } else {
+ this.fileendpos = 0;
+ }
+ super.setLength(newLength);
+ }
+ public long getFilePointer() throws IOException {
+ return this.curpos;
+ }
+
+ private long max(long a, long b) {
+ if (a > b) return a;
+ return b;
+ }
+
+ public void close() throws IOException {
+ this.flushbuf();
+ super.close();
+ }
+
+ public static void main(String[] args) throws IOException {
+ long readfilelen = 0;
+ BufferedRandomAccessFile brafReadFile, brafWriteFile;
+
+ brafReadFile = new BufferedRandomAccessFile("C:\\WINNT\\Fonts\\STKAITI.TTF");
+ readfilelen = brafReadFile.initfilelen;
+ brafWriteFile = new BufferedRandomAccessFile(".\\STKAITI.001", "rw", 10);
+
+ byte buf[] = new byte[1024];
+ int readcount;
+
+ long start = System.currentTimeMillis();
+
+ while((readcount = brafReadFile.read(buf)) != -1) {
+ brafWriteFile.write(buf, 0, readcount);
+ }
+
+ brafWriteFile.close();
+ brafReadFile.close();
+
+ System.out.println("BufferedRandomAccessFile Copy & Write File: "
+ + brafReadFile.filename
+ + " FileSize: "
+ + java.lang.Integer.toString((int)readfilelen >> 1024)
+ + " (KB) "
+ + "Spend: "
+ +(double)(System.currentTimeMillis()-start) / 1000
+ + "(s)");
+
+ java.io.FileInputStream fdin = new java.io.FileInputStream("C:\\WINNT\\Fonts\\STKAITI.TTF");
+ java.io.BufferedInputStream bis = new java.io.BufferedInputStream(fdin, 1024);
+ java.io.DataInputStream dis = new java.io.DataInputStream(bis);
+
+ java.io.FileOutputStream fdout = new java.io.FileOutputStream(".\\STKAITI.002");
+ java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(fdout, 1024);
+ java.io.DataOutputStream dos = new java.io.DataOutputStream(bos);
+
+ start = System.currentTimeMillis();
+
+ for (int i = 0; i < readfilelen; i++) {
+ dos.write(dis.readByte());
+ }
+
+ dos.close();
+ dis.close();
+
+ System.out.println("DataBufferedios Copy & Write File: "
+ + brafReadFile.filename
+ + " FileSize: "
+ + java.lang.Integer.toString((int)readfilelen >> 1024)
+ + " (KB) "
+ + "Spend: "
+ + (double)(System.currentTimeMillis()-start) / 1000
+ + "(s)");
+ }
+}
diff --git a/src/com/nis/nmsclient/util/file/Res.java b/src/com/nis/nmsclient/util/file/Res.java
new file mode 100644
index 0000000..7e61830
--- /dev/null
+++ b/src/com/nis/nmsclient/util/file/Res.java
@@ -0,0 +1,17 @@
+package com.nis.nmsclient.util.file;
+
+public class Res extends java.util.ListResourceBundle {
+ static final Object[][] contents = new String[][]{
+ { "r", "r" },
+ { "bufbitlen_size_must_0", "bufbitlen size must >= 0" },
+ { "rw", "rw" },
+ { "BufferedRandomAccess", "BufferedRandomAccessFile Copy & Write File: " },
+ { "FileSize_", " FileSize: " },
+ { "_KB_", " (KB) " },
+ { "Spend_", "Spend: " },
+ { "_s_", "(s)" },
+ { "DataBufferedios_Copy", "DataBufferedios Copy & Write File: " }};
+ public Object[][] getContents() {
+ return contents;
+ }
+} \ No newline at end of file
diff --git a/src/com/nis/nmsclient/util/io/UnicodeInputStream.java b/src/com/nis/nmsclient/util/io/UnicodeInputStream.java
new file mode 100644
index 0000000..9e61d42
--- /dev/null
+++ b/src/com/nis/nmsclient/util/io/UnicodeInputStream.java
@@ -0,0 +1,118 @@
+package com.nis.nmsclient.util.io;
+/**
+ version: 1.1 / 2007-01-25
+ - changed BOM recognition ordering (longer boms first)
+
+ Original pseudocode : Thomas Weidenfeller
+ Implementation tweaked: Aki Nieminen
+
+ http://www.unicode.org/unicode/faq/utf_bom.html
+ BOMs in byte length ordering:
+ 00 00 FE FF = UTF-32, big-endian
+ FF FE 00 00 = UTF-32, little-endian
+ EF BB BF = UTF-8,
+ FE FF = UTF-16, big-endian
+ FF FE = UTF-16, little-endian
+
+ Win2k Notepad:
+ Unicode format = UTF-16LE
+ ***/
+
+import java.io.*;
+
+/**
+ * This inputstream will recognize unicode BOM marks and will skip bytes if
+ * getEncoding() method is called before any of the read(...) methods.
+ *
+ * Usage pattern: String enc = "ISO-8859-1"; // or NULL to use systemdefault
+ * FileInputStream fis = new FileInputStream(file); UnicodeInputStream uin = new
+ * UnicodeInputStream(fis, enc); enc = uin.getEncoding(); // check and skip
+ * possible BOM bytes InputStreamReader in; if (enc == null) in = new
+ * InputStreamReader(uin); else in = new InputStreamReader(uin, enc);
+ */
+public class UnicodeInputStream extends InputStream {
+ PushbackInputStream internalIn;
+ boolean isInited = false;
+ String defaultEnc;
+ String encoding;
+
+ private static final int BOM_SIZE = 4;
+
+ UnicodeInputStream(InputStream in, String defaultEnc) {
+ internalIn = new PushbackInputStream(in, BOM_SIZE);
+ this.defaultEnc = defaultEnc;
+ }
+
+ public String getDefaultEncoding() {
+ return defaultEnc;
+ }
+
+ public String getEncoding() {
+ if (!isInited) {
+ try {
+ init();
+ } catch (IOException ex) {
+ IllegalStateException ise = new IllegalStateException(
+ "Init method failed.");
+ ise.initCause(ise);
+ throw ise;
+ }
+ }
+ return encoding;
+ }
+
+ /**
+ * Read-ahead four bytes and check for BOM marks. Extra bytes are unread
+ * back to the stream, only BOM bytes are skipped.
+ */
+ protected void init() throws IOException {
+ if (isInited)
+ return;
+
+ byte bom[] = new byte[BOM_SIZE];
+ int n, unread;
+ n = internalIn.read(bom, 0, bom.length);
+
+ if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00)
+ && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
+ encoding = "UTF-32BE";
+ unread = n - 4;
+ } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)
+ && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
+ encoding = "UTF-32LE";
+ unread = n - 4;
+ } else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB)
+ && (bom[2] == (byte) 0xBF)) {
+ encoding = "UTF-8";
+ unread = n - 3;
+ } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
+ encoding = "UTF-16BE";
+ unread = n - 2;
+ } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
+ encoding = "UTF-16LE";
+ unread = n - 2;
+ } else {
+ // Unicode BOM mark not found, unread all bytes
+ encoding = defaultEnc;
+ unread = n;
+ }
+ // System.out.println("read=" + n + ", unread=" + unread);
+
+ if (unread > 0)
+ internalIn.unread(bom, (n - unread), unread);
+
+ isInited = true;
+ }
+
+ public void close() throws IOException {
+ // init();
+ isInited = true;
+ internalIn.close();
+ }
+
+ public int read() throws IOException {
+ // init();
+ isInited = true;
+ return internalIn.read();
+ }
+}
diff --git a/src/com/nis/nmsclient/util/io/UnicodeReader.java b/src/com/nis/nmsclient/util/io/UnicodeReader.java
new file mode 100644
index 0000000..c4169b5
--- /dev/null
+++ b/src/com/nis/nmsclient/util/io/UnicodeReader.java
@@ -0,0 +1,120 @@
+package com.nis.nmsclient.util.io;
+/**
+ version: 1.1 / 2007-01-25
+ - changed BOM recognition ordering (longer boms first)
+
+ Original pseudocode : Thomas Weidenfeller
+ Implementation tweaked: Aki Nieminen
+
+ http://www.unicode.org/unicode/faq/utf_bom.html
+ BOMs:
+ 00 00 FE FF = UTF-32, big-endian
+ FF FE 00 00 = UTF-32, little-endian
+ EF BB BF = UTF-8,
+ FE FF = UTF-16, big-endian
+ FF FE = UTF-16, little-endian
+
+ Win2k Notepad:
+ Unicode format = UTF-16LE
+ ***/
+
+import java.io.*;
+
+/**
+ * Generic unicode textreader, which will use BOM mark to identify the encoding
+ * to be used. If BOM is not found then use a given default or system encoding.
+ */
+public class UnicodeReader extends Reader {
+ PushbackInputStream internalIn;
+ InputStreamReader internalIn2 = null;
+ String defaultEnc;
+
+ private static final int BOM_SIZE = 4;
+
+ /**
+ *
+ * @param in
+ * inputstream to be read
+ * @param defaultEnc
+ * default encoding if stream does not have BOM marker. Give NULL
+ * to use system-level default.
+ */
+ public UnicodeReader(InputStream in, String defaultEnc) {
+ internalIn = new PushbackInputStream(in, BOM_SIZE);
+ this.defaultEnc = defaultEnc;
+ }
+
+ public String getDefaultEncoding() {
+ return defaultEnc;
+ }
+
+ /**
+ * Get stream encoding or NULL if stream is uninitialized. Call init() or
+ * read() method to initialize it.
+ */
+ public String getEncoding() {
+ if (internalIn2 == null)
+ return null;
+ return internalIn2.getEncoding();
+ }
+
+ /**
+ * Read-ahead four bytes and check for BOM marks. Extra bytes are unread
+ * back to the stream, only BOM bytes are skipped.
+ */
+ protected void init() throws IOException {
+ if (internalIn2 != null)
+ return;
+
+ String encoding;
+ byte bom[] = new byte[BOM_SIZE];
+ int n, unread;
+ n = internalIn.read(bom, 0, bom.length);
+
+ if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00)
+ && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
+ encoding = "UTF-32BE";
+ unread = n - 4;
+ } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)
+ && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
+ encoding = "UTF-32LE";
+ unread = n - 4;
+ } else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB)
+ && (bom[2] == (byte) 0xBF)) {
+ encoding = "UTF-8";
+ unread = n - 3;
+ } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
+ encoding = "UTF-16BE";
+ unread = n - 2;
+ } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
+ encoding = "UTF-16LE";
+ unread = n - 2;
+ } else {
+ // Unicode BOM mark not found, unread all bytes
+ encoding = defaultEnc;
+ unread = n;
+ }
+ // System.out.println("read=" + n + ", unread=" + unread);
+
+ if (unread > 0)
+ internalIn.unread(bom, (n - unread), unread);
+
+ // Use given encoding
+ if (encoding == null) {
+ internalIn2 = new InputStreamReader(internalIn);
+ } else {
+ internalIn2 = new InputStreamReader(internalIn, encoding);
+ }
+ }
+
+ public void close() throws IOException {
+ init();
+ internalIn2.close();
+ }
+
+ public int read(char[] cbuf, int off, int len) throws IOException {
+ init();
+ return internalIn2.read(cbuf, off, len);
+ }
+
+} \ No newline at end of file
diff --git a/src/com/nis/nmsclient/util/log4j/MyDailyRollingFileAppender.java b/src/com/nis/nmsclient/util/log4j/MyDailyRollingFileAppender.java
new file mode 100644
index 0000000..b003cc4
--- /dev/null
+++ b/src/com/nis/nmsclient/util/log4j/MyDailyRollingFileAppender.java
@@ -0,0 +1,14 @@
+package com.nis.nmsclient.util.log4j;
+
+import org.apache.log4j.DailyRollingFileAppender;
+import org.apache.log4j.Priority;
+
+public class MyDailyRollingFileAppender extends DailyRollingFileAppender {
+
+ @Override
+ public boolean isAsSevereAsThreshold(Priority priority) {
+ // 只判断相等,不判断优先级
+ return this.getThreshold().equals(priority);
+ }
+
+}
diff --git a/src/com/nis/nmsclient/util/log4j/MyRollingFileAppender.java b/src/com/nis/nmsclient/util/log4j/MyRollingFileAppender.java
new file mode 100644
index 0000000..133c592
--- /dev/null
+++ b/src/com/nis/nmsclient/util/log4j/MyRollingFileAppender.java
@@ -0,0 +1,14 @@
+package com.nis.nmsclient.util.log4j;
+
+import org.apache.log4j.Priority;
+import org.apache.log4j.RollingFileAppender;
+
+public class MyRollingFileAppender extends RollingFileAppender {
+
+ @Override
+ public boolean isAsSevereAsThreshold(Priority priority) {
+ // 只判断相等,不判断优先级
+ return this.getThreshold().equals(priority);
+ }
+
+}