More‎ > ‎

Top of Apache Commons Libraries for Java Development



It is always a good idea to reuse a stable, tested and commonly used library instead of reinventing the wheel and write own solutions. They include a lot of useful solutions for daily tasks and may save time.


Command Line Arguments Parser (CLI

The Command Line Library provides a simple API for parsing command line options and it is able to display the detailed help messages for the defined options of a command line tool. 

The following modified code sample (from How to Enhance Static Call-Graph Analysis with Dynamic Data from Profiling?) demonstrates the use of the CLI library. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.sprunck.cli;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.Parser;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SampleCLI {

    private static final Log LOGGER = LogFactory.getLog(SampleCLI.class);

    private static final String NL = System.getProperty("line.separator");

    private static Options createCommandLineOptions() {
        final Options options = new Options();
        options.addOption("port", true, "Mandatory parameter port for webserver.");
        options.addOption("id", true, "Mandatory parameter process id of JVM.");
        options.addOption("help", false, "Show help information.");
        options.addOption("details", false, "Do a detailed analysis.");
        options.addOption("filter", true, "Just classes which have a package " 
                + "name which starts with the string "
                + "of the package filter will be recorded.");
        options.addOption("jar_files", true, "Scan jar files.");
        return options;
    }

    private static void outputCommandLineHelp(final Options options) {
        final HelpFormatter formater = new HelpFormatter();
        formater.printHelp("The SampleCLI demonstrates the use of CLI.", options);
    }

    private static void processCommandline(final CommandLine cl) throws IllegalArgumentException {
        if ((null != cl) && cl.hasOption("port")) {
            // do something with port
        }
        if ((null != cl) && cl.hasOption("id")) {
            // do something with id
        }
        if ((null != cl) && cl.hasOption("filter")) {
            // do something with filter
        }
        if ((null != cl) && cl.hasOption("details")) {
            // do something with details
        }
        if ((null != cl) && cl.hasOption("jar_files")) {
            // do something with jar_files
        }
    }

    public static void main(final String[] args) {
        // Parse command line
        final Parser commandlineparser = new PosixParser();
        final Options options = createCommandLineOptions();
        CommandLine cl = null;
        try {
            cl = commandlineparser.parse(options, args, true);
        } catch (final ParseException exp) {
            LOGGER.error("Unexpected exception:" + exp.getMessage() + NL);
        }
        // Process command line and store parameter in attributes
        try {
            if (null != cl) {
                processCommandline(cl);
            }
        } catch (final IllegalArgumentException e) {
            outputCommandLineHelp(options);
            LOGGER.warn("Illegal arguments on command line: " + e.getMessage() + NL);
            return;
        }
        if ((null != cl) && cl.hasOption("help") || args.length < 1) {
            outputCommandLineHelp(options);
            return;
        }
        // do something ...        
    }
}

Important of this sample are the methods: 
  • private static Options createCommandLineOptions() configures the command line

  • private static void outputCommandLineHelp(final Options options) prints the following help text:
usage: The SampleCLI demonstrates the use of CLI. 
-details           Do a detailed analysis.
 -filter <arg>      Just classes which have a package name which starts
                    with the string of the package filter will be
                    recorded.
 -help              Show help information.
 -id <arg>          Mandatory parameter process id of JVM.
 -jar_files <arg>   Scan jar files.
 -port <arg>        Mandatory parameter port for webserver.
  • private static void processCommandline(final CommandLine cl) scans the command line

  • public static void main(final String[] args) uses the command line
Just include the commons-cli-1.2.jar in your project.

Extra Functionality for Classes in java.lang (Lang)

Contains a lot of helper utilities like String manipulation methods, numerical methods, reflection, concurrency, creation and serialization and System properties.

The Building Classes

It also contains utilitiy classes to help with building methods like toString(), hashCode() and equals(). These building classes (EqualsBuilder, HashCodeBuilder, and ToStringBuilder) are very useful because this is a common source of errors in real world projects.

The Validation Class

My personal favorite is the class Validate. This class help to validate arguments of a method and this is better than unread or inconsistent JavaDoc comments. The validation methods create:
  • NullPointerException (invalid null argument), 
  • IllegalArgumentException (non-null argument) and
  • IndexOutOfBoundsException (invalid index into an array/collection/map/string). 

The exceptions messages are format strings like:

1
Validate.isTrue(i < 0, "Value must be smaller than zero: %d", i); 

Just include the commons-lang3-3.1.jar in your project.

General Encoding and Decoding Algorithms (Codec)

A set of utilities and a simple framework for encoding and decoding text and binary data. E.g. Base16, Base32, and Base64 data encoding are implemented. Further encoding like URLCodec.

Just include the commons-codec-1.7.jar in your project.

API for Working with Compression (Compress)

  • ar, 
  • cpio, 
  • Unix dump, 
  • tar, 
  • zip, 
  • gzip, 
  • XZ, 
  • Pack200 and 
  • bzip2.
Just include the commons-compress-1.4.1.jar in your project.

Reading of Configuration or Preferences Files (Configuration)

  • Properties files,
  • XML documents,
  • Windows INI files,
  • Property list files (plist),
  • JNDI,
  • JDBC Datasource,
  • System properties,
  • Applet parameters and 
  • Servlet parameters.
Just include the commons-configuration-1.9.jar in your project.

Sending E-Mail from Java (Email)

  • SimpleEmail, 
  • MultiPartEmail, 
  • HtmlEmail and
  • EmailAttachment (for MultiPartEmail and HtmlEmail).
Just include the commons-email-1.2.jar in your project.

Collection of I/O Utilities (IO)

  • Utility classes,
  • Input,
  • Output,
  • Filters,
  • Comparators and
  • File Monitor.
Just include the commons-io-2.4.jar in your project.

Lightweight Mathematics and Statistics Components (Math)

  • Computing means, variances and other summary statistics for a list of numbers
  • Fitting a line to a set of data points using linear regression
  • Finding a smooth curve that passes through a collection of points (interpolation)
  • Fitting a parametric model to a set of measurements using least-squares methods
  • Solving equations involving real-valued functions (i.e. root-finding)
  • Solving systems of linear equations
  • Solving Ordinary Differential Equations
  • Minimizing multi-dimensional functions
  • Generating random numbers with more restrictions (e.g distribution, range) than what is possible using the JDK
  • Generating random samples and/or datasets that are "like" the data in an input file
  • Performing statistical significance tests
  • Miscellaneous mathematical functions such as factorials, binomial coefficients and "special functions" (e.g. gamma, beta functions)
Just include the commons-math3-3.0.jar in your project.

Sponsored Link