“This is the 30th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

The background,

I have seen many open source automation frameworks on GitHub that come with a lot of Util utility classes. We also need to use the utility class library when developing automation frameworks, so this will bring some problems:

  • The cost of learning the API
  • Repeat the wheel
  • Bugs caused by poor encapsulation

So, is there a good universal wheel that we can use directly? Of course, today we will introduce the tool class library – Hutool

2. Introduction to Hutool

Hutool is a small and complete Java tool class library, through the static method encapsulation, reduce the cost of learning related API, improve work efficiency, make Java has the elegant functional language, let the Java language can also be “sweet”. The tools and methods in Hutool come from the elaboration of each user. It covers all aspects of the underlying code of Java development. It is not only a sharp tool to solve small problems in large project development, but also an efficiency responsibility in small projects. Hutool is a friendly alternative to the util package in a project. It saves developers the time to encapsulate common classes and common tool methods in a project, enables development to focus on the business, and avoids bugs caused by incomplete encapsulation to the maximum.

The above is an introduction from the official website. If we need to use some tools and methods, we might as well look for them in Hutool.

Official website: github.com/looly/hutoo…

Hutool contains components

Util utility class a Java basic utility class that encapsulates JDK methods such as files, streams, encryption and decryption, transcoding, re, threads, and XML. Util utility classes provide the following components:

The module introduce
hutool-aop JDK dynamic proxy encapsulation, providing non-IOC aspect support
hutool-bloomFilter Bloom filtering, which provides some Hash algorithms for Bloom filtering
hutool-cache Simple cache implementation
hutool-core Core, including Bean operations, dates, various utils, and so on
hutool-cron Scheduled task module that provides scheduled tasks like Crontab expressions
hutool-crypto Encryption and decryption module, providing symmetric, asymmetric and digest algorithm encapsulation
hutool-db JDBC encapsulated data manipulation, based on ActiveRecord ideas
hutool-dfa Multi-keyword search based on DFA model
hutool-extra Extension module, encapsulation for third parties (template engine, mail, Servlet, TWO-DIMENSIONAL code, Emoji, FTP, word segmentation, etc.)
hutool-http Http client encapsulation based on HttpUrlConnection
hutool-log Automatic identification of log facade of log implementation
hutool-script Scripts perform encapsulation, such as Javascript
hutool-setting More powerful Setting profile and Properties wrapper
hutool-system System parameters call encapsulation (JVM information, etc.)
hutool-json JSON implementation
hutool-captcha Image verification code implementation
hutool-poi Excel and Word encapsulation for POI
hutool-socket NIO and AIO Socket encapsulation based on Java

Each module can be imported individually as required, or all modules can be imported by hutool-all.

Four, installation,

1, Maven

Add the following to the project’s PM.xml dependencies:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.4.2</version>
</dependency>
Copy the code

2, Gradle

The compile 'cn. Hutool: hutool -all: 5.4.2'Copy the code

3. Non-maven projects

Click one of the following links to download hutool -all-x.x.x. jar:

  • Maven Central Library 1
  • Maven Central Library 2

Note that Hutool 5.x supports JDK8+. There is no test for The Android platform and no guarantee that all tool classes or tool methods are available. If your project uses JDK7, use Hutool version 4.x

5. Common tools

1, the Convert

Type conversion utility class for converting various types of data.

@test (description = "Convert use: type conversion utility class ")
public void covert(a) {
	int a = 1;
	String aStr = Convert.toStr(a);
	// Convert to an array of the specified type
	String[] b = {"1"."2"."3"."4"};
	Integer[] bArr = Convert.toIntArray(b);
	log.info(bArr.toString());

	// Convert to a date object
	String dateStr = "2020-09-17";
	Date date = Convert.toDate(dateStr);
	log.info(date.toString());

	// Convert to a list
	String[] strArr = {"a"."b"."c"."d"};
	List<String> strList = Convert.toList(String.class, strArr);
	log.info(strList.toString());
}
Copy the code

Running results:

[Ljava.lang.Integer;@4c0884e8
Thu Sep 17 00:00:00 CST 2020
[a, b, c, d]
Copy the code

2, DateUtil

The datetime utility class defines some common datetime manipulation methods.

@test (description = "DateUtil use: datetime tool ")
public void dateUtil(a) {
	// Convert between Date, long, and Calendar
	// The current time
	Date date = DateUtil.date();
	log.info(date.toString());
	/ / the Calendar Date
	date = DateUtil.date(Calendar.getInstance());
	// Change the timestamp to Date
	date = DateUtil.date(System.currentTimeMillis());
	// Automatically recognize format conversion
	String dateStr = "2020-09-17";
	date = DateUtil.parse(dateStr);
	// Custom formatting conversion
	date = DateUtil.parse(dateStr, "yyyy-MM-dd");
	// Format the output date
	String format = DateUtil.format(date, "yyyy-MM-dd");
	log.info(format.toString());
	// Get the year portion
	int year = DateUtil.year(date);
	// Get the months, counting from 0
	int month = DateUtil.month(date);
	// Get the start and end times of a day
	Date beginOfDay = DateUtil.beginOfDay(date);
	Date endOfDay = DateUtil.endOfDay(date);
	// Calculate the offset date and time
	Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
	// Calculate the offset between date and time
	long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);
}
Copy the code

Running results:

The 2020-09-17 18:42:22 2020-09-17Copy the code

3, StrUtil

The string utility class defines some common string manipulation methods.

@test (description = "StrUtil use: string tool ")
public void strUtil(a) {
	// Check for an empty string
	String str = "test";
	StrUtil.isEmpty(str);
	StrUtil.isNotEmpty(str);
	// Remove the prefix and suffix of the string
	StrUtil.removeSuffix("a.jpg".".jpg");
	StrUtil.removePrefix("a.jpg"."a.");
	// Format a string
	String template = "This is just a placeholder :{}";
	String str2 = StrUtil.format(template, "I'm a placeholder.");
	log.info("/strUtil format:{}", str2);
}
Copy the code

Running results:

/strUtil format: This is just a placeholder: I am a placeholderCopy the code

4, ClassPathResource

Get files in the classPath, which is usually web-INF /classes in containers such as Tomcat.

@test (description = "ClassPath single resource access class: find files in ClassPath ")
public void classPath(a) throws IOException {
	// Get the configuration files defined in the SRC /main/resources folder
	ClassPathResource resource = new ClassPathResource("generator.properties");
	Properties properties = new Properties();
	properties.load(resource.getStream());
	log.info("/classPath:{}", properties);
}
Copy the code

Running results:

/classPath:{jdbc.userId=root, jdbc.password=root, jdbc.driverClass=com.mysql.cj.jdbc.Driver, jdbc.connectionURL=jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai}
Copy the code

5, ReflectUtil

Java reflection utility class, which can be used to reflect methods that get classes and create objects.

@test (description = "ReflectUtil use: Java ReflectUtil utility class ")
public void reflectUtil(a) {
	// Get all the methods of a class
	Method[] methods = ReflectUtil.getMethods(Dog.class);
	// Gets the specified method of a class
	Method method = ReflectUtil.getMethod(Dog.class, "getName");
	// Use reflection to create objects
	Dog dog = ReflectUtil.newInstance(Dog.class);
	// reflect the method of executing the object
	ReflectUtil.invoke(dog, "setName"."Rhubarb");
	log.info(dog.getName());
}
Copy the code

Dog

Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Dog {
	private String name;
	private Float weight;
}
Copy the code

Running results:

rhubarbCopy the code

6, NumberUtil

Number processing tool class, can be used for various types of numbers of addition, subtraction, multiplication and division operations and judgment type.

@test (description = "NumberUtil ")
public void numberUtil(a) {
	double n1 = 1.234;
	double n2 = 1.234;
	double result;
	// Add, subtract, multiply and divide float, double, BigDecimal
	result = NumberUtil.add(n1, n2);
	result = NumberUtil.sub(n1, n2);
	result = NumberUtil.mul(n1, n2);
	result = NumberUtil.div(n1, n2);
	// Keep two decimal places
	BigDecimal roundNum = NumberUtil.round(n1, 2);
	String n3 = "1.234";
	// Check whether it is a number, integer, or floating point
	NumberUtil.isNumber(n3);
	NumberUtil.isInteger(n3);
	NumberUtil.isDouble(n3);
}
Copy the code

7, BeanUtil

JavaBean tool class, which can be used to convert Map and JavaBean objects and copy object attributes.

@test (description = "BeanUtil use: JavaBean utility class ")
public void beanUtil(a) {
	Dog dog = new Dog();
	dog.setName("Rhubarb");
	dog.setWeight(5.14 f);

	/ / Bean Map
	Map<String, Object> map = BeanUtil.beanToMap(dog);
	log.info("beanUtil bean to map:{}", map);
	/ / Map Bean
	Dog mapDog = BeanUtil.mapToBean(map, Dog.class, false);
	log.info("beanUtil map to bean:{}", mapDog);
	// Copy Bean properties
	Dog copyDog = new Dog();
	BeanUtil.copyProperties(dog, copyDog);
	log.info("beanUtil copy properties:{}", copyDog);
}
Copy the code

Running results:

BeanUtil bean to map:{name= rhubarb, weight=5.14} beanUtil map to bean:Dog(name= rhubarb, BeanUtil Copy Properties :Dog(name= rhubarb, weight=5.14)Copy the code

8 CollUtil.

The collection operations utility class defines some common collection operations.

@test (description = "CollUtil use: Collection utility class ")
public void collUtil(a) {
	// Array is converted to list
	String[] array = new String[]{"a"."b"."c"."d"."e"};
	List<String> list = CollUtil.newArrayList(array);
	//join: add join symbol when array is converted to string
	String joinStr = CollUtil.join(list, ",");
	log.info("collUtil join:{}", joinStr);
	// Convert a concatenated string to a list
	List<String> splitList = StrUtil.split(joinStr, ', ');
	log.info("collUtil split:{}", splitList);
	// Create a new Map, Set, List
	HashMap<Object, Object> newMap = CollUtil.newHashMap();
	HashSet<Object> newHashSet = CollUtil.newHashSet();
	ArrayList<Object> newList = CollUtil.newArrayList();
	// Check whether the list is empty
	CollUtil.isEmpty(list);
	CollUtil.isNotEmpty(list);
}
Copy the code

Running results:

collUtil join:a,b,c,d,e
collUtil split:[a, b, c, d, e]
Copy the code

9 MapUtil.

Map operation tool class, used to create a Map object and determine whether the Map is empty.

@test (description = "MapUtil use: Map utility class ")
public void mapUtil(a) {
	// Add multiple key-value pairs to the Map
	Map<Object, Object> map = MapUtil.of(new String[][]{
			{"key1"."value1"},
			{"key2"."value2"},
			{"key3"."value3"}});// Check whether Map is empty
	MapUtil.isEmpty(map);
	MapUtil.isNotEmpty(map);
}
Copy the code

10, SecureUtil

Encryption and decryption tool class, can be used for MD5 encryption.

@test (description = "SecureUtil use: SecureUtil tool class ")
public void secureUtil(a) {
	/ / the MD5 encryption
	String str = "123456";
	String md5Str = SecureUtil.md5(str);
	log.info("secureUtil md5:{}", md5Str);
}
Copy the code

Running results:

secureUtil md5:e10adc3949ba59abbe56e057f20f883e
Copy the code

11, CaptchaUtil

Captcha tool class that can be used to generate graphic captcha.

@test (description = "CaptchaUtil use: graphic CaptchaUtil ")
public void captchaUtil(HttpServletRequest request, HttpServletResponse response) {
	// Generate a captcha image
	LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200.100);
	try {
		request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
		response.setContentType("image/png");// Tell the browser to output as a picture
		response.setHeader("Pragma"."No-cache");// Disable browser caching
		response.setHeader("Cache-Control"."no-cache");
		response.setDateHeader("Expire".0);
		lineCaptcha.write(response.getOutputStream());
	} catch(IOException e) { e.printStackTrace(); }}Copy the code

12, the Validator

A field validator that verifies that a given string meets a specified condition. It is commonly used in form field validation.

@test (description = "Validator: field Validator ")
public void validator(a) {
	// Check whether it is an email address
	boolean result = Validator.isEmail("[email protected]");
	log.info("Validator isEmail:{}", result);
	// Check whether it is a mobile phone number
	result = Validator.isMobile("18911111111");
	log.info("Validator isMobile:{}", result);
	// Check whether it is an IPV4 address
	result = Validator.isIpv4("192.168.3.101");
	log.info("Validator isIpv4:{}", result);
	// Check if it is Chinese
	result = Validator.isChinese("Hello");
	log.info("Validator isChinese:{}", result);
	// Check whether it is id number (18 digits Chinese)
	result = Validator.isCitizenId("123456");
	log.info("Validator isCitizenId:{}", result);
	// Check whether it is a URL
	result = Validator.isUrl("http://www.7d.com");
	log.info("Validator isUrl:{}", result);
	// Check whether it is the birthday
	result = Validator.isBirthday("2020-09-17");
	log.info("Validator isBirthday:{}", result);
}
Copy the code

Running results:

Validator isEmail:true
Validator isMobile:true
Validator isIpv4:true
Validator isChinese:true
Validator isCitizenId:false
Validator isUrl:true
Validator isBirthday:true
Copy the code

13, JSONUtil

JSON parsing tool class, a collection of static shortcuts for JSONObject and JSONArray.

@test (description = "JSONUtil use: JSON parsing utility class ")
public void jsonUtil(a) {
	Dog dog = new Dog();
	dog.setName("Rhubarb");
	dog.setWeight(5.14 f);

	// The object is converted to a JSON string
	String jsonStr = JSONUtil.parse(dog).toString();
	log.info("jsonUtil parse:{}", jsonStr);
	//JSON string to object
	Dog dogBean = JSONUtil.toBean(jsonStr, Dog.class);
	log.info("jsonUtil toBean:{}", dogBean);
	List<Dog> dogList = new ArrayList<>();
	dogList.add(dog);
	String jsonListStr = JSONUtil.parse(dogList).toString();
	//JSON string is converted to list
	dogList = JSONUtil.toList(new JSONArray(jsonListStr), Dog.class);
	log.info("jsonUtil toList:{}", dogList);
}
Copy the code

Running results:

jsonUtil parse:{"weight": 5.14."name":"Rhubarb"} jsonUtil toBean:Dog(name= rhubarb, weight=5.14) jsonUtil toList:[name= rhubarb, weight=5.14]Copy the code

14, RandomUtil

Random tool class, RandomUtil mainly for the JDK Random object encapsulation.

@test (description = "RandomUtil use: randomUtility class ")
public void randomUtil(a) {
	int result;
	String uuid;
	// Get a random number within the specified range
	result = RandomUtil.randomInt(1.100);
	log.info("randomInt:{}",StrUtil.toString(result));
	// Get a random UUID
	uuid = RandomUtil.randomUUID();
	log.info("randomUUID:{}", uuid);
}
Copy the code

Running results:

randomInt:9
randomUUID:8aec5890-72ab-4d72-a37d-d36acba83b58
Copy the code

15, DigestUtil

Summary algorithm tool class, supporting common summary algorithms MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512, etc.

@test (description = "DigestUtil usage: Summary algorithm utility class ")
public void digestUtil(a) {
	String password = "123456";
	// Calculates the MD5 digest value and converts it to a hexadecimal string
	String result = DigestUtil.md5Hex(password);
	log.info("DigestUtil md5Hex:{}", result);
	// Calculates the SHA-256 digest value and converts it to a hexadecimal string
	result = DigestUtil.sha256Hex(password);
	log.info("DigestUtil sha256Hex:{}", result);
	// Generate encrypted Bcrypt ciphertext and verify it
	String hashPwd = DigestUtil.bcrypt(password);
	boolean check = DigestUtil.bcryptCheck(password,hashPwd);
	log.info("DigestUtil bcryptCheck:{}", check);
}
Copy the code

Running results:

DigestUtil md5Hex:e10adc3949ba59abbe56e057f20f883e
DigestUtil sha256Hex:8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
DigestUtil bcryptCheck:true
Copy the code

16, HttpUtil

Http client tool class, to deal with the simple scenario of Http request tool class encapsulation, this tool encapsulates the common operations of the HttpRequest object, can ensure that Http requests can be completed in a method.

This module is completed based on JDK’s HttpUrlConnection encapsulation, complete support for HTTPS, proxy and file upload.

@test (description = "HttpUtil use: Http request utility class ")
public void httpUtil(a) {
	String response = HttpUtil.get("http://example.com/");
	log.info("HttpUtil get:{}", response);
}
Copy the code

Running results:

The 18:48:27 2020-09-17. 12004-328 the INFO [main] com. Zuozewei. Demo. Example. Example: HttpUtil get: <! doctype html> <html> <head> <title>Example Domain</title> <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI"."Open Sans"."Helvetica Neue", Helvetica, Arial, sans-serif;
        
    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;Border - the radius: 0.5 em. Box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02); } a:link, a:visited { color:#38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information... </a></p> </div> </body> </html>Copy the code

17. Other tool classes

Hutool provides a variety of tool classes, for example, www.hutool.cn/

Six, the summary

In the process of test development, we should be good at semi-open source and semi-code to save development time, make reasonable use of wheels and improve work efficiency.

Article source: github.com/zuozewei/bl…

References:

  • [1] : www.hutool.cn/docs