项目总结——java工具类

Posted 喵喵7781

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了项目总结——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;

 

 

 

 

 

以上是关于项目总结——java工具类的主要内容,如果未能解决你的问题,请参考以下文章

项目总结——java工具类

常用高效 Java 工具类总结

java 树形结构工具类

Java验证工具类

179 01 Android 零基础入门 03 Java常用工具类02 Java包装类 03 包装类总结 01 Java中的包装类总结

Java 时间工具类 总结