• Java常用工具类整理


    字符数组转String

    package com.sunsheen.hcc.fabric.utils;
    /**
     * 字符数组工具
     * @author WangSong
     *
     */
    public class ByteArryUtil {
    
        /**
          * 字节数组转成16进制表示格式的字符串
          * 
          * @param byteArray
          *            需要转换的字节数组
          * @return 16进制表示格式的字符串
          **/
         public static String toHexString(byte[] byteArray) {
             if (byteArray == null || byteArray.length < 1)
                 throw new IllegalArgumentException("this byteArray must not be null or empty");
         
             final StringBuilder hexString = new StringBuilder();
             for (int i = 0; i < byteArray.length; i++) {
                 if ((byteArray[i] & 0xff) < 0x10)//0~F前面不零
                     hexString.append("0");
                 hexString.append(Integer.toHexString(0xFF & byteArray[i]));
             }
             return hexString.toString().toLowerCase();
         }
        
    }
    View Code

    json、map、list、String格式数据互转

    package com.sunsheen.hcc.fabric.utils;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.commons.collections.map.ListOrderedMap;
    
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    import net.sf.json.JsonConfig;
    import net.sf.json.util.CycleDetectionStrategy;
    
    /**
     * json工具
     * @author WangSong
     *
     */
    public class JsonParseUtil {
    
        /**
         * 將jsonArry字符串转换成map(里面可能是多个对象的情况)
         * @param json
         * @return
         */
        public static List<Map<String, Object>> parseJSON2List(String json) {
            JSONArray jsonArr = JSONArray.fromObject(json);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            Iterator<JSONObject> it = jsonArr.iterator();
            while (it.hasNext()) {
                JSONObject json2 = it.next();
                list.add(parseJSON2Map(json2.toString()));
            }
            return list;
        }
    
        private static Map<String, Object> parseJSON2Map(String jsonStr) {
            ListOrderedMap map = new ListOrderedMap();
            // 最外层解析
            JSONObject json = JSONObject.fromObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                // 如果内层还是数组的话,继续解析
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<JSONObject> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = it.next();
                        list.add(parseJSON2Map(json2.toString()));
                    }
                    map.put(k.toString(), list);
                } else {
                    map.put(k.toString(), v);
                }
            }
            Iterator iterator = map.keySet().iterator();
            List<String> lsList = new ArrayList<String>();
            int d=0;
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                Object object = map.get(key);    
                // 进行遍历删除,当值为空的时候删除这条数据
                if (object.equals("")) {
                    iterator.remove();
                    map.remove(key);
                }
            }
            return map;
        }
        
        /**
         * 将对象转换成json
         * @param param
         * @return
         */
        public static String object2Json(Object param){
    //        JSON.toJSONString();
            
            JSONObject jsonObject = JSONObject.fromObject(param);
            return jsonObject.toString();
        }
        
        /**
         * 将json字符串转换成map
         * @param json
         * @return
         */
        public static Map<String, Object> json2Map(String json) {
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(json);
            Map<String, Object> valueMap = new HashMap<String, Object>();
            valueMap.putAll(jsonObject);
            return valueMap;
        }
    
        /**
         * list对象转换成json
         * @param param
         * @return
         */
        public static String list2String(List param){
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
            JSONArray json = JSONArray.fromObject(param, jsonConfig);
            return json.toString();
        }
        
    }
    View Code

    实体对象转换成map

                    Contract contract = new Contract ();
            try{
                Map<String, Object> params = new HashMap<String, Object>();
                //将对象信息封装到map
                Class clazz = contract.getClass();
                Field[] fields = clazz.getDeclaredFields();
                for (Field f : fields) {
                    String name = f.getName();//当前字段
                    if(name.equals("serialVersionUID"))
                        continue;
                    PropertyDescriptor descriptor = new PropertyDescriptor(name, clazz);//得到当前字段信息
                    Method readMethod = descriptor.getReadMethod();
                    Object value = readMethod.invoke(contract);//得到当前字段值
                    if(null != value)
                        params.put(name, value);
                
    View Code

    前后端数据格式转换

    package com.sunsheen.hcc.fabric.utils;
    
    import java.util.Date;
    import java.util.Enumeration;
    
    import javax.servlet.http.HttpServletRequest;
    
    import com.sunsheen.edu.case1.entity.ResponseMsg;
    import com.sunsheen.jfids.commons.beanutils.BeanUtils;
    import com.sunsheen.jfids.commons.beanutils.ConvertUtils;
    import com.sunsheen.jfids.commons.beanutils.converters.DateConverter;
    import com.sunsheen.jfids.gson.Gson;
    
    /**
     * 前后端数据转换工具类
     * @author WangSong
     *
     */
    public class WebUtils {
        
        /**
         * 把request对象中的请求参数封装到bean中
         * @param request    http请求
         * @param clazz        需要存入信息的对象class
         * @return
         */
        public static <T> T request2Bean(HttpServletRequest request,Class<T> clazz){
            try{
                T bean = clazz.newInstance();
                Enumeration e = request.getParameterNames();
                while(e.hasMoreElements()){
                        String name = (String) e.nextElement(); 
                        String value = request.getParameter(name);
                        if(null != value && !"".equals(value)){
                            //日期注册
                            if(value.contains("-")){
                                DateConverter converter = new DateConverter();
                                converter.setPattern("yyyy-MM-dd");
                                ConvertUtils.register(converter,Date.class);
                            }
                            //对象赋值
                            BeanUtils.setProperty(bean, name, value);
                        }
                }
                return bean;
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        
        /**
         * 响应到页面的数据
         * @param code
         * @param data
         * @return
         */
        public static String responseMsg(Integer code, Object data) {
            ResponseMsg msg =  new ResponseMsg(data,code);
            return new Gson().toJson(msg);
        }
        
        /**
         * 响应到页面的数据
         * @param data
         * @return
         */
        public static String responseMsg(Object data) {
            ResponseMsg msg =  new ResponseMsg(data);
            return new Gson().toJson(msg);
        }
        
        
    }
    View Code

    得到指定文件夹大小

    package com.sunsheen.jfids.studio.monitor.utils.local;
    
    import java.io.File;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicLong;
    
    /**
     * 得到指定文件夹大小
     * @author WangSong
     *
     */
    public class FileUtil {
        
        private ExecutorService service;
        final private AtomicLong pendingFileVisits = new AtomicLong();
        
        /** 通过CountdownLatch 得到文件夹大小的初始常量 **/
        final private AtomicLong totalSize = new AtomicLong();
        final private CountDownLatch latch = new CountDownLatch(1);
        
        /** 通过BlockingQueue得到文件夹大小的初始常量 **/
        final private BlockingQueue<Long> fileSizes = new ArrayBlockingQueue<Long>(500);
        
    
        /////////////////////////////////////CountdownLatch/////////////////////////////////////////
        //更新文件总大小(多线程)
        private void updateTotalSizeOfFilesInDir(final File file) {
            long fileSize = 0;//初始化文件大小
            //文件,直接返回大小
            if (file.isFile())
                fileSize = file.length();
            //文件夹,遍历所有文件总大小
            else {
                final File[] children = file.listFiles();
                if(null == children){
                    totalSize.set(0);
                    return;
                }
                for (final File child : children) {
                    //文件:直接加当前文件的大小
                    if (child.isFile())
                        fileSize += child.length();
                    //文件夹:遍历里面的文件的大小
                    else {
                        pendingFileVisits.incrementAndGet();//增加一个当前值(用来观察这里的线程是否启动)
                        service.execute(new Runnable() {
                            public void run() {
                                updateTotalSizeOfFilesInDir(child);
                            }
                        });
                    }
                }
            }
            totalSize.addAndGet(fileSize);
            //如果没有遍历的子文件夹,则pendingFileVisits-1 = 0,当前线程等待
            if (pendingFileVisits.decrementAndGet() == 0)
                latch.countDown();//发令枪 - 1
        }
    
        /**
         * 得到指定文件的大小
         * @param fileName    文件名(全路径)
         * @return    文件夹大小(M)
         * @throws InterruptedException
         */
        public double getTotalSizeOfFile(final String filePath){
            service = Executors.newCachedThreadPool();//初始化线程池
            pendingFileVisits.incrementAndGet();//增加当前值1
            double result = 0;//初始化结果
            try {
                updateTotalSizeOfFilesInDir(new File(filePath));
                latch.await(100, TimeUnit.SECONDS);//当前线程等待,直到锁存器计数到0
    //            latch.await();
                //将k转换成m
                long resultK = totalSize.longValue();
                BigDecimal bdK = new BigDecimal(resultK);
                BigDecimal bdM = bdK.divide(new BigDecimal(1024 * 1024)).setScale(5, RoundingMode.HALF_UP);//保留5位小数
                result = bdM.doubleValue();
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                service.shutdown();
            }
            return result;
        }
        /////////////////////////////////////CountdownLatch/////////////////////////////////////////
    
        
        /////////////////////////////////////BlockingQueue/////////////////////////////////////////
        private void startExploreDir(final File file) {
            pendingFileVisits.incrementAndGet();//記錄遍历文件夹次数
            service.execute(new Runnable() {
                public void run() {
                    exploreDir(file);
                }
            });
        }
        
        private void exploreDir(final File file) {
            long fileSize = 0;
            if (file.isFile())
                fileSize = file.length();
            else {
                final File[] children = file.listFiles();
                if (children != null)
                    for (final File child : children) {
                        if (child.isFile())
                            fileSize += child.length();
                        else {
                            startExploreDir(child);
                        }
                    }
            }
            try {
                fileSizes.put(fileSize);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            pendingFileVisits.decrementAndGet();
        }
    
        /**
         * 得到指定文件的大小
         * @param fileName
         * @return
         * @throws InterruptedException
         */
        public double getTotalSizeOfFile1(final String fileName){
            service = Executors.newFixedThreadPool(100);
            double result = 0;
            try {
                startExploreDir(new File(fileName));
                long totalSize = 0;
                while (pendingFileVisits.get() > 0 || fileSizes.size() > 0) {
                    final Long size = fileSizes.poll(10, TimeUnit.SECONDS);
                    totalSize += size;
                }
                //将k转换成m
                BigDecimal bdK = new BigDecimal(totalSize);
                BigDecimal bdM = bdK.divide(new BigDecimal(1024 * 1024)).setScale(5, RoundingMode.HALF_UP);//保留5位小数            
                result = bdM.doubleValue();
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                service.shutdown();
            }
            return result;
        }
        /////////////////////////////////////BlockingQueue/////////////////////////////////////////
    
        
        
        /**
         * 先根遍历序递归删除文件夹
         *
         * @param dirFile 要被删除的文件或者目录
         * @return 删除成功返回true, 否则返回false
         */
        public boolean deleteFile(File dirFile) {
            // 如果dir对应的文件不存在,则退出
            if (!dirFile.exists()) {
                return false;
            }
            if (dirFile.isFile()) {
                return dirFile.delete();
            } else {
                for (File file : dirFile.listFiles()) {
                    deleteFile(file);
                }
            }
            return dirFile.delete();
        }
        
    }
    View Code

    遍历指定文件夹下存在log日志文件的文件夹

    package com.sunsheen.jfids.studio.monitor.utils.local;
    
    import java.io.File;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.ConcurrentHashMap;
    
    import com.sunsheen.jfids.studio.monitor.common.LogInfo;
    
    /**
     * 遍历当前eclipse运行空间下所有项目名跟对应日志
     * @author WangSong
     *
     */
    public class LocalLogUtil {    
        
        private LocalLogUtil(){}
        
        
        /**
         * 遍历出存在项目日志文件的文件夹
         * @return
         */
        public static Map<String,Set<File>> getPlugLogs(){
            Map<String,Set<File>> associatedLogMap = new ConcurrentHashMap<String,Set<File>>();//
            //截取出正确的运行空间目录
            String runtimeSpace = LogInfo.RUNTIME_SPACE.substring(1,LogInfo.RUNTIME_SPACE.length() - 1);        
            String[] arr = runtimeSpace.split("/");
            StringBuffer sb = new StringBuffer();
            for(String space : arr)
                sb.append(space+File.separator);
            String logParentFolder = sb + LogInfo.LOG_PARENT_PATH;
            
            File file = new File(logParentFolder);//存放所有日志文件的文件夹
            listExistingLogFolder(associatedLogMap,file);
            return associatedLogMap;
        }
    
        
        //遍历当前文件夹下面所有文件
        private static void listExistingLogFolder(Map<String,Set<File>> associatedLogMap,File file){
            //遍历当前文件夹
            File[]  innerFiles = file.listFiles();
            for(File result : innerFiles){
                //存放对应关系
                if(result.isDirectory())
                    listExistingLogFolder(associatedLogMap,result);
                else{
                    String name = result.getName();//当前文件名
                    //是日志文件,存入
                    if(name.contains(".log")){
                        String projectName = result.getParent();//上层项目名路径
                        //如果不是项目日志文件不记录
                        if(!projectName.contains("com.sunsheen.jfids"))
                            continue;
                        //截取出正确的插件项目名
                        projectName = projectName.substring(projectName.lastIndexOf("c"));
                        //保证能添加所有的日志文件
                        if(associatedLogMap.containsKey(projectName)){
                            //当前项目存在日志文件时
                            Set<File> currentLogs = associatedLogMap.get(projectName);
                            currentLogs.add(result);
                            associatedLogMap.put(projectName, currentLogs);//保存最新的关系
                        }else{
                            //不存在当前项目日志文件时
                            Set<File> currentLogs = new HashSet<File>();
                            currentLogs.add(result);
                            associatedLogMap.put(projectName,currentLogs);//创建一个新关联
                        }
                    }
                }
            }
        }
        
    }
    View Code

    文件压缩跟解压

    package com.sunsheen.jfids.studio.monitor.utils;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipOutputStream;
    
    import org.eclipse.core.runtime.Assert;
    
    import com.sunsheen.jfids.studio.monitor.HKMonitor;
    import com.sunsheen.jfids.studio.monitor.HKMonitorFactory;
    
    import ch.ethz.ssh2.ChannelCondition;
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.Session;
    import ch.ethz.ssh2.StreamGobbler;
    /**
     * 多文件的打包压缩跟解压
     * @author WangSong
     *
     */
    public class ZipFileUtil {
        private final static HKMonitor moniter = HKMonitorFactory.getLogger(ZipFileUtil.class.getName());
    
        /**
         * 压缩离线备份log文件成一个zip
         * @param srcFiles
         * @param zipFile
         * @return
         */
        public static File zipOfflineLogs(File[] srcFiles,File zipFile){
            if(srcFiles.length == 0 || null==srcFiles)
                return new File("");
            
            byte[] buf=new byte[1024];
            try {
                ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));//定义要写入的文件
                for(int i=0;i<srcFiles.length;i++){
                    FileInputStream in = new FileInputStream(srcFiles[i]);//读取文件
                    out.putNextEntry(new ZipEntry(srcFiles[i].getName()));//设置内文件名
                    //写入数据
                    int length;
                    while((length = in.read(buf)) > 0){
                            out.write(buf,0,length);
                    }
                    out.closeEntry();
                    in.close();
                    }
                    out.close();
    //                System.out.println("文件【"+zipFile.getName()+"】压缩完成!");
              } catch (Exception e) {
                  e.printStackTrace();
              }
            
            return zipFile;
        }
        
          /**
           * 功能:压缩多个log文件成一个zip文件(本地)
           * @param srcfile:源文件列表
           * @param zipfile:压缩后的文件
           * @return    压缩后的文件
           */
          public static File zipFiles(File[] srcfile,File zipfile){
              if(srcfile.length == 0 || null==srcfile)
                  return null;
              
              //存在当前压缩文件时,保存新文件(文件名 + 1)    eg:log.zip  ---->  log(1).zip
              if(zipfile.exists() && zipfile.length() != 0){
                  File[] files = new File(zipfile.getParent()).listFiles();//当前目录的所有zip文件
                  //截取出当前需要增加数字标号的名字部分
                  String[] sourceArray = (zipfile.getName()).split("\.");//将\. 转义成.
                  //防止异常
                  Assert.isTrue(sourceArray.length != 0, "程序异常:文件名划分错误!");
                  String change = sourceArray[sourceArray.length - 2];//get需要修改部分  eg:monitor
                  //备份第二个时,增加数字下标
                  if(files.length>0 && files.length<2){
                      change = change + "("+ 1 +")";
                      sourceArray[sourceArray.length - 2] = change;//需要修改部分重新赋值
                      StringBuffer newName = new StringBuffer();
                      for(String source : sourceArray){
                          //最后一次添加不能添加:.
                          if(source.equals(sourceArray[sourceArray.length - 1])){
                              newName.append(source);
                              break;
                          }
                          newName.append(source+".");
                      }
                      String path = zipfile.getPath();
                      path = path.substring(0, path.lastIndexOf(File.separator));
                      zipfile = new File(path + File.separator + newName);
                  }
                  //需要排除掉第一个备份(没有数字的),且最大数字+1
                  else if(files.length >= 2){                  
                      int[] nums = new int[files.length - 1];
                      int k = 0;
                      //取出当前文件夹下所有文件名的数字部分
                      for(File file : files){
                          //排除第一次备份(没有数字标号)的
                          if((zipfile.getName()).equals(file.getName()))
                              continue;
                          
                         String[] oldArray = null;    //存放切割出来的zip文件名
                         String target = null; //有数字的字符串
                         int index = 0;
                         oldArray = (file.getName()).split("\.");
                          target = oldArray[oldArray.length - 2];
                         index = Integer.parseInt(target.substring(target.lastIndexOf("(") + 1, target.lastIndexOf(")")));
                         nums[k] = index;
                         k++;
                      }
                      //找出最大的数字
                      int max=0;
                      for(int i=0;i<nums.length;i++){
                          if(nums[i] > max){
                                  max=nums[i];
                          }
                      }
                      //重新设置数字
                      max++;
                      change = change + "("+ max +")";
                      sourceArray[sourceArray.length - 2] = change;//需要修改部分重新赋值
                      StringBuffer newName = new StringBuffer();
                      for(String source : sourceArray){
                          //最后一次添加后退出
                          if(source.equals(sourceArray[sourceArray.length - 1])){
                              newName.append(source);
                              break;
                          }
                          newName.append(source+".");
                      }
                      String path = zipfile.getPath();
                      path = path.substring(0, path.lastIndexOf(File.separator));
                      zipfile = new File(path + File.separator + newName);
                  }
              }
     
              //压缩
              byte[] buf=new byte[1024];
              try {
                  //ZipOutputStream :完成文件或文件夹的压缩
                  ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
                  for(int i=0;i<srcfile.length;i++){
                      if(!srcfile[i].exists())
                          continue;
                      FileInputStream in = new FileInputStream(srcfile[i]);//读取文件
                      String zipName = srcfile[i].getName();
                      out.putNextEntry(new ZipEntry(zipName));//设置内文件名
                      //写入数据
                      int length;
                      while((length = in.read(buf)) > 0){
                              out.write(buf,0,length);
                      }
                      out.closeEntry();
                      in.close();
                      }
                      out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
              return zipfile;
           }
          
          /**
           * 功能:解压缩(本地)
           * @param zipfile:需要解压缩的文件
           * @param descDir:解压后的目标目录
           */
          public static void unZipFiles(File zipfile,String descDir){
         
              try {
                  ZipFile zf = new ZipFile(zipfile);//格式化
                  //循环遍历出压缩的每个文件
                  for(Enumeration entries = zf.entries();entries.hasMoreElements();){
                      ZipEntry entry = (ZipEntry) entries.nextElement();
                      String zipEntryName = entry.getName();//当前压缩文件中文件名
                      InputStream in = zf.getInputStream(entry);
                      
                      File mkFile = new File(descDir + zipEntryName);
                      mkFile.createNewFile();
                      
                      OutputStream out=new FileOutputStream(descDir + zipEntryName);
                      byte[] buf1 = new byte[1024];
                      int len;
                      while((len=in.read(buf1)) > 0){
                          out.write(buf1,0,len);
                      }
                      in.close();
                      out.close();
                      moniter.info("文件【"+zipfile.getName()+"】,解压缩完成!");
                      System.out.println("解压缩完成.");
                  }
                } catch (Exception e) {
                    e.printStackTrace();
                }
          }
          
          /**
           * 壓縮指定文件夾下所有文件
           * @param targetZipFile    压缩后的文件     eg:d://logs//log.zip
           * @param logFolder    日志文件所在的文件夹    eg:e://logs
           * @return
           */
          public static File zipLogs(String targetZipFile,String logFolder){
            //定义日志压缩文件
            File[] logsFileArr = new File(logFolder).listFiles();//所有的日志文件
            //創建一個空的目標zip文件
            File resultZip = new File(targetZipFile);
            //壓縮
            zipFiles(logsFileArr, resultZip);
            return resultZip;
          }
          
          
          /**
           * 解压文件(远程)
           * @param romoteAddr    服务器地址
           * @param username    服务器用户名
           * @param password    服务器密码
           * @param targetFolder    服务器上需要解压文件的目录    eg:/usr/local/hk-logs
           * @param zipFileName    需要解压文件的文件名    eg:logs.zip
           */
          public static void remoteUnZip(String romoteAddr,String username,String password,
                  String targetFolder,String zipFileName){
              
              try {
                  Connection connection = new Connection(romoteAddr);// 创建一个连接实例
                  connection.connect();// Now connect
                  boolean isAuthenticated = connection.authenticateWithPassword(username, password);//認證
                  Assert.isTrue(isAuthenticated, "用戶名或者密碼錯誤!");
                  Session sess = connection.openSession();// 創建一個會話
                  sess.requestPTY("bash");
                  sess.startShell();
                  InputStream stdout = new StreamGobbler(sess.getStdout());
                  InputStream stderr = new StreamGobbler(sess.getStderr());
                  BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
                  BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
                  //向服务器上输入命令
                  PrintWriter out = new PrintWriter(sess.getStdin());
                  out.println("cd " + targetFolder);//進入日志文件存放的目录
                  out.println("ll");
                  out.println("unzip -o -d "+targetFolder+" "+zipFileName);//解压文件到指定位置
                  out.println("ll");
                  out.println("exit");
                  out.close();
                  sess.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,30000);
                  //本机查看远程操作的指令及状态
                  showRemoteShell(stdoutReader,stderrReader,sess);
                  //查看当前退出状态
                  System.out.println("ExitCode: " + sess.getExitStatus());
                  //关闭连接
                  sess.close();
                  connection.close();
              } catch (IOException e) {
                  moniter.error("远程解压文件【"+ zipFileName +"】,错误:" + e);
                  e.printStackTrace(System.err);
    //              System.exit(2);
              }
          }
          
          //打印远程指令及状态
          private static void showRemoteShell(BufferedReader stdoutReader,BufferedReader stderrReader,
                  Session sess) throws IOException{
              System.out.println("输入在服务器的指令:");
              while (true) {
                  String line = stdoutReader.readLine();
                  if (line == null)
                      break;
                  System.out.println(line);
              }
              System.out.println("输入指令后对应的显示信息:");
              while (true) {
                  String line = stderrReader.readLine();
                  if (line == null)
                      break;
                  System.out.println(line);
              }
          }
          
    }
    View Code

    监测服务器是否可达【一】

    package com.sunsheen.jfids.studio.monitor.utils.remote;
    
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.text.DateFormat;
    import java.util.Date;
    /**
     * 檢測網絡或者指定连接是否可用
     * @author WangSong
     *
     */
    public class IntenetAvailableUtil {
        /**记录连接次数**/
        private static int count = 0;
        /**URL**/
        private static URL urlStr = null;
        /**连接响应码**/
        private static int stateCode = 0;
        /**记录网络断开时间**/
        private static String closeTime = null;
        /**HttpURLCOnnection对象**/
        private static HttpURLConnection connection = null;
    
        /***
        * 功能描述:检测当前的网络是否断开或当前地址是否可连接
        *  如果网络没有断开,最多连接网络5次,如果5次连接不成功说明该地址不存在或视为无效地址。
        * @param url
        */
        public synchronized static boolean connState(String url) {
            while(count < 5){
                try {
                    urlStr = new URL(url);
                    connection = (HttpURLConnection) urlStr.openConnection();
                    stateCode = connection.getResponseCode();
                    if(stateCode == 200){
                        return true;
                    }
                } catch (Exception e) {
                    if(closeTime == null){
                        DateFormat df = DateFormat.getDateTimeInstance();
                        closeTime = df.format(new Date());
                        System.out.println("网络连接已断开,请检查网络连接设备");
                        System.out.println("断开时间:"+closeTime);
                        System.out.println("程序开始設定每10秒检查一次");
                    }
                    try {
                        System.out.println("开始第"+ ++count +"次检查网络连接状态");
                        Thread.sleep(10000);
                    } catch (InterruptedException e1) {}
                }
            }
            return false;
        }
    }
    View Code

    监测服务器是否可达【二】

    package com.sunsheen.jfids.studio.monitor.utils.remote;
    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.InetAddress;
    import java.net.MalformedURLException;
    import java.net.URL;
     
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLSession;
     /**
      * 检测网址、ip、服务器是否可用
      * @author WangSong
      *
      */
    public class NetStateUtil {
        
        //https
        static HostnameVerifier hv = new HostnameVerifier() {  
            public boolean verify(String urlHostName, SSLSession session) {  
                return true;  
            }  
        };  
        
        /**
         * 当前网址是否可用
         * @param remoteInetAddr
         * @return    
         */
        public static boolean connectingAddress(String remoteInetAddr){
            boolean flag=false;
            String tempUrl=remoteInetAddr.substring(0, 5);//取出地址前5位
            if(tempUrl.contains("http")){//判断传过来的地址中是否有http
                if(tempUrl.equals("https")){//判断服务器是否是https协议
                    try {
                        trustAllHttpsCertificates();//当协议是https时
                    } catch (Exception e) {
                        e.printStackTrace();
                    }  
                    HttpsURLConnection.setDefaultHostnameVerifier(hv);//当协议是https时
                }
                flag=isConnServerByHttp(remoteInetAddr);
            }else{//传过来的是IP地址
                flag=isReachable(remoteInetAddr);
            }
            return flag;
        }
        
        /**
         * 传入远程服务器的IP,返回是否连接成功
         *
         * @param remoteInetAddr
         * @return
         */
        public static boolean isReachable(String remoteInetAddr) {// IP地址是否可达,相当于Ping命令
            boolean reachable = false;
            try {
                InetAddress address = InetAddress.getByName(remoteInetAddr);
                reachable = address.isReachable(1500);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return reachable;
        }
     
        /**
         * 服务器连接检测
         * @param serverUrl
         * @return
         */
        public static boolean isConnServerByHttp(String serverUrl) {// 服务器是否开启
            boolean connFlag = false;
            URL url;
            HttpURLConnection conn = null;
            try {
                url = new URL(serverUrl);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3 * 1000);
                if (conn.getResponseCode() == 200) {// 如果连接成功则设置为true
                    connFlag = true;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                conn.disconnect();
            }
            return connFlag;
        }
        
        /*以下是Https适用*/
        private static void trustAllHttpsCertificates() throws Exception {  
            javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];  
            javax.net.ssl.TrustManager tm = new miTM();  
            trustAllCerts[0] = tm;  
            javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext  
                    .getInstance("SSL");  
            sc.init(null, trustAllCerts, null);  
            javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc  
                    .getSocketFactory());  
        }  
     
        //
        static class miTM implements javax.net.ssl.TrustManager,  
                javax.net.ssl.X509TrustManager {  
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
                return null;  
            }  
     
            public boolean isServerTrusted(  
                    java.security.cert.X509Certificate[] certs) {  
                return true;  
            }  
     
            public boolean isClientTrusted(  
                    java.security.cert.X509Certificate[] certs) {  
                return true;  
            }  
     
            public void checkServerTrusted(  
                    java.security.cert.X509Certificate[] certs, String authType)  
                    throws java.security.cert.CertificateException {  
                return;  
            }  
     
            public void checkClientTrusted(  
                    java.security.cert.X509Certificate[] certs, String authType)  
                    throws java.security.cert.CertificateException {  
                return;  
            }  
        }  
    }
    View Code

    服务器(centos)指定本地指令集

    package com.sunsheen.jfids.studio.monitor.utils.remote;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.util.Properties;
    
    import org.eclipse.core.runtime.Assert;
    
    import ch.ethz.ssh2.ChannelCondition;
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.StreamGobbler;
    
    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    import com.jcraft.jsch.SftpException;
    import com.sunsheen.jfids.studio.monitor.HKMonitor;
    import com.sunsheen.jfids.studio.monitor.HKMonitorFactory;
    import com.sunsheen.jfids.studio.monitor.common.LogInfo;
    
    /**
     * 输入指令到服务器执行
     * @author WangSong
     *
     */
    public class ServersDebugUtil {
        
        private static final HKMonitor monitor = HKMonitorFactory.getLogger(ServersDebugUtil.class.getName());
    
        private ServersDebugUtil(){}
        
        /**
         * 转换指令到服务器执行
         * @param command    要执行的指令
         */
        public static void transferCommand(String... commands){
            String romoteAddr = LogInfo.SERVERS_ADDRESS;
            String username = LogInfo.SERVERS_USERNAME;
            String password = LogInfo.SERVERS_PASSWORD;
            try {
                  Connection connection = new Connection(romoteAddr);// 创建一个连接实例
                  connection.connect();// Now connect
                  boolean isAuthenticated = connection.authenticateWithPassword(username, password);//認證
                  Assert.isTrue(isAuthenticated, "用戶名或密碼錯誤!");
                  ch.ethz.ssh2.Session sess = connection.openSession();// 創建一個會話
                  sess.requestPTY("bash");
                  sess.startShell();
                  InputStream stdout = new StreamGobbler(sess.getStdout());
                  InputStream stderr = new StreamGobbler(sess.getStderr());
                  BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
                  BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
                  //向服务器上输入命令
                  PrintWriter out = new PrintWriter(sess.getStdin());
                  for(String command : commands){
                      out.println(command);
                  }
                  out.close();
                  sess.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,100);
                  //关闭连接
                  sess.close();
                  connection.close();
                  stderrReader.close();
                  stdoutReader.close();
              } catch (IOException e) {
                  e.printStackTrace();
                  monitor.error("服务器执行指令出错:", e);
              }
        }
        
        /**
         * 文件夹校验
         * @param commands        进入对应文件夹指令集:第一个参数传log目录;第二个参数传用户log目录
         */
        public static void foldedrCheck(String... commands){
            String username = LogInfo.SERVERS_USERNAME;
            String password = LogInfo.SERVERS_PASSWORD;
            String address = LogInfo.SERVERS_ADDRESS;
            int port = LogInfo.SERVERS_FTP_PORT;
            
            ChannelSftp sftp = null;
            Channel channel = null;
            Session sshSession = null;
            int index = 0;//记录有异常文件夹的下标
            try {
                //创建连接
                JSch jsch = new JSch();
                sshSession = jsch.getSession(username, address, port);
                sshSession.setPassword(password);
                //获取session
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                sshSession.setConfig(sshConfig);
                sshSession.connect();
                //得到sftp
                channel = sshSession.openChannel("sftp");
                channel.connect();
                sftp = (ChannelSftp) channel;
                //进入文件夹
                for(int i=0;i<commands.length;i++){
                    index = i;
                    sftp.cd(commands[i]);//进入对应存放日志文件的目录
                }
                
            } catch (Exception e) {
                  if(e.toString().contains("No such file")){
                      System.out.println("服务器自动创建【"+commands[index]+"】文件夹");
                      try{
                          //创建父文件夹
                          if(index == 0){
                              sftp.mkdir(LogInfo.SERVERS_PARENT_USER_FOLDER);
                              System.out.println("服务器创建【"+ LogInfo.SERVERS_PARENT_USER_FOLDER+"】文件夹成功!");
                              monitor.info("服务器创建【"+ LogInfo.SERVERS_PARENT_USER_FOLDER+"】文件夹成功!");
                          }
                          //创建用户层
                          else if(index == 1){
                              sftp.mkdir(LogInfo.SERVERS_RECIVE_FOLDER);
                              System.out.println("服务器创建【"+ LogInfo.SERVERS_RECIVE_FOLDER+"】文件夹成功!");
                              monitor.info("服务器创建【"+ LogInfo.SERVERS_RECIVE_FOLDER+"】文件夹成功!");
                          }
                          //TODO 传入的其他指令
                          
                      }catch(SftpException e1){
                          e1.printStackTrace();
                          monitor.error("服务器创建用户层目录失败:"+e1);
    //                      System.exit(2);
                      }
              }
        }
        }
    }
    View Code

    服务器指定文件夹遍历

    package com.sunsheen.jfids.studio.monitor.utils.remote;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.eclipse.core.runtime.Assert;
    
    import ch.ethz.ssh2.ChannelCondition;
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.Session;
    import ch.ethz.ssh2.StreamGobbler;
    
    import com.sunsheen.jfids.studio.monitor.HKMonitor;
    import com.sunsheen.jfids.studio.monitor.HKMonitorFactory;
    import com.sunsheen.jfids.studio.monitor.common.LogInfo;
    import com.sunsheen.jfids.studio.monitor.timer.MonitorOffline;
    
    /**
     * 遍历出远程服务器上指定目录下的所有文件夹
     * 
     * @author WangSong
     *
     */
    public class ServersFolderUtil {
        private static final HKMonitor monitor = HKMonitorFactory.getLogger(ServersFolderUtil.class.getName());
    
        private ServersFolderUtil() {
        }
    
        /**
         * 得到服务器上指定文件夹下所有子文件夹(第一级子文件夹)
         * 
         * @return
         */
        public static List<Object> getSubfolderName(final String targetFolder) {
            final String romoteAddr = LogInfo.SERVERS_ADDRESS;
            final String username = LogInfo.SERVERS_USERNAME;
            final String password = LogInfo.SERVERS_PASSWORD;
    
            List<Object> folderNameList = new ArrayList<Object>();
            try {
                Connection connection = new Connection(romoteAddr);// 创建一个连接实例
                connection.connect();// 没有网络连接时,这一步会抛出连接异常
                boolean isAuthenticated = connection.authenticateWithPassword(username, password);// 認證
                Assert.isTrue(isAuthenticated, "用戶名或密碼錯誤!");
                ch.ethz.ssh2.Session sess = connection.openSession();// 創建一個會話
                sess.requestPTY("bash");
                sess.startShell();
                InputStream stdout = new StreamGobbler(sess.getStdout());
                InputStream stderr = new StreamGobbler(sess.getStderr());
                BufferedReader stdoutReader = new BufferedReader(
                        new InputStreamReader(stdout));
                BufferedReader stderrReader = new BufferedReader(
                        new InputStreamReader(stderr));
                // 向服务器上输入命令
                PrintWriter out = new PrintWriter(sess.getStdin());
                out.println("cd " + targetFolder);// 進入日志文件存放的目录
                out.println("ls -ld */");
                out.println("exit");
                out.close();
                /** 如果服务器没有返回信息过来,线程现在一直在c.wait这里,等待服务器返回信息将他唤醒。 **/
                // TODO 需要解决当前阻塞...
                 sess.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF|ChannelCondition.EXIT_STATUS,30000);
                 while (true) {
                     String line = stdoutReader.readLine();//当前读取到的整行数据
                     //数据读取完,退出
                     if (line == null)
                         break;
                     //取出文件夹
                     if(line.contains("drwxr-xr-x")){
                         //取出正确的文件夹名
                         StringBuffer sb = 
                                 new StringBuffer(line.substring(line.lastIndexOf(" "),line.lastIndexOf("/")));
                         line = sb.toString().replace(" ", "");
                         folderNameList.add(line); 
                     }
                 }
    
                // 关闭连接
                sess.close();
                connection.close();
                stderrReader.close();
                stdoutReader.close();
            } catch (IOException e) {
                //如果没有网络连接,离线记录日志文件
                if(e.toString().contains("There was a problem while connecting to")){
                    System.out.println("连接服务器失败:"+e);
                    monitor.error("连接服务器失败:", e);
                    //本地离线备份日志线程执行
                    final MonitorOffline mo = new MonitorOffline();
                    mo.monitor();
                }
    //            e.printStackTrace(System.err);
    //            System.exit(2);
            }
            return folderNameList;
        }
    
        /**
         * 返回当前目录下所有文件夹
         * @param remoteDir
         * @return
         */
        @Deprecated
        public static List<Object> getChildFolders(String remoteDir){
            List<Object> results = new ArrayList<Object>();//返回所有的文件夹名
            String[] resultArr = {};
            try {
                resultArr = getRemoteDirFileNames(remoteDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (String line : resultArr) {
    //            if (line.contains("drwxr-xr-x")) {
    //                // 取出正确的文件夹名
    //                StringBuffer sb = new StringBuffer(line.substring(
    //                        line.lastIndexOf(" "), line.lastIndexOf("/")));
    //                line = sb.toString().replace(" ", "");
    //                results.add(line);
    //            }
                System.out.println(line);
            }
            return results;
        }
        
        /**
         * 列出指定文件夹下所有文件
         * 
         * @param conn
         * @param remoteDir
         * @return
         * @throws IOException 
         */
         public static String[] getRemoteDirFileNames(String remoteDir) throws IOException{
         Connection conn = new Connection(LogInfo.SERVERS_ADDRESS);// 创建一个连接实例
         conn.connect();// Now connect
            boolean isAuthenticated = conn.authenticateWithPassword(
                    LogInfo.SERVERS_USERNAME, LogInfo.SERVERS_PASSWORD);// 認證
            Assert.isTrue(isAuthenticated, "用戶名或密碼錯誤!");
         Session sess=null;
         try {
             sess = conn.openSession();
             sess.execCommand("ls -lt "+remoteDir);
             InputStream stdout = new StreamGobbler(sess.getStdout());
             InputStream stderr = new StreamGobbler(sess.getStderr());
    
             byte[] buffer = new byte[100];
             String result = null;
             while (true) {
                 if ((stdout.available() == 0)) {
                     int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA |
                             ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 1000*5);
                     if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                         break;//超时后退出循环,要保证超时时间内,脚本可以运行完成
                     }
                     if ((conditions & ChannelCondition.EOF) != 0) {
                         if ((conditions & (ChannelCondition.STDOUT_DATA |
                                 ChannelCondition.STDERR_DATA)) == 0) {
                             break;
                         }
                     }
                 }
    
                 if(stdout!=null){
                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        int i;
                        while ((i = stdout.read()) != -1) {
                            baos.write(i);
                        }
                        String fileNames = baos.toString();
    
                        if (fileNames != null) {
                            String[] resultArr = fileNames.split("
    ");
                            return resultArr;
                 }
    
                 while (stderr.available() > 0) {
                     int len = stderr.read(buffer);
                     if (len > 0){
                         result += new String(buffer, 0, len);
                     }
                 }
             }
             }
             stdout.close();
             stderr.close();
         } catch (Exception e) {
    //         log.info("获取指定目录下文件列表失败:"+e.getMessage());
             System.out.println("获取指定目录下文件列表失败:"+e.getMessage());
         }finally {
             sess.close();
         }
         return null;
         }
         
    }
    View Code

    上传文件到服务器的ftp工具

    package com.sunsheen.jfids.studio.monitor.utils.remote;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.eclipse.core.runtime.Assert;
    
    import ch.ethz.ssh2.ChannelCondition;
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.Session;
    import ch.ethz.ssh2.StreamGobbler;
    
    import com.sunsheen.jfids.studio.monitor.HKMonitor;
    import com.sunsheen.jfids.studio.monitor.HKMonitorFactory;
    import com.sunsheen.jfids.studio.monitor.common.LogInfo;
    import com.sunsheen.jfids.studio.monitor.timer.MonitorOffline;
    
    /**
     * 遍历出远程服务器上指定目录下的所有文件夹
     * 
     * @author WangSong
     *
     */
    public class ServersFolderUtil {
        private static final HKMonitor monitor = HKMonitorFactory.getLogger(ServersFolderUtil.class.getName());
    
        private ServersFolderUtil() {
        }
    
        /**
         * 得到服务器上指定文件夹下所有子文件夹(第一级子文件夹)
         * 
         * @return
         */
        public static List<Object> getSubfolderName(final String targetFolder) {
            final String romoteAddr = LogInfo.SERVERS_ADDRESS;
            final String username = LogInfo.SERVERS_USERNAME;
            final String password = LogInfo.SERVERS_PASSWORD;
    
            List<Object> folderNameList = new ArrayList<Object>();
            try {
                Connection connection = new Connection(romoteAddr);// 创建一个连接实例
                connection.connect();// 没有网络连接时,这一步会抛出连接异常
                boolean isAuthenticated = connection.authenticateWithPassword(username, password);// 認證
                Assert.isTrue(isAuthenticated, "用戶名或密碼錯誤!");
                ch.ethz.ssh2.Session sess = connection.openSession();// 創建一個會話
                sess.requestPTY("bash");
                sess.startShell();
                InputStream stdout = new StreamGobbler(sess.getStdout());
                InputStream stderr = new StreamGobbler(sess.getStderr());
                BufferedReader stdoutReader = new BufferedReader(
                        new InputStreamReader(stdout));
                BufferedReader stderrReader = new BufferedReader(
                        new InputStreamReader(stderr));
                // 向服务器上输入命令
                PrintWriter out = new PrintWriter(sess.getStdin());
                out.println("cd " + targetFolder);// 進入日志文件存放的目录
                out.println("ls -ld */");
                out.println("exit");
                out.close();
                /** 如果服务器没有返回信息过来,线程现在一直在c.wait这里,等待服务器返回信息将他唤醒。 **/
                // TODO 需要解决当前阻塞...
                 sess.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF|ChannelCondition.EXIT_STATUS,30000);
                 while (true) {
                     String line = stdoutReader.readLine();//当前读取到的整行数据
                     //数据读取完,退出
                     if (line == null)
                         break;
                     //取出文件夹
                     if(line.contains("drwxr-xr-x")){
                         //取出正确的文件夹名
                         StringBuffer sb = 
                                 new StringBuffer(line.substring(line.lastIndexOf(" "),line.lastIndexOf("/")));
                         line = sb.toString().replace(" ", "");
                         folderNameList.add(line); 
                     }
                 }
    
                // 关闭连接
                sess.close();
                connection.close();
                stderrReader.close();
                stdoutReader.close();
            } catch (IOException e) {
                //如果没有网络连接,离线记录日志文件
                if(e.toString().contains("There was a problem while connecting to")){
                    System.out.println("连接服务器失败:"+e);
                    monitor.error("连接服务器失败:", e);
                    //本地离线备份日志线程执行
                    final MonitorOffline mo = new MonitorOffline();
                    mo.monitor();
                }
    //            e.printStackTrace(System.err);
    //            System.exit(2);
            }
            return folderNameList;
        }
    
        /**
         * 返回当前目录下所有文件夹
         * @param remoteDir
         * @return
         */
        @Deprecated
        public static List<Object> getChildFolders(String remoteDir){
            List<Object> results = new ArrayList<Object>();//返回所有的文件夹名
            String[] resultArr = {};
            try {
                resultArr = getRemoteDirFileNames(remoteDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (String line : resultArr) {
    //            if (line.contains("drwxr-xr-x")) {
    //                // 取出正确的文件夹名
    //                StringBuffer sb = new StringBuffer(line.substring(
    //                        line.lastIndexOf(" "), line.lastIndexOf("/")));
    //                line = sb.toString().replace(" ", "");
    //                results.add(line);
    //            }
                System.out.println(line);
            }
            return results;
        }
        
        /**
         * 列出指定文件夹下所有文件
         * 
         * @param conn
         * @param remoteDir
         * @return
         * @throws IOException 
         */
         public static String[] getRemoteDirFileNames(String remoteDir) throws IOException{
         Connection conn = new Connection(LogInfo.SERVERS_ADDRESS);// 创建一个连接实例
         conn.connect();// Now connect
            boolean isAuthenticated = conn.authenticateWithPassword(
                    LogInfo.SERVERS_USERNAME, LogInfo.SERVERS_PASSWORD);// 認證
            Assert.isTrue(isAuthenticated, "用戶名或密碼錯誤!");
         Session sess=null;
         try {
             sess = conn.openSession();
             sess.execCommand("ls -lt "+remoteDir);
             InputStream stdout = new StreamGobbler(sess.getStdout());
             InputStream stderr = new StreamGobbler(sess.getStderr());
    
             byte[] buffer = new byte[100];
             String result = null;
             while (true) {
                 if ((stdout.available() == 0)) {
                     int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA |
                             ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 1000*5);
                     if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                         break;//超时后退出循环,要保证超时时间内,脚本可以运行完成
                     }
                     if ((conditions & ChannelCondition.EOF) != 0) {
                         if ((conditions & (ChannelCondition.STDOUT_DATA |
                                 ChannelCondition.STDERR_DATA)) == 0) {
                             break;
                         }
                     }
                 }
    
                 if(stdout!=null){
                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        int i;
                        while ((i = stdout.read()) != -1) {
                            baos.write(i);
                        }
                        String fileNames = baos.toString();
    
                        if (fileNames != null) {
                            String[] resultArr = fileNames.split("
    ");
                            return resultArr;
                 }
    
                 while (stderr.available() > 0) {
                     int len = stderr.read(buffer);
                     if (len > 0){
                         result += new String(buffer, 0, len);
                     }
                 }
             }
             }
             stdout.close();
             stderr.close();
         } catch (Exception e) {
    //         log.info("获取指定目录下文件列表失败:"+e.getMessage());
             System.out.println("获取指定目录下文件列表失败:"+e.getMessage());
         }finally {
             sess.close();
         }
         return null;
         }
         
    }
    View Code

    通过http上传文件

    package com.sunsheen.jfids.studio.monitor.sender;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.Iterator;
    import java.util.Map;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.FormBodyPart;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.eclipse.core.runtime.Assert;
    
    /**
     * 發送日誌文件到服務器 :需要将文件打包压缩
     * 
     * @author WangSong
     *
     */
    public class SendLogByHttp {
    
        /**
         * 发送日志文件
         * @param url        远程地址
         * @param param        String类型的map数据,可以为空
         * @param file        上传的文件
         * @return
         * @throws ClientProtocolException
         * @throws IOException
         */
        public static String postFile(String url, Map<String, Object> param,
                File file) throws ClientProtocolException, IOException {
            
            String res = null;
            CloseableHttpClient httpClient = HttpClients.createDefault();//创建http客户端
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(getMutipartEntry(param, file));//设置发送的消息体
            
            CloseableHttpResponse response = httpClient.execute(httppost);//发送消息到指定服务器 
            
            HttpEntity entity = response.getEntity();
            
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                res = EntityUtils.toString(entity, "UTF-8");
                response.close();
            } else {
                res = EntityUtils.toString(entity, "UTF-8");
                response.close();
                throw new IllegalArgumentException(res);
            }
            return res;
        }
    
        //得到当前文件实体
        private static MultipartEntity getMutipartEntry(Map<String, Object> param,
                File file) throws UnsupportedEncodingException {
            Assert.isTrue(null == file, "文件不能为空!");
            
            FileBody fileBody = new FileBody(file);//通过文件路径,得到文件体
            FormBodyPart filePart = new FormBodyPart("file", fileBody);//格式化
            MultipartEntity multipartEntity = new MultipartEntity();
            multipartEntity.addPart(filePart);
    
            if(null != param){
                Iterator<String> iterator = param.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    FormBodyPart field = new FormBodyPart(key, new StringBody(
                            (String) param.get(key)));
                    multipartEntity.addPart(field);
                }
            }
    
            return multipartEntity;
        }
    
    }
    View Code

    通过socket上传文件

    package com.sunsheen.jfids.studio.monitor.sender;
    
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.Socket;
    
    /**
     * 通過socket通信,發送文件
     * @author WangSong
     *
     */
    public class SendLogBySocket {
    
        /**
         * 文件上傳
         * @param address    远程服务器地址
         * @param port        远程服务器开放的端口号
         * @param file        上传的文件
         */
        public static void postFile(String address,int port,File file) {
            Socket st = null;
            BufferedOutputStream bos = null;
            FileInputStream fis = null;
            try {
                //指定端口号
                //InetAddress.getLocalHost();
                st = new Socket(address,port);
                //要上传文件位置
                bos = new BufferedOutputStream(st.getOutputStream());
                fis = new FileInputStream(file);
                int len = 0;
                byte b[] = new byte[1024];
                //文件写入
                while ((len = fis.read(b)) != -1) {
                    bos.write(b, 0, len);
                    bos.flush();
                }
                System.out.println("客户端上传完成!");
            }
            catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    //关闭资源
                    fis.close();
                    bos.close();
                    st.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
    View Code
  • 相关阅读:
    安全参考和书安 NPM、PYPI、DockerHub 备份
    [NTT][组合]P4491 [HAOI2018]染色
    [主席树][哈希][最短路]CF464E The Classic Problem
    序章在那星雨之夜
    [二分][后缀数组]luogu P2463 [SDOI2008]Sandy的卡片
    GDOI 2021 退役记
    [后缀数组][单调栈]luogu P4248 [AHOI2013]差异
    [BFS]luogu P2536 [AHOI2005]病毒检测
    [多项式下降幂][组合][二项式定理]luogu P6620 [省选联考 2020 A 卷] 组合数问题
    AtCoder Regular Contest 116 总结
  • 原文地址:https://www.cnblogs.com/Soy-technology/p/12166849.html
Copyright © 2020-2023  润新知