The arrangement and use of jar package in Java development

Keywords: Java log4j Apache Lombok

This article collates the jar packages and API records that I often use in Java development.

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

common-lang3

brief introduction

One of the most commonly used jar packages now encapsulates many commonly used Toolkits

Online API
Dependence:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

The main common classes are as follows:

  • Array utility class ArrayUtils
  • Date tool class DateUtils DateFormatUtils
  • String utility class StringUtils
  • Digital tool class NumberUtils
  • Boolean utility class
  • Reflection related tool classes FieldUtils, MethodUtils, MemberUtils, TypeUtils, ConstructorUtils
  • Object tool class ObjectUtils
  • Serializationutilities

API introduction

Here I only introduce a few frequently used tool classes and methods, ArrayUtils, StringUtils, NumberUtils, DateUtils. For others, please check the official API documents

1.ArrayUtils

Method name Explain
add
remove
clone Replicated array
addAll
removeAll The second parameter passes in the subscript to be deleted (multiple subscripts can be specified)
toObject Convert value (Int[],Double []) to wrapper class (Int[],Double [])
indexOf Search the array in order to find the first subscript that meets the corresponding value
lastIndexOf Search the array in order to find the last subscript that meets the corresponding value
contains Whether the array contains a value
isEmpty Judge whether the array is empty
isNotEmpty Judge whether the array is not empty
reverse Array inversion
subarray Specifies the interval truncation array. The interval is a half open interval, excluding the end
toArray Receive multiple objects and convert them into arrays of corresponding types
toMap Convert a 2D array to Map

2.NumberUtils

Method name Explain
min Compare three numbers, return the minimum value or compare the specified numbers, return the minimum value
max Compare three numbers, return the maximum value or compare the specified numbers, return the maximum value
createInt Create a value of the corresponding type from the incoming String, createDouble,createFloat
toInt If the string is null, the default value will be returned. In addition, there are methods such as to double, to long, etc
compare Compare the size of two values of the same type
isDigits Determine whether the string contains only numbers
isParsable Determine whether the string can be converted to Long,Int and other types
isNumber Determine whether the string is a numeric value (decimal value at the beginning of 0x, 0xs)

3.DateUtils

Method name Explain
parseDate Convert Date object to string
isSameDay Determine whether two Dated objects are the same day
isSameDay Determine whether two Dated objects are the same day
addHour Add the specified Date object to the specified hour. In addition, addMonth,addDay

DateFormatUtils, like its name, is used to convert time into a string, so we will not talk about it here

4.StringUtils

Method name Explain
join Concatenates the specified array into a string and adds the specified split character
containOnly Whether a string contains only one string
substringBefore Intercepts the content before the specified string
substringAfter Intercepts the contents after the specified string (excluding the specified string)
substringBetween Intercept the contents of a certain interval of a string, such as substringbetween ("a BCD e", "a", "e") = "BCD"
difference Compare the two strings and return the different contents of the two strings. For details, see the example given in the API document
isBlank Determine whether the string is blank, null, "", "", and "are all true
isEmpty Judge whether the String is empty (true as long as it is not null or the length of the String object passed in is not 0)
countMatches Determines the number of occurrences of a specified string in a string
deleteWhitespace Remove spaces from string
defaultIfBlank Returns a specified default value (null or a String) if the string is blank
defaultIfEmpty Returns a specified default value (null or a String) if the string is empty
capitalize Capitalizes the first letter of the specified string
abbreviate Converts the last three digits of the specified string to
swapCase Invert the case of letters in a string, such as ABC to ABC
lowerCase Convert all letters of the string to lowercase
upperCase Capitalize all letters of a string
left Take a few characters to the left of the string, such as left("hello",3)="hel", right is the opposite
leftPad If the length of the string is not enough, fill the specified string with the specified characters, such as leftpad ("hel", 5, "Z") = "zzhel". The rightpad method is the opposite
prependIfMissing If the specified string does not start with a certain string, the beginning will be added automatically, for example, prependIfMissing("hello","li")="lihello"
prependIfMissing If the specified string does not start with a certain string (case is ignored), the beginning will be added automatically
getCommonPrefix Get the same starting content of multiple strings and receive multiple strings as parameters
removeEnd Delete the end of the string (satisfying the end of a paragraph), such as removeend ("he LLO", "LLO") = "he"
removeEndIgnoreCase Ignore case as above
removeStart Contrary to the above
remove Delete the specified content in the string, such as remove("hello","l")="heo"
removeIgnoreCase Delete the specified content in the string, such as remove("hello","l")="heo"
strip Clear the characters specified at the beginning and end of the string (the second parameter is null, which is used to clear the spaces at the beginning and end of the string), such as strip ("ABC XY", "XY") = "ABC", strip ("abcxy", "YX") = "ABC"
stripStart Clear the specified character at the beginning of the string
stripEnd Clears the character specified at the end of the string

common-io

brief introduction

Common IO stream Toolkit
Online API

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

API

We are mainly concerned about the classes with the suffix of Utils. As you can see, the common IO library provides FileUtils,FileSystemUtils,FileNameUtils,FileFilterUtils,IOUtils

FileUtils

  • File out
  • read file
  • Create a folder with a parent folder
  • Copy files and folders
  • Delete files and folders
  • URL file transfer
  • Filter files and folders through filters and extensions
  • Compare file contents
  • File last modified
  • File check

FileSystemUtils

Related operations of file system, such as checking the size of C disk, remaining size, etc

IOUtils

Literally, it is a tool class that encapsulates various operations of IO flow

Log4j

brief introduction

Log4J is an open source project of Apache. By using Log4J in the project, we can control the output of log information to console, file, GUI component, even database.

We can control the output format of each log. By defining the output level of the log, we can control the output process of the log more flexibly and facilitate the debugging of the project.

Dependence:

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

structure

Log4J is mainly composed of Loggers, Appenders and Layout.

Loggers control the output level of the log and whether the log is output;
Appenders specifies the output mode of the log (output to console, file, etc.);
Layout controls the output format of log information.

Log level:

level Explain
OFF Highest log level, turn off left and right logs
FATAL Errors that will cause the application to exit
ERROR An error event occurs, but does not affect the system's continued operation
WARN Warning, i.e. potential error condition
INFO In general and at the coarse-grained level, it emphasizes the whole process of the application
DEBUG Generally used at the fine-grained level, it is very helpful for debugging applications
ALL Minimum level, turn on all logging

We mainly use these four: error > warn > info > debug

Use

There are two ways to run Log4j: java code and configuration file

Example (Java mode)

public class Log4JTest {
    public static void main(String[] args) {   
        //Get an instance of the Logger object (passed in to the current class)         
        Logger logger = Logger.getLogger(Log4JTest.class);
        //Using the default configuration information, you do not need to write log4j.properties
        BasicConfigurator.configure();
        //Set the log output level to WARN, which will override the level set in the configuration file. Only logs with a log level lower than WARN will be output
        logger.setLevel(Level.WARN);
        logger.debug("This is debug");
        logger.info("This is info");
        logger.warn("This is warn");
        logger.error("This is error");
        logger.fatal("This is fatal");
    }
}

Example (profile mode)

In the above example, we want to print the Log, but we have to write it every time, wasting time and energy. Therefore, Log4j provides another way to configure our information

Create a file named log4j.properties, which needs to be placed in the root directory of the project (Convention). If it is a maven project, just put it directly in the resources folder

log4j.properties

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

#log jdbc
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=WARN
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

#log mybatis settings
#log4j.logger.org.apache.ibatis=DEBUG
log4j.logger.org.apache.ibatis.jdbc=error
log4j.logger.org.apache.ibatis.io=info
log4j.logger.org.apache.ibatis.datasource=info

#Spring MVC log
log4j.logger.org.springframework.web=WARN

# File output configuration
log4j.appender.A = org.apache.log4j.DailyRollingFileAppender
log4j.appender.A.File = D:/log.txt #Specify the output path of the log
log4j.appender.A.Append = true
log4j.appender.A.Threshold = DEBUG
log4j.appender.A.layout = org.apache.log4j.PatternLayout #Use custom log formatter
log4j.appender.A.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n #Specify the output format of the log
log4j.appender.A.encoding=UTF-8 #Specifies the file encoding for the log

#Specify the output level and output end of the log
log4j.rootLogger=DEBUG,Console,A

#Specify a package name log level (cannot exceed the level defined above, otherwise the log will not be output)
log4j.logger.com.wan=DEBUG

It will be easier to use later

//Initialization of the Logger (this is recommended to be defined as a global variable for easy use)
Logger logger = Logger.getLogger(Log4JTest.class);
//Output Log
logger.info("This is info");

Reference link: Getting started with Log4j

lombok

brief introduction

Usually, when we create entity classes, we need get/set methods, which is extremely troublesome. Although ides such as IDEA provide quick generation, the best solution is to omit or not write

lombok is such a framework, which can omit the get/set method. Of course, lombok's function is not only this, but also equal and toString methods can be generated automatically by this framework

The principle of lombok is to use annotations, and then it will automatically add methods such as get/set to the Class file during compilation

However, the IDEA seems to be unrecognized, and code checking will still report errors. Therefore, when using the IDEA, you need to install a plug-in, search for lombok in plugin, and then install and restart it, as shown in the figure below.

Then add a dependency for the Java project

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.8</version>
    <scope>provided</scope>
</dependency>

Use example

1. Entity class omits get/set
It is estimated that the data keyword in Kotlin is implemented by referring to lombok

//Here, we just need to add Data annotation to the class, and we will automatically generate the get/set method, toString, equal and other methods of the corresponding property
@Data
public class User {
    private String username;
    private String password;
}

2. Parameter free construction and get/set method are required

@Getter
@Setter
@NoArgsConstructor
public class User {
    private String username;
    private String password;
}

3. Chain call set method

@Data
@Accessors(chain = true)
public class User {
    private String username;
    private String password;
}

//Use
User user = new User();
user.setUsername("helo").setPassword("123");

4. The parameter is not empty

//If this method is called, it will hold a null pointer error
public String print(@NotNull String str){
    ...
}

5. Only toString is needed

@ToString(callSuper=true, includeFieldNames=true)
public class User {
    private String username;
    private String password;
    //Omitted get/set methods
}

6. Create entity class object in builder mode

@Data
@Builder
public class User {
    private String username;
    private String password;
}
//Use
User user1 = User.builder().username("user1").password("123").build();

7. tool class

@UtilityClass
public class MyUtils{
    //This method is automatically converted to a static method
    public void print(String str){
        ...
    }
}
//Use
MyUtils.print("hello");

8. Automatically close the flow

public static void main(String[] args) throws Exception {
    //close method will be called automatically with Cleanup
    @Cleanup InputStream in = new FileInputStream(args[0]);
    @Cleanup OutputStream out = new FileOutputStream(args[1]);
    byte[] b = new byte[1024];
    while (true) {
        int r = in.read(b);
        if (r == -1) break;
        out.write(b, 0, r);
    }
}

9. Omit initialization of Logger

@Log4j
@Log
public class User{
    //This statement will be added automatically
    //Logger logger = Logger.getLogger(User.class);
    ...
}

Reference resources:
Introduction, usage and summary of Lombok
Detailed explanation of Lombok

Posted by ramli on Mon, 25 Nov 2019 05:46:52 -0800