Common web tools

Time:2020-2-26

Necessary Java tool class and Middleware

<!-- Maps,Sets,CollectionUtils -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>28.1-jre</version>
        </dependency>
        <!-- StringUtils -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <! -- JSON special toolkit -- >
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

JSON tool class

Serverresponse – Generic JSON response object

Responsecode is an enumeration class that encapsulates code and desc

package com.mmall.common;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.Serializable;

/**
 *Represents the data object to be encapsulated in the response
 * @param <T>
 */
//Set that the returned JSON object does not have null. When serializing JSON, if it is a null object, the key will disappear
//@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@Jsoninclude (jsoninclude. Include. Non null) // fields whose JSON entity is converted to JSON null do not participate in serialization (that is, they are not displayed)
public class ServerResponse<T> implements Serializable {
    /**
     * status code
     *
     */
    private int status;
    /**
     *Relevant information of response (e.g. user name is not saved, password is wrong, etc.)
     */
    private String msg;
    /**
     *Encapsulated data object information
     */
    private T data;

    //Build private constructors to encapsulate public methods more elegantly
    private ServerResponse(int status){
        this.status = status;
    }
    private ServerResponse(int status,String msg){
        this.status = status;
        this.msg = msg;
    }
    private ServerResponse(int status,String msg,T data){
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
    private ServerResponse(int status,T data){
        this.status = status;
        this.data = data;

    }

    //Ignore this result in serializing JSON objects
    @JsonIgnore
    public boolean isSuccess(){
        return this.status == ResponseCode.SUCCESS.getCode();
    }

    public int getStatus() {
        return status;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    /**
     *Successful response, static method open to the public
     */
    public static <T> ServerResponse<T> createBySuccess(){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
    }
    //Respond only to success messages
    public static <T> ServerResponse<T> createBySuccessMessage(String msg){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
    }
    public static <T> ServerResponse<T> createBySuccess(T data){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);
    }
    //Create a successful server response, fill in the response information and object data
    public static <T> ServerResponse<T> createBySuccess(String msg,T data){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg, data);
    }

    /**
     *Failure response
     */
    public static <T> ServerResponse<T> createByError(){
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
    }
    //Respond only to failure information
    public static <T> ServerResponse<T> createByErrorMessage(String errorMessage){
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMessage);
    }

    /**
     *Expose a parameter side error response
     */
    public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMessage){
        return new ServerResponse<T>(errorCode,errorMessage);
    }

}

Jacksonutils – conversion tool class between JSON and POJO objects

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @Title JsonUtils.java
 * @Package com.aust.utils
 *@ description defines the JSON object format of the response and how to convert it to a JSON object
 * Copyright:Copyright (c) 2019
 * Company:anhui.aust.imooc
 * 
 * @author austwuhong
 * @date 2019/10/31 19:11 PM
 * @version v1.0
 */
public class JackSonUtils {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    
    /**
     *Convert object to string in JSON format
     * @param data 
     * @return
     */
    public static Object objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     *Convert JSON result set to object
     * @param <T>
     *@ param jsondata JSON data
     *@ param beantype object type
     * @return
     */
    public static <T> T jsonToPojo(String jsonData,Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
}

Gsonutil – Google’s JSON tool class gson converts normal JSON strings to POJO objects

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

class User {
    private String username;
    private int userId;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getUserId() {
        return userId;
    }
    public void setUserId(byte userId) {
        this.userId = userId;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", userId=" + userId + "]";
    }
}

/**
 *Google's JSON tool class, gson, converts ordinary JSON strings into POJO objects
 * @author Administrator
 *
 */
public class GSONUtil {
    
    /**
     *String in @ param jsondata JSON format
     *@ return JavaBean object
     */
    public <T> T getJSON(String jsonData) {
        Gson gson = new Gson();
        Type typeOfT = new TypeToken<T>(){}.getType();
        T t = gson.fromJson(jsonData, typeOfT);
        return t;
    }
    
    //Basic test
    public static void main(String[] args) {
        String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";  
        jsonData = "{" + 
                "            \"code\":200," + 
                "            \"message\":\"success\"," + 
                "            \"data\":\"{\"username\":\"arthinking\",\"userId\":001}\"" + 
                "    }";
        jsonData = "{\"username\":\"rachel\",\"userId\":123456}";
        
        Gson gson = new Gson();
        Type typeOfT = new TypeToken<User>(){}.getType();
        User users = gson.fromJson(jsonData, typeOfT);
        
        System. Out. Println ("parse JSON data");
//        for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
//            User user = iterator.next();
//            System.out.print(user.getUsername() + " | ");
//            System.out.println(user.getUserId());
//        }
        System.out.println(users);
    }
}

Cloneutils – object cloning tool class

Deep copy of objects through serialization and memory stream object stream
In fact, spring also has a tool class for copying beans

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *Deep copy of objects through serialization and memory stream object stream
 * @author Administrator
 *
 */
public class CloneUtils {
    
    //Prohibit instantiation
    private CloneUtils() {
        throw new AssertionError();
    }

    @SuppressWarnings("unchecked")
    public static <T> T clone(T obj) throws Exception {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bout);
        oos.writeObject(obj);
        
        //Input stream must determine source
        ByteArrayInputStream bis = new ByteArrayInputStream(bout.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        //Note forces the conversion from object to generic T. If the object type passed in is not t, an error may occur
        return (T) ois.readObject();
    }
}

Uploadutil – file upload tool class

Can be used to upload files in SSM framework

import java.io.File;
import java.io.IOException;

import org.springframework.web.multipart.MultipartFile;

public class UploadUtil {
    Private static string basepath = "D: \ \ repositories \ \ uploadfiles \ \"; // file upload and save path
    
    /**
     *Manage the saving of uploaded files
     * @param file
     *@ return if the upload file is saved successfully, a new file name will be returned. Otherwise, an empty "" will be returned
     */
    public static String saveFile(MultipartFile file) {
        try {
            //To prevent duplicate file names, you need to use random file name + file extension, but you should use the original file name when saving to the database (time stamp is not available, because it is possible to get the same time stamp in the case of multithreading)
            //UUID is not used, and the storage performance of UUID is not good
            String extName = file.getOriginalFilename();
            int index = extName.lastIndexOf(".");
            if(index > -1) {
                Extname = extname. Substring (index); // here, the parameter in substring cannot be - 1, otherwise an exception will be reported
            } else {
                extName = "";
            }
            //Random name + suffix name and save to basepath path path
            String newFileName = Math.random() + extName;
            File newFilePath = new File(basePath + newFileName);
            while(newFilePath.exists()) {
                newFileName = Math.random() + extName;
                newFilePath = new File(basePath + newFileName);
            }
            file.transferTo(newFilePath);
            return newFileName;
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}

Dbutil – JDBC connection special tool class

Save JDBC connection code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *Self custom tool class
 *Standard database tool class
 * @author Shiniad
 */
public class DBUtil {
    public static String username = "root";
    public static String password = "root";
    public static String driver = "com.mysql.jdbc.Driver";
    public static String url = "jdbc:mysql://127.0.0.1:3306/mywork?useUnicode=true&characterEncoding=utf8";
    
    Static string SQL = "insert into SYS [user (uname, upassword) values ('test ', 325)";
    
    public static Connection conn = null;
    public static Statement st = null;
    public static ResultSet rs = null;
    
    // additions and deletions
    public static int update() {
        int count = 0;
        try {
            Class. Forname (driver); // load driver
            Conn = drivermanager.getconnection (URL, username, password); // create connection
            St = conn.createstatement(); // execute SQL statement
            count = st.executeUpdate(sql);
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
            return 0;
        } catch(SQLException e) {
            e.printStackTrace();
            return 0;
        }
        
        return count;
    }
    
    // query
    public static ResultSet query() {
        
        try {
            Class. Forname (driver); // load driver
            Conn = drivermanager.getconnection (URL, username, password); // create connection
            St = conn.createstatement(); // execute SQL statement
            rs = st.executeQuery(sql);            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        
        return rs;    
    }
    //Close internal resources
    public static void closeSource() {
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    //Close external resources
    public static void closeSource(ResultSet rs, Statement st, Connection conn) {
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    /*
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        DBUtil.sql = "select * from sys_user";
        
        ResultSet rSet = DBUtil.query();
        while(rSet.next()) {
             System.out.println(rSet.getInt(1) + "\t" + rSet.getString(2));
        }
        //Insert operation of database
//Dbutil.sql = "insert into sys (uname, upassword) values ('test 2 ', 325)";
        
//        if(DBUtil.update()>0) {
//System. Out. Println ("added successfully");
//        } else {
//System. Out. Println ("add failed");
//        }
        
        //Close connection (close internal connection)
        DBUtil.closeSource();
        System.out.println(DBUtil.conn.isClosed());
    }
    */
}

Encryption tool class

Des – DES encryption tool class

import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


/**
 * 
 *Self custom tool class
 *Classic DES encryption
 *@ author macro
 */
public class DES {
    
    // encryption
    public static String encrypt(String content, String password) {
        byte[] contentByte = content.getBytes();
        byte[] passwordByte = password.getBytes();
        SecureRandom random = new SecureRandom();
        
        try {
            //Generate secret certificate
            DESKeySpec key = new DESKeySpec(passwordByte);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = factory.generateSecret(key);
            //Use certificate encryption
            Cipher cipher = Cipher.getInstance("DES");
            Cipher. Init (cipher. Encrypt? Mode, secret key, random); // configuration parameters
            byte[] result = cipher.doFinal(contentByte);
            //Base64 encryption, converting binary files to string format
            String contentResult = Base64.getEncoder().encodeToString(result);
            
            return contentResult;
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    // decryption
    public static byte[] decrypt(String password, byte[] result) {
        byte[] passwordByte = password.getBytes();
        SecureRandom random = new SecureRandom();
        
        try {
            //Generate secret certificate
            DESKeySpec key = new DESKeySpec(passwordByte);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = factory.generateSecret(key);
            
            // decryption
            Cipher decipher = Cipher.getInstance("DES");
            decipher.init(Cipher.DECRYPT_MODE, secretKey, random);
            byte[] de_result = decipher.doFinal(result);
            
            return de_result;
                
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    // decryption2
    public static byte[] decrypt(String password, String contentResult) {
        byte[] passwordByte = password.getBytes();
        byte[] result = Base64.getDecoder().decode(contentResult);
        SecureRandom random = new SecureRandom();
        
        try {
            //Generate secret certificate
            DESKeySpec key = new DESKeySpec(passwordByte);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = factory.generateSecret(key);
            
            // decryption
            Cipher decipher = Cipher.getInstance("DES");
            decipher.init(Cipher.DECRYPT_MODE, secretKey, random);
            byte[] de_result = decipher.doFinal(result);
            
            return de_result;
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static void main(String[] args) throws Exception {
        String content = "123456";
        String password = "unkonwnsecret"; // clear text password
        
        String contentResult = encrypt(content, password);
        System. Out. Println ("encrypted text:" + contentresult);
    
        if(contentResult!=null) {
            byte[] myByte = decrypt(password, contentResult);
            System. Out. Println ("decrypted text:" + new string (mybyte));
        }
        
        
//        //Generate secret certificate
//        DESKeySpec key = new DESKeySpec(password.getBytes());
//        SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
//Secretkey secretkey = factory. Generatesecret (key); // convert the plaintext password to the secret key certificate
//        //Use certificate encryption
//        Cipher cipher = Cipher.getInstance("DES");
//        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//        byte[] result = cipher.doFinal(content.getBytes());
//// Base64 transcoding
//        String base64Result = Base64.getEncoder().encodeToString(result);
    }

}

MD5 – MD5 encryption tool class

In the same way as SHA1, replace MD5 with SHA1

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 *Self custom class
 *Encryption algorithm MD5 / SHA1
 * @author Shiniad
 *
 */
public class MD5 {
    public static String contentResult;
    public static String salt;
    
    public static void encrypt(String password) {
        MD5.contentResult = null;
        MD5.salt = null;
        
        SecureRandom random = new SecureRandom();
        String salt = string. Valueof (random. Nextdouble()); // random salt
        
        String contentResult = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] result = md.digest((password).getBytes());
            contentResult = ByteArrayUtil.bytesToHex(result);
            if(contentResult!=null && salt!=null) {
                MD5.contentResult = contentResult;
                MD5.salt = salt;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    
    public static boolean verification(String salt,String secretKey) {
        System. Out. Print ("please enter password validation:");
        java.util.Scanner in = new java.util.Scanner(System.in);
        String password = in.nextLine();
        
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] result = md.digest((password+salt).getBytes());
            
            String contentResult = ByteArrayUtil.bytesToHex(result);
            if(contentResult.equals(secretKey)) {
                System. Out. Println ("the password you entered is correct. "";
                in.close();
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System. Out. Println ("the password you entered is wrong! "";
        in.close();
        return false;
    }
    
    //Basic test
    public static void main(String[] args) throws Exception {
        String password = "123456";
        
        encrypt(password);
        System. Out. Println ("salt value is:" + MD5. Salt + ", key is:" + MD5. Contentresult);
        
        while( !MD5.verification(MD5.salt, MD5.contentResult) ) {
            MD5.verification(MD5.salt, MD5.contentResult);
        }
        
//Core API of MD5
//        MessageDigest md = MessageDigest.getInstance("MD5");
//        byte[] result = md.digest(password.getBytes());
    }
}

Bytearrayutil – a byte conversion utility class that converts a byte / byte array to a hexadecimal number (string format)

/**
 *Self custom tool class
 *Byte conversion tool, convert byte / byte array to hexadecimal number (string format)
 *@ author macro
 */
public class ByteArrayUtil {
    
    public static String byteToHex(byte b) {
        String hex = integer.tohexstring (B & 0xff); // sum B with constant (1111 1111) sub2, and set the value of random bits of the first three bytes to 0
        if(hex.length() < 2) {
            Hex = "0" + hex; // mark a bitinteger as a hexadecimal number
        }
        return hex;
    }
    
    public static String bytesToHex(byte[] b) {
        StringBuffer sb = new StringBuffer();
        String str = "";
        for (byte c : b) {
            str = byteToHex(c);
            sb.append(str);
        }
        return new String(sb);
    }
}

File2multipartfileutil – file to multipartfile tool class

public class File2MultipartFileUtil{
        public static MultipartFile getMultipartFile(String filePath) {
        File file = new File(filePath);
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(file.getName(), "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[4096];
        try(FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream()) {
            while((bytesRead=fis.read(buffer, 0, 4096)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            throw new RuntimeException("getMultipartFile error:" + e.getMessage());
        }
        MultipartFile cFilePath = new CommonsMultipartFile(item);
        return cFilePath;
    }
}

Sendmailutil – Java toolkit for sending mail

package com.mydemo.project.utils;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendMailUtil {
    private static final Logger logger = LoggerFactory.getLogger(SendMailUtil.class);
    
    /**
     * 
     *@ param subject email subject
     *@ param content email content (can be HTML)
     *@ param toemailaddres to
     * @param log
     * @throws MessagingException 
     */
    @SuppressWarnings("restriction")
    public static void sendMail(String subject,String content,String toEmailAddres) throws MessagingException {
             String host = "SMTP. 163. Com"; // email server address
            String port = "465"; // port 25 / 587 for sending mail
            String auth = "true"; // whether authentication is required depends on the calling mailbox. For example, QQ mailbox is required. Otherwise, sending fails
            String protocol = "SMTP"; // transport protocol
            String Mailfrom = "1 * 5 @ 163. Com"; // sender's email
            String personalname = "1 * 5"; // sender's mailbox alias
            String username = "1 * 5 @ 163. Com"; // sender's email username
            String password = "*"; // sender's email password, 163 email uses authorization code
            String maildebug = "false"; // enable debug or not
            String contenttype = null; // message body type

            Security.addprovider (new com. Sun. Net. SSL. Internal. SSL. Provider()); // SSL authentication
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", auth == null ? "true" : auth);
            props.put("mail.transport.protocol", protocol == null ? "smtp" : protocol);
            props.put("mail.smtp.port", port == null ? "25" : port);
            props.put("mail.debug", mailDebug == null ? "false" : mailDebug);
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            Session mailSession = Session.getInstance(props);
            
            //Set session to communicate with mail server.
            MimeMessage message = new MimeMessage(mailSession);
            //Set message subject
            message.setSubject(subject);
            //Set message body
            message.setContent(content, contentType == null ? "text/html;charset=UTF-8" : contentType);
            //Set mail send date
            message.setSentDate(new Date());
            InternetAddress address = null;
            try {
                address = new InternetAddress(mailFrom, personalName);
            } catch (UnsupportedEncodingException e) {
                Logger.info ("IP address encoding exception: {}", e.getmessage());
                e.printStackTrace();
            }
            //Set the address of the mail sender
            message.setFrom(address);
            //Set the address of the mail receiver
            message.setRecipients(Message.RecipientType.TO, toEmailAddres);
            Transport transport = null;
            transport = mailSession.getTransport();
            message.saveChanges();
     
            transport.connect(host, username, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
    }
    
    public static void main(String[] args) {
        String subject = "from java";
        String content = "<h1>hello world!</h1>";
        String toEmailAddres = "7*@qq.com";
        try {
            sendMail(subject, content, toEmailAddres);
            System. Out. Println ("email sent successfully");
        } catch (MessagingException e) {
            Logger.info ("failed to send message: {}", e.getmessage());
            e.printStackTrace();
        }
    }
}

Other reference websites
https://www.jianshu.com/p/d36…
Common guava kits
Commonly used are preconditions pre verification / lists / maps tool classes
https://www.baidu.com/link?ur…
https://blog.csdn.net/Munger6…
Commons IO Toolkit
FileUtils – a very powerful tool for file byte array

Recommended Today

Incomplete delivery order log of SAP SD basic knowledge

Incomplete delivery order log of SAP SD basic knowledge   If we call the incomplete project log, the system checks whether the data in the outbound delivery is complete. From the generated list, we can directly jump to the screen of maintaining incomplete fields.   We can call log of incomplete items from delivery processing, […]