項目總結——java工具類

目的:

1.抽象公共方法,避免重複造輪子

2.便於統一修改

 

工具類類型:

1.加載properties配置信息

1)Resource+Spring ClassPathResource

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.util.Properties;

public class DbUtil {

    private static final Logger logger = LoggerFactory.getLogger(DBConfig.class);

    public static final String JDBC_URL = "jdbc.url";
    public static final String JDBC_USERNAME ="jdbc.username";
    public static final String JDBC_PASSWORD="jdbc.password";

    private static final String DB_CONFIG = "db.properties";

    private static final Properties properties = new Properties();

    
    static {
        try {
            Resource resource = new ClassPathResource(DB_CONFIG);
            properties.load(resource.getInputStream());
        } catch (IOException e) {
            logger.error("Exception when loading config files", e.getMessage());
        }
    }

    public static String getProperties(String key) {
        return properties.getProperty(key);
    }
}

2)ResourceBundle

 static {
        ResourceBundle bundle = PropertyResourceBundle.getBundle("db");
        ENDPOINT = bundle.containsKey("jdbc.url") == false ? "" : bundle.getString("jdbc.url");
        ACCESS_KEY_ID = bundle.containsKey("oss.access.key.id") == false ? "" : bundle.getString("oss.access.key.id");
        ACCESS_KEY_SECRET = bundle.containsKey("jdbc.username") == false ? "" : bundle.getString("jdbc.username");
        BUCKET_NAME = bundle.containsKey("jdbc.password") == false ? "" : bundle.getString("jdbc.password");
}

2.文件操作

1)IO流轉byte[]數組

public static byte[] toByteArray(InputStream inStream) throws IOException {
	BufferedInputStream bufferedInputStream = new BufferedInputStream(inStream);
	ByteArrayOutputStream swapStream = new ByteArrayOutputStream();

	try{
		byte[] buff = new byte[1024];
		int rc = 0;
		while ((rc = bufferedInputStream.read(buff)) > 0) {
			swapStream.write(buff,0,rc);
		}
		return swapStream.toByteArray();

	}catch (Exception e){
		logger.error("根據inputStream讀取字節異常");
		throw new IOException(e.getMessage());

	}finally {
		if(swapStream!=null){
			swapStream.close();
		}
		inStream.close();

	}

}

2)獲取文件擴展名

	public static String getExtName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot >-1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			} 
	    }
		return null;
	}

3)獲取url網絡地址資源的文件size大小

public static long getFileLength(String downloadUrl) throws IOException {
		if (downloadUrl == null || "".equals(downloadUrl)) {
			return 0L;
		}
		URL url = new URL(downloadUrl);
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows 7; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 YNoteCef/5.8.0.1 (Windows)");
			return (long) conn.getContentLength();
		} catch (IOException e) {
			return 0L;
		} finally {
			conn.disconnect();
		}

	}

 

3.分佈式主鍵生成

snowflake算法

public class UUIDUtils {
    private static IdWorker idWorder;

    public UUIDUtils() {
    }

    public static synchronized long generateId() {
        return idWorder.nextId();
    }

    static {
        int machineNo = Integer.parseInt(LocalHostUtil.getLastSegment());
        idWorder = new IdWorker((long)machineNo);
    }


}



public class IdWorker {

    private final long workerId;
    private static final long twepoch = 1412092800000L;
    private long sequence = 0L;
    private static final long workerIdBits = 10L;
    private static final long maxWorkerId = 1023L;
    private static final long sequenceBits = 12L;
    private static final long workerIdShift = 12L;
    private static final long timestampLeftShift = 22L;
    private static final long sequenceMask = 4095L;
    private long lastTimestamp = -1L;

    public IdWorker(long workerId) {
        if(workerId <= 1023L && workerId >= 0L) {
            this.workerId = workerId;
        } else {
            throw new IllegalArgumentException(String.format("worker Id can\'t be greater than %d or less than 0", new Object[]{Long.valueOf(1023L)}));
        }
    }

    public synchronized long nextId() {
        long timestamp = this.timeGen();
        if(this.lastTimestamp == timestamp) {
            this.sequence = this.sequence + 1L & 4095L;
            if(this.sequence == 0L) {
                timestamp = this.tilNextMillis(this.lastTimestamp);
            }
        } else {
            this.sequence = 0L;
        }

        if(timestamp < this.lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", new Object[]{Long.valueOf(this.lastTimestamp - timestamp)}));
        } else {
            this.lastTimestamp = timestamp;
            return timestamp - 1412092800000L << 22 | this.workerId << 12 | this.sequence;
        }
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp;
        for(timestamp = this.timeGen(); timestamp <= lastTimestamp; timestamp = this.timeGen()) {
            ;
        }

        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }



}


public class LocalHostUtil {

    private static String localHost = null;

    public LocalHostUtil() {
    }

    public static void setLocalHost(String host) {
        localHost = host;
    }

    public static String getLocalHost() throws Exception {
        if(isNotBlank(localHost)) {
            return localHost;
        } else {
            localHost = findLocalHost();
            return localHost;
        }
    }

    private static String findLocalHost() throws SocketException, UnknownHostException {
        Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
        InetAddress ipv6Address = null;

        while(enumeration.hasMoreElements()) {
            NetworkInterface localHost = (NetworkInterface)enumeration.nextElement();
            Enumeration en = localHost.getInetAddresses();

            while(en.hasMoreElements()) {
                InetAddress address = (InetAddress)en.nextElement();
                if(!address.isLoopbackAddress()) {
                    if(!(address instanceof Inet6Address)) {
                        return normalizeHostAddress(address);
                    }

                    ipv6Address = address;
                }
            }
        }

        if(ipv6Address != null) {
            return normalizeHostAddress(ipv6Address);
        } else {
            InetAddress localHost1 = InetAddress.getLocalHost();
            return normalizeHostAddress(localHost1);
        }
    }

    private static boolean isNotBlank(String str) {
        return !isBlank(str);
    }


    private static boolean isBlank(String str) {
        int strLen;
        if(str != null && (strLen = str.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if(!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

    public static String normalizeHostAddress(InetAddress localHost) {
        return localHost instanceof Inet6Address?localHost.getHostAddress():localHost.getHostAddress();
    }

    public static String getLastSegment() {
        try {
            String e = getLocalHost();
            return e.substring(e.lastIndexOf(".") + 1);
        } catch (Exception var1) {
            return String.valueOf(System.currentTimeMillis() % 604800000L);
        }
    }
}

4.Http請求

import java.io.IOException;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class HttpManager {

    private static final int           DEFAULT_CONNECTION_REQUEST_TIMEOUT = 5000;
    private static final int           DEFAULT_CONNECT_TIMEOUT            = 3000;
    private static final int           DEFAULT_SOCKET_TIMEOUT             = 60000;

    private static final RequestConfig DEFAULT_REQUEST_CONFIG             = RequestConfig.custom()
            .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT).setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
            .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build();

    private static final int           DEFAULT_FAIL_STATUS                = -1;

    public static HttpResult<String> post(String uri, RequestBuilder builder) {
        builder.setUri(uri);
        builder.setCharset(Consts.UTF_8);
        builder.setConfig(DEFAULT_REQUEST_CONFIG);

        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;

        try {
            client = HttpClientBuilder.create().setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG)
                    .build();
            response = client.execute(builder.build());
            int statusCode = response.getStatusLine().getStatusCode();
            String errorMessage = response.getStatusLine().getReasonPhrase();
            if (statusCode != HttpStatus.SC_OK) {
                return HttpResult.fail(statusCode, errorMessage);
            }
            HttpEntity responseEntity = response.getEntity();
            String content = EntityUtils.toString(responseEntity, Consts.UTF_8);
            return HttpResult.success(content);
        } catch (Exception e) {
            return HttpResult.fail(DEFAULT_FAIL_STATUS, "請求出錯:" + e.getMessage());
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {

                }
            }

            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {

                }
            }
        }
    }

}

import org.apache.http.HttpStatus;

public class HttpResult<T> {

    private boolean success;
    private int     status;
    private String  message;
    private T       data;

    public static <T> HttpResult<T> success() {
        return success(null);
    }

    public static <T> HttpResult<T> success(T data) {
        HttpResult<T> result = new HttpResult<>();
        result.success = true;
        result.status = HttpStatus.SC_OK;
        result.data = data;
        return result;
    }

    public static <T> HttpResult<T> fail(int status, String message) {
        HttpResult<T> result = new HttpResult<>();
        result.success = false;
        result.status = status;
        result.message = message;
        return result;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "HttpResult{" +
                "success=" + success +
                ", status=" + status +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}

5.文件處理工具類

1)圖片添加水印

public static InputStream getWaterMarkStream(byte[] bytes, String waterMarkMsg,String directionCode){

        Color color=new Color(255, 0, 0, 255);//水印顏色
        Font font = new Font("微軟雅黑", Font.PLAIN, 30); //水印字體

        ByteArrayOutputStream outImgStream = null;
        try {
            InputStream origionSteam = new ByteArrayInputStream(bytes);
            Image srcImg = ImageIO.read(origionSteam);
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);
            //加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            g.setColor(color);
            g.setFont(font);


            int x = 0;
            int y = 0;

            if(directionCode.equals(WaterMarkDirectionEnum.NORTH.getDirectionCode())){
                 x = (srcImgWidth - g.getFontMetrics(g.getFont()).charsWidth(waterMarkMsg.toCharArray(), 0, waterMarkMsg.length()))/2;
                 y = srcImgHeight * 2 / 20;
            }else if (directionCode.equals(WaterMarkDirectionEnum.SOUTH.getDirectionCode())) {
                 x = (srcImgWidth - g.getFontMetrics(g.getFont()).charsWidth(waterMarkMsg.toCharArray(), 0, waterMarkMsg.length())) / 2;
                 y = srcImgHeight * 18 / 20;
            }else if (directionCode.equals(WaterMarkDirectionEnum.CENTER.getDirectionCode())){
                x = (srcImgWidth - g.getFontMetrics(g.getFont()).charsWidth(waterMarkMsg.toCharArray(), 0, waterMarkMsg.length())) / 2;
                y = srcImgHeight / 2;
            }

            g.drawString(waterMarkMsg, x, y);  //畫出水印
            g.dispose();

            outImgStream = new ByteArrayOutputStream();
            ImageIO.write(bufImg, "jpg", outImgStream);
            InputStream inputStream = new ByteArrayInputStream(outImgStream.toByteArray());
            return inputStream;

        } catch (IOException e) {
            throw  new SdkException("加水印失敗!");
        }finally {
            try {
                outImgStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

2)graphicsMagick多張圖片合成一張圖片

import org.im4java.core.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;


public class ImageUtil {

    // GraphicsMagick的安裝目錄,需要在linux上面安裝
    private static final String GRAPHICS_MAGICK_PATH ;

    static {
        GRAPHICS_MAGICK_PATH = FileConfig.getProperties(FileConfig.GRAPHICS_MAGICK_PATH);
    }

    //最大每張圖片寬度設置
    private static final Integer MAX_WIDTH = 600;

    //最大每張圖片高度設置
    private static final Integer MAX_HEIGHT =400;

    /**
     * 多張圖片合成一張圖片
     * @param bos 圖片信息集合:uuid ,localPicPath圖片本地地址
     * @param newpath 圖片合成後的臨時路徑
     * @param type 1:橫,2:豎
     */
    public static void montage(List<CoreLocalFileBo> bos , String newpath, String type) throws IOException, IM4JavaException, InterruptedException {

        Integer maxWidth = MAX_WIDTH;
        Integer maxHeight = MAX_HEIGHT;

        IMOperation op = new IMOperation();
        ConvertCmd cmd = new ConvertCmd(true);
        cmd.setSearchPath(GRAPHICS_MAGICK_PATH);

        if("1".equals(type)){
            op.addRawArgs("+append");
        }else if("2".equals(type)){
            op.addRawArgs("-append");
        }

        op.addRawArgs("-gravity","center");
        op.addRawArgs("-bordercolor","#ccc");
        op.addRawArgs("-border",1+"x"+1);
        op.addRawArgs("-bordercolor","#fff");

        for(CoreLocalFileBo coreLocalFileBo : bos){
           if(coreLocalFileBo.getFileType().equals("png")){
               BufferedImage image =  ImageIO.read(new File(coreLocalFileBo .getWholePicPath()));

                //獲取圖片像素點,如果是png格式的,透明的圖片,需要轉透明圖片爲白底圖片
               if((image.getRGB(1,1)>>24)==0){
                   IMOperation opPngImg = new IMOperation();
                   ConvertCmd cmdImg = new ConvertCmd(true);
                   cmdImg.setSearchPath(GRAPHICS_MAGICK_PATH);
                   opPngImg.addRawArgs("-channel","Opacity");
                   opPngImg.addImage(coreLocalFileBo.getWholePicPath());
                   opPngImg.addImage(coreLocalFileBo.getWholePicPath());
                   cmdImg.run(opPngImg);
                   opPngImg.dispose();
                   op.addImage(coreLocalFileBo.getWholePicPath());
               }else {
                   op.addImage(coreLocalFileBo.getWholePicPath());
               }
           }else {
               op.addImage(coreLocalFileBo.getWholePicPath());
           }
        }
        if("0".equals(type)){
            Integer whole_width = (1  + maxWidth  +1)* bos.size() ;
            Integer whole_height = maxHeight  + 1;
            op.addRawArgs("-extent",whole_width + "x" +whole_height);
        }else if("1".equals(type)){
            Integer whole_width = maxWidth  + 1;
            Integer whole_height = ( +1  + maxHeight  +  +1)* bos.size() ;
            op.addRawArgs("-extent",whole_width + "x" +whole_height);
        }
        op.addImage(newpath);
        try {
            cmd.run(op);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            op.dispose();
        }
    }

}

3)pdf合成

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import org.slf4j.LoggerFactory;

public  ByteArrayOutputStream createPdf(Map<String , byte[]> downlodFileMap ,List<WaterMarkDto> waterMarkDtos ) throws Exception {

        Document document = new Document(PageSize.A4, 10, 10, 10, 10);
        PdfWriter pdfWriter = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {

            pdfWriter = PdfWriter.getInstance(document, bos);
            pdfWriter.setViewerPreferences(PdfWriter.PageLayoutOneColumn);// 設置文檔單頁顯示
            document.open();

            byte[] ZERO = new byte[0];
            for (WaterMarkDto dto : waterMarkDtos) {
                if(Arrays.equals(downlodFileMap .get(dto.getUuid()),ZERO) ){
                    continue;
                }
                Image image = Image.getInstance(downlodFileMap .get(dto.getUuid()));
                image.setAlignment(Image.ALIGN_CENTER); // 居中顯示 Image.ALIGN_CENTER
                float imgWidth = image.getWidth();// 獲取圖片寬度
                float imgHeight = image.getHeight();// 獲取圖片高度
                if (imgWidth > imgHeight) {
                    document.setPageSize(PageSize.A4.rotate());
                } else {
                    document.setPageSize(PageSize.A4);
                }

                document.newPage();
                float width = document.getPageSize().getWidth() - 30;// 取頁面寬度並減去頁邊距
                float height = document.getPageSize().getHeight() - 40;// 取頁面高度並減去頁邊距
                image.scalePercent(width / imgWidth * 100, height / imgHeight * 100);
                String waterMsg =  dto.getWaterMarkMessage();
                if(waterMsg.getBytes().length > 78){
                    logger.info("waterMarkMessage原始長度爲{},太長截取部分",dto.getWaterMarkMessage().getBytes().length );
                    waterMsg = waterMsg.substring(0,26);
                }
                Chunk chunk = new Chunk(waterMsg);
                BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                Font font = new Font(bfChinese, 22, Font.NORMAL, new BaseColor(255, 0, 0));
                chunk.setFont(font);
                Paragraph paragraph = new Paragraph();
                paragraph.add(chunk);
                document.add(paragraph);
                document.add(image);
                document.addCreator("dragon");
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally {
            document.close();
            pdfWriter.close();
        }

        return bos;
}

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章