工具类随写[copy|unzip|http|yml读写]

 

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crux.common.exception.InnerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.InputStreamResource;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Utils {
    protected final static Logger log = LoggerFactory.getLogger(Utils.class);

    private static final String ENCODING = "utf-8";

    private static final String PROJECT = PathUtil.PROJECT_JS;

    private static final String PARAMS = PathUtil.PARAMS_JS;
    public static final String PROJECT_PATH = "projectPath";

    public static final Integer PROJECT_TYPE = 1;

    public static final Integer PARAMS_TYPE = 2;

    public static Boolean isWin() {
        return System.getProperty("os.name").indexOf("Windows") > -1;
    }

    private static FileWriter fileWriter = null;

    /**
     * 加载项目类别
     *
     * @return
     */
    public static JSONArray loadData(Integer type) {
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader reader = null;
        String jsType = type == PROJECT_TYPE ? PROJECT : PARAMS;
        try {
            File file = new File(jsType);
            is = new FileInputStream(file);
            isr = new InputStreamReader(is, ENCODING);
            reader = new BufferedReader(isr);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (InnerException | IOException e) {
            throw new InnerException("加载项目类别异常" + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                throw new InnerException("关闭加载项目类别流异常" + e.getMessage());
            }
        }
        return JSONObject.parseArray(sb.toString());
    }

    public static void writeParam(JSONArray js, Integer type) {
        String jsType = type == PROJECT_TYPE ? PROJECT : PARAMS;
        File file = new File(jsType);
        OutputStreamWriter out = null;
        log.debug("fileConent" + js.toJSONString());
        try {
            out = new OutputStreamWriter(new FileOutputStream(file), ENCODING);
            out.write(js.toJSONString());
            out.flush();
        } catch (InnerException | IOException e) {
            throw new InnerException("将配置写入文件异常" + e.getMessage());
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static JSONObject getProject(String key) {
        JSONArray js = loadData(PROJECT_TYPE);
        for (int i = 0; i < js.size(); i++) {
            JSONObject j = js.getJSONObject(i);
            if (j.get("id").equals(key)) {
                return j;
            }
        }
        return null;
    }

    public static void copy(InputStream in, File dst) {
        int BUFFER_SIZE = 4096;
        OutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (InnerException | IOException e) {
            throw new InnerException("上传复制补丁包异常" + e.getMessage());
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                out = null;
            }
        }
    }

    public static void unZip(String zipFilePath, String desPath) {
        try {
            ZipInputStream zin = new ZipInputStream(new FileInputStream(
                    zipFilePath));//输入源zip路径
            BufferedInputStream bin = new BufferedInputStream(zin);
            File fout = null;
            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                fout = new File(desPath, entry.getName());
                if (!fout.exists()) {
                    (new File(fout.getParent())).mkdirs();
                }
                if (entry.isDirectory()) {
                    new File(entry.getName()).mkdirs();
                    continue;
                }
                FileOutputStream out = new FileOutputStream(fout);
                BufferedOutputStream Bout = new BufferedOutputStream(out);
                int b;
                while ((b = bin.read()) != -1) {
                    Bout.write(b);
                }
                Bout.close();
                out.close();
                System.out.println(fout + "解压成功");
            }
            bin.close();
            zin.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new InnerException("解压补丁异常:" + e.getMessage());
        }
    }

    public static void rollBack(String zipFilePath, String desPath) {
        try {
            ZipInputStream zin = new ZipInputStream(new FileInputStream(
                    zipFilePath));//输入源zip路径
            File fout = null;
            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                fout = new File(desPath, entry.getName());
                if (!fout.exists()) {
                    break;
                }
                if (entry.isDirectory()) {
                    continue;
                } else {
                    if (fout.exists())
                        fout.delete();
                    System.out.println(fout.getName() + "----" + fout.getAbsolutePath());
                }
            }
            zin.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new InnerException("撤销补丁文件异常:" + e.getMessage());
        }
    }

    public static void writeConfig(File file, JSONObject jb) {
        try {
            YamlMapFactoryBean mapFactoryBean = new YamlMapFactoryBean();
            mapFactoryBean.setResources(new InputStreamResource(new FileInputStream(file)));
            Map<String, Object> map = mapFactoryBean.getObject();
            Iterator en = map.entrySet().iterator();
            fileWriter = new FileWriter(file);
            while (en.hasNext()) {
                Map.Entry entry = (Map.Entry) en.next();
                if (entry.getValue() instanceof LinkedHashMap) {
                    System.out.println(entry.getKey() + ":");
                    fileWriter.write(entry.getKey() + ":" + System.getProperty("line.separator"));
                    tran((LinkedHashMap) entry.getValue(), 1);
                } else {
                    fileWriter.write(entry.getKey() + ": " + entry.getValue() + System.getProperty("line.separator"));
                    System.out.println(entry.getKey() + ": " + entry.getValue());
                }
            }
            fileWriter.flush();
            fileWriter.close();
        } catch (Exception e) {
            throw new InnerException("写入yml配置文件异常" + e.getMessage());
        }
    }

    public static void tran(Map<String, Object> linkedHashMap, int len) throws IOException {
        for (Map.Entry<String, Object> entry : linkedHashMap.entrySet()) {
            if (entry.getValue() instanceof LinkedHashMap) {
                fileWriter.write(nullNum(len) + entry.getKey() + ":" + System.getProperty("line.separator"));
                System.out.println(nullNum(len) + entry.getKey() + ":");
                tran((LinkedHashMap) entry.getValue(), len + 1);
            } else {
                if (entry.getValue() instanceof ArrayList) {
                    fileWriter.write(nullNum(len) + entry.getKey() + ":" + System.getProperty("line.separator"));
                    System.out.println(nullNum(len) + entry.getKey() + ":");
                    for (int i = 0; i < ((ArrayList) entry.getValue()).size(); i++) {
                        fileWriter.write(nullNum(len + 1) + "- " + ((ArrayList) entry.getValue()).get(i) + System.getProperty("line.separator"));
                        System.out.println(nullNum(len + 1) + "- " + ((ArrayList) entry.getValue()).get(i));
                    }
                } else {
                    String v = entry.getValue() == null ? "" : String.valueOf(entry.getValue());
                    if (v.equals("*")) //
                        v = "\"*\"";
                    fileWriter.write(nullNum(len) + entry.getKey() + ": " + v + System.getProperty("line.separator"));
                    System.out.println(nullNum(len) + entry.getKey() + ": " + entry.getValue());
                }
            }
        }
    }

    private static String nullNum(int len) {
        String s = "  ";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(s);
        }
        return sb.toString();
    }

    public static Integer callCmd(String locationCmd) {
        try {
            File file = new File(PathUtil.TOMCAT_BIN_PATH);
            ProcessBuilder process = new ProcessBuilder(locationCmd);
            process.directory(file);
            process.redirectErrorStream(true);
            process.start();
//            String success = consumeInputStream(p.getInputStream());
//            String error = consumeInputStream(p.getErrorStream());
//            log.debug("-=---------------------" + success);
//            log.debug("-=---------------------" + error);
            return 0;
//            try {
//                return   p.exitValue();
//            } catch (InterruptedException e) {
//                throw new InnerException("服务操作异常" + e.getMessage());
//            }
        } catch (IOException e) {
            throw new InnerException("服务操作异常" + e.getMessage());
        }
    }

    public static String consumeInputStream(InputStream is) {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String s = null;
        StringBuilder sb = new StringBuilder();
        try {
            while ((s = br.readLine()) != null) {
                sb.append(s + "\n");
                log.debug("-----------" + s);
            }
        } catch (Exception e) {
            throw new InnerException(e.getMessage());
        }
        return sb.toString();
    }

    public static int sendGet(String url) {
        HttpURLConnection httpConn = null;
        try {
            java.net.URL connURL = new java.net.URL(url);
            // 打开URL连接
            httpConn = (java.net.HttpURLConnection) connURL
                    .openConnection();
            // 设置通用属性
            httpConn.setConnectTimeout(1000);
            httpConn.setReadTimeout(1000);
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            // 建立实际的连接
            httpConn.connect();
            int state = httpConn.getResponseCode();
            return state;
        } catch (Exception e) {
            e.printStackTrace();
            return HttpURLConnection.HTTP_INTERNAL_ERROR;
        } finally {
            if (httpConn != null)
                httpConn.disconnect();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值