# Jodd Util

Curated set of free Java utilities.

Various Java utilities. Zero dependencies.

{% hint style="info" %}
Only a few utitlities are listed here. Please check [JavaDoc](https://javadoc.io/doc/org.jodd/jodd-util) for all.
{% endhint %}

### License

The code is released under the `BSD-2-Clause` license. It has a minimal set of dependencies with the same or similarly open license, so you should be able to use it in any project and for any purpose.


# Installation

**Jodd Util** is released on Maven Central. You can use the following snippets to add it to your project:

{% tabs %}
{% tab title="Maven" %}

```markup
<dependency>
  <groupId>org.jodd</groupId>
  <artifactId>jodd-util</artifactId>
  <version>x.x.x</version>
</dependency>
```

{% endtab %}

{% tab title="Gradle" %}

```
implementation 'org.jodd:jodd-util:x.x.x'
```

{% endtab %}

{% tab title="Gradl.kt" %}

```kotlin
implementation("org.jodd:jodd-util:x.x.x")
```

{% endtab %}

{% tab title="Scala SBT" %}

```scala
libraryDependencies += "org.jodd" % "jodd-util" % "x.x.x"
```

{% endtab %}

{% tab title="Ivy" %}

```markup
<dependency org="org.jodd" name="jodd-util" rev="x.x.x" />
```

{% endtab %}

{% tab title="Leiningen" %}

```
[org.jodd/jodd-util "x.x.x"]
```

{% endtab %}

{% tab title="Buildr" %}

```
'org.jodd:jodd-util:jar:x.x.x'
```

{% endtab %}
{% endtabs %}

That is all!

### Snapshots

**Jodd Util** snapshots are published on [Maven Central Snapshot repo](https://oss.sonatype.org/content/repositories/snapshots/org/jodd/jodd-util/).

{% hint style="warning" %}
Snapshots are released manually. Feel free to contact me if you need a new SNAPSHOT release sooner.
{% endhint %}


# Contact

Let's keep in touch.

{% hint style="success" %}

## <info@jodd.org>

{% endhint %}


# StringUtil

Strings manipulation is a common and frequent task in the everyday life of a developer. JDK doesn't provide much help on this topic. The `StringUtil` class offers more than **100** additional string utilities (and still growing). And each one is optimized for speed. Description of some methods follows, more details can be founded in JavaDoc and test cases.

### Replacing

`replace()` is one of the most missing functionality String needs. It doesn't use a regular expression, just simply replaces all founded substrings. Alternatively, there is a method that replaces just first or last occurrence of some substring: `replaceFirst()` and `replaceLast()`, respectively.

Besides substrings, it is possible to replace a single character as well as several characters at once, by using `replaceChars()`.

### Removing

Similar to replace methods, removing methods removes all substring occurrences from the provided target string: `remove()`. The same can be done for removing a single character, as well as more characters at once: `removeChars()`.

### Empty string detection

`StringUtil` provides methods for the detection of empty and blank strings. Empty strings are those that are either `null` or with zero-length; `isEmpty()`, `isNotEmpty()`. Blank strings are those that are either empty or that contains just whitespaces; `isBlank()`, `isNotBlank()`.

`StringUtil` also may check several strings at once: `isAllBlank()`, `isAllEmpty()`.

### Safe equals

`equals()` offers safe compression of provided strings: it will not fail if one of the arguments is `null`. Similarly, there is `equalsIgnoreCase()` for checking two strings ignoring the characters case.

### Capitalization

Two methods that are always needed: `capitalize()` and `uncapitalize()`.

### Splitting

When parsing, splitting a string into substrings is also a common task. `StringUtil` offers several split methods.

`split(String src, String delimiter)` splits a string into several parts (tokens) that are separated by a delimiter. A delimiter is **always** surrounded by two strings (tokens)! If there is no content between two delimiters, an empty string will be returned for that token. Therefore, the length of the returned array will always be `#delimiters + 1`. This method is much, much faster than regexp variant `String.split()` and just a bit faster than `StringTokenizer`.

`splitc(String src, char d)` and `splitc(String src, String d)`splits a string into several parts (tokens) that are separated by delimiter **characters**. A delimiter may contain any number of characters, and it is always surrounded by two strings.

### IndexOfs

`StringUtil` provides many missing `indexOf` methods. It is possible to scan just an inner part of a string, to ignore case while searching, to scan in both directions (from start or and of the string)... There are also more scanners, such: `lastIndexOfWhitespace()` and `lastIndexOfNonWhitespace()`.

In the same manner, `startsWithIgnoreCase()` and `endsWithIgnoreCase()` are commonly needed methods.

But that is not all:) It is also possible to scan for more strings at the same time. Such methods return an `int` array, where the first element is a substring index and the second element is founded position.

There are also character-oriented scanners, that search for the first/last occurrence of provided character(s).

### Strips, crops, trims, and cuts

Another set of common methods for trimming (removing whitespaces from left and right), cropping (setting empty strings to `null`), stripping (first or last characters from a string in a safe manner) and cutting (cut a string from the beginning or from the end up to the first occurrence of some substring, or cutting last or first words).

### indexOfRegion

This is a powerful region scanning method that returns indexes of the first occurrence of some string region. The region is and substring defined by its left and right boundary. The return value is an array of the following indexes: start of left boundary index, region start index (i.e. end of the left boundary), region end index (i.e. start of the right boundary), and end of right boundary index.

Escape characters may be used to prefix boundaries so they can be ignored. Double escaped regions will be found, and the first index of the result will be decreased to include one escape character. If a region is not founded, `null` is returned.

### And more!

Obviously, this is just a subset of the ever-growing number of utilities we provide in the `StringUtil`. Please check the code or the JavaDocs :)


# InExRules

It's a common practice to set some include and exclude rules to filter some resources.&#x20;

This small rule engine is implemented in `InExRules` class. This rule engine may work in one of the two following modes:

* **blacklist** mode (default) - any input is included, and you specify what to exclude;
* **whitelist** mode - any input is excluded, and you specify what to include.

The order of execution of explicit include/exclude rules depends on the mode.

{% hint style="warning" %}
The rules 'opposite' to the rule engine mode is always executed first! Corresponding rules of the same group (include or exclude) are executed as they are defined.
{% endhint %}

For example, if the rule engine is in blacklist mode, the engine first executes exclude rules and then include rules. When executing one of these groups, all corresponding rules are executed as defined. This way you can filter out any combination you need.

I am sure you are totally puzzled with the above definitions:) Let's see rules in action, everything will be much clearer!

### Rules

When created, the rules engine can be filled up with the various include/exclude rules. For example, we can have something like this:

```java
InExRules inExRules = ... // we get the engine instance

inExRules.include("shelf.book.*");
inExRules.exclude("shelf.book.page.1");
```

What we set here are two rules: one for defining what will be included and one for what is going to be excluded. In this example, rules are simple strings, but this does not have to be the case, as we gonna see later.

After setting the rule, our engine is set and we can start matching input resources. In our trivial example, resources are again strings, so we can write something like:

```java
inExRules.match("shelf.book.page.1");
inExRules.match("shelf.book");
inExRules.match("shelf.book.page.34");
```

### Order of execution

The above two rules are a bit vague. In one rule, we said we want to include all pages, and then we are excluding one page. Which rule is applied first?

Look again at what we said at the very beginning. The order of execution depends on the current mode. So here is the logic behinds the rule engine in this case:

* By default, the engine is created in **blacklist** mode
* Therefore, everything is *included*.
* First check the *opposite* rules, the *excluded* group.
* We have just one *excludes* rule (`shelf.book.page.1`).

If we stop now, then the rule engine would be set to include all book pages except page 1. But we have more rules:

* After checking the *opposite* group, go with the *included* group.
* We have one *includes* rule (`shelf.book.*`).

We just overwrite the exclude rule! Meaning, we didn't exclude anything!

### Changing the mode

Obviously, this is not what we wanted. We have to change the initial mode of the rule engine.

then the rule engine logic goes like this

* The engine is started in *whitelist* mode
* Therefore, everything is *excluded*.
* First check the *opposite* rules, the *included* group.
* We have one *includes* rule (`shelf.book.*`).
* After checking the *opposite* group, go with the *excluded* group.
* We have just one *excludes* rule (`shelf.book.page.1`).

This time, rules are set as we wanted: the whole book is included except page 1.


# Wildcard

Matching strings to wildcards pattern is useful and often needed. Using regular expression may help, but is not a top performance solution. `Wildcard` class matches strings to wildcard patterns using `*` and `?` characters, and that does very fast and good!

### Matching strings

Here are some examples:

```java
Wildcard.match("CfgOptions.class", "*C*g*cl*");         // true   
Wildcard.match("CfgOptions.class", "*g*c**s");          // true!   
Wildcard.match("CfgOptions.class", "??gOpti*c?ass");    // true   
Wildcard.match("CfgOpti*class", "*gOpti\\*class");      // true   
Wildcard.match("CfgOptions.class", "C*ti*c?a?*");       // true
```

### Matching file paths

`Wildcard` class supports path matching wildcards. It matches path against pattern using `*`, `?` and `**` wildcards. Both path and the pattern are tokenized on path separators (`\` and `/`). `**` represents deep tree wildcard, as in Ant.

```java
Wildcard.matchPath("/foo/soo/doo/boo", "/**/bo*");          // true
Wildcard.matchPath("/foo/one/two/three/boo", "**/t?o/**");  // true
```

### Wildcards in Jodd

Wildcard matching is used in many places in *Jodd*. As the general rule-of-the-thumb, everywhere where file paths are involved in scanning and matching, the `matchPath()` method is used, otherwise, the classic `path()`.


# BeanUtil

**BeanUtil** is a bean manipulation library that, in a nutshell, allows setting and reading bean properties. Several features make **BeanUtil** distinct:

* *fast* (if not the fastest) bean manipulation utility
* works with both *attributes* and *properties*
* nested properties can be arrays, lists and maps
* missing inner properties may be created
* may work silently (no exception is thrown)
* offers few populate methods
* has strong-type conversion library

### Flavors of BeanUtil

Before we jump into the details, let's quickly learn what types of `BeanUtil` exists. Implementations differ in the way how they threat private properties, if they throw exceptions and, finally, if they force the creation of missing inner properties (more details later). You can build your own implementation easily using `BeanUtilBean`, but these are already provided:

| Name                            | <p>Access<br>Privates</p> | <p>Throws</p><p>Exceptions</p> | <p>Force</p><p>Missing</p><p>Properties</p> |
| ------------------------------- | :-----------------------: | :----------------------------: | :-----------------------------------------: |
| `BeanUtil.pojo`                 |             no            |               yes              |                      no                     |
| `BeanUtil.declared`             |            yes            |               yes              |                      no                     |
| `BeanUtil.silent`               |             no            |               no               |                      no                     |
| `BeanUtil.forced`               |             no            |               yes              |                     yes                     |
| `BeanUtil.declaredSilent`       |            yes            |               no               |                      no                     |
| `BeanUtil.declaredForced`       |            yes            |               no               |                     yes                     |
| `BeanUtil.declaredForcedSilent` |            yes            |               no               |                     yes                     |
| `BeanUtil.forcedSilent`         |             no            |               no               |                     yes                     |

Let' jump into details!


# Usage

### Working with bean properties

In `BeanUtil` world, bean property is a class field with its *optional* setter and getter (aka accessors) methods. When accessing properties, `BeanUtil` first tries to use accessors methods. If they don't exist, `BeanUtil` fail-backs to using the field of the same visibility. Therefore, the existence of accessors methods is not required and depends on usage, which often may be handy. `BeanUtil` is used internally inside the *Jodd* library, so this behavior applies everywhere.

Simple bean:

```java
public class Foo {
    private String readwrite;   // with getter and setter
    private String readonly;    // with getter
    ...
}
```

Usage:

```java
Foo foo = new Foo();
BeanUtil.pojo.setProperty(foo, "readwrite", "data");
BeanUtil.pojo.getProperty(foo, "readwrite");
BeanUtil.declared.setProperty(foo, "readonly", "data");
```

Lines #2 and #3 show common and expected `BeanUtil` usage: setting value of read-write property through its accessors methods. Setting `readonly` property in above example is only possible with default implementation, so we use `BeanUtil.declared`. This variant first tries to use `setReadonly()` method, but since such method doesn't exist, field value is accessed directly.

### Nested properties

`BeanUtil` supports nested properties. Nested properties can be java beans, a **List**, a **Map** or an **array** element:

```java
BeanUtil.pojo.getProperty(cbean, "list[0].map[foo].foo");
BeanUtil.pojo.setProperty(cbean, "arr[4].map[elem.boo].foo", "test");
```

When accessing nested properties, `BeanUtil` access one property at time and, by default, expects that all inner properties exist i.e. are not-`null`. Above example is executed like the following pseudo-code:

```java
cbean.getList().get(0).get("foo").getFoo();
cbean.getArr()[4].get("elem.boo").setFoo("test");
```

### Forced setting of nested properties

The setting of nested properties fails if one of the inner elements is `null`. Using *forced* feature of `BeanUtil`, such properties still may be set!

```java
BeanUtil.forced.setProperty(x, "y.foo", value);
BeanUtil.forced.setProperty(x, "yy[2].foo", "xxx");
```

If the object `x` in the above example has an uninitialized property `y`, `BeanUtil` will first create a new instance of `y` type, and set it to property `y`. Then, `foo` property of newly created object `y` will be set. In the second example, `yy` is an array. If it is uninitialized, `BeanUtil` will create a new array of length 3. Then, it will create a new instance of `yy` type that will be stored as the third element of the array. Finally, the `foo` property is set.

In forced mode, `BeanUtil` tries to instantiate all uninitialized properties needed for setting the final property. Instantiation depends on the inner property type: if it is a simple bean, the no-args constructor will be invoked. If it is a list, new `ArrayList` will be created. Similar applies to arrays and map types. Additionally, `BeanUtil` will check the length of existing initialized arrays and lists and if the current size is not enough, list or array will be expanded by adding `null` elements up to the new size.

### Generics support

When creating a new element of a list, `BeanUtil` will consider existing generics information in order to create an element of correct type.

### Silent mode (no exceptions)

Property setting may fail for various reasons, causing an unchecked exception `BeanUtilException` to be thrown. Sometimes this is not desired behavior. For these cases, `BeanUtil` offers *silent* implementation that does not throw any exception at all.

### Maps and lists instead of beans

You can pass maps and list instead of beans as a root object. Just omit the bean name (since we do not work on a bean anymore):

```java
Properties properties = new Properties();
BeanUtil.pojo.setProperty(property, "[ldap.auth.enabled]", "true");
```

### Testing of property existence

`BeanUtil` also offers a convenient way to test if some property exists:

```java
BeanUtil.pojo.hasProperty(fb, "fooInteger")
```


# Type Conversion

When setting properties, **BeanUtil** converts the type of provided value to match the destination. For this purpose, it uses Type converter utility.

Getting properties always return an `Object`. If you need to cast it to some type, you may use `TypeConverterManager#convertType`. The following snippet shows the usage:

```java
public boolean getBoolean(Object bean, String param, boolean defaultValue) {
    Boolean booleanValue = null;
    if (bean != null) {
        Object value = BeanUtil.pojo.getProperty(bean, param);
        beanValue = TypeConverterManager.convertType(value, Boolean.class);
    } catch (Exception ex) {
        // log error
    }
    if (booleanValue == null) {
        return defaultValue;
    } else {
        return booleanValue.booleanValue();
    }
}
```


