Skip to content

Commit

Permalink
Merge branch 'feature/message-format-eids' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
cardil committed Nov 22, 2015
2 parents 08e334a + a32cfbf commit 5d51bef
Show file tree
Hide file tree
Showing 15 changed files with 1,125 additions and 208 deletions.
69 changes: 58 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

[![Build Status](https://travis-ci.org/wavesoftware/java-eid-exceptions.svg?branch=master)](https://travis-ci.org/wavesoftware/java-eid-exceptions) [![Coverage Status](https://coveralls.io/repos/wavesoftware/java-eid-exceptions/badge.svg?branch=master&service=github)](https://coveralls.io/github/wavesoftware/java-eid-exceptions?branch=master) [![SonarQube Tech Debt](https://img.shields.io/sonar/http/sonar-ro.wavesoftware.pl/pl.wavesoftware:eid-exceptions/tech_debt.svg)](http://sonar-ro.wavesoftware.pl/dashboard/index/2600) [![Dependency Status](https://www.versioneye.com/user/projects/55aafc74306535001b000440/badge.svg?style=flat)](https://www.versioneye.com/user/projects/55aafc74306535001b000440) [![Maven Central](https://img.shields.io/maven-central/v/pl.wavesoftware/eid-exceptions.svg)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22pl.wavesoftware%22%20AND%20a%3A%22eid-exceptions%22)

This small library holds a set of Exceptions that implements idea of fast, reusable, error codes that can be simple thrown fast in case of unpredictable and unrecoverable application failure.
This small library holds a set of exceptions and utilities that implements idea of fast, reusable, error codes that can be simply thrown fast in case of unpredictable and unrecoverable application failure. It is meant to be used for application bugs.

## Idea

The idea is to use a set of simple runtime exceptions. They should always take the field Exception ID (Eid) in the making. This field will then be reported when displaying or logging that exception. It can also be viewed on the professional fatal error window of the application as a bug reference. EidRuntimeExceptions contains also additional unique ID to identify each single exception. This approach simplifies the management of exceptions in the application and allows developers to focus on functionalities rather than coming up with the correct statement for the exception.
The idea is to use a set of simple runtime exceptions. They should always take the Exception ID (Eid) object in the making. This eid object will then be reported when displaying or logging that exception. It can also be viewed on the professional fatal error window of the application as a bug reference. EidRuntimeExceptions contains also additional unique ID to distinguish each single exception from others with same Eid. This approach simplifies the management of exceptions in the application and allows developers to focus on functionalities rather than coming up with the correct statement for the exception.

This approach is best to use with tools and plugins like:

Expand Down Expand Up @@ -43,17 +43,17 @@ This classes shouldn't be used in any public API or library. It is designed to b
<dependency>
<groupId>pl.wavesoftware</groupId>
<artifactId>eid-exceptions</artifactId>
<version>1.0.0</version>
<version>1.1.0</version>
</dependency>
```

### `EidPreconditions` class

#### General use

Static convenience methods that help a method or constructor check whether it was invoked correctly (whether its preconditions have been met). These methods generally accept a `boolean` expression which is expected to be `true` (or in the case of `checkNotNull`, an object reference which is expected to be non-null). When `false` (or `null`) is passed instead, the `EidPreconditions` method throws an unchecked exception, which helps the calling method communicate to its caller that that caller has made a mistake.
`EidPreconditions` class consists static methods that help to use Eid in a method or constructor. This is solely for convenience purposes. Use them to check whether method or constructor was invoked correctly (whether its preconditions have been met). These methods generally accept a `boolean` expression which is expected to be `true` (or in the case of `checkNotNull`, an object reference which is expected to be non-null). When `false` (or `null`) is passed instead, the `EidPreconditions` method throws an unchecked exception, which helps the calling method communicate to its caller that that caller has made a mistake.

Each method accepts a EID string or Eid object, which is designed to ease of use and provide strict ID for given exception usage. This approach speed up development of large application and helps support teams by giving both static and random ID for each possible unpredicted bug.
Each method accepts a EID string or Eid object, which is designed to ease of use and provide strict ID for given exception usage. This approach speed up development of large application and helps support teams by giving both static and random ID for each possible bug that could occur.

Each example uses static import:

Expand Down Expand Up @@ -104,23 +104,66 @@ String nonNullUserName = checkNotNull(userName, "20150721:115515");
```java
checkElementIndex(index, list.size(), "20150721:115749");
```

#### Formatted message support

From release `1.1.0` there have been added methods to support additional formatted messages for `checkArgument`, `checkState`, `checkNotNull` and `checkElementIndex` method. Those method versions can sometimes be used to pass additional information to exceptions that will be displayed in log files.

Message formatting is done using `String.format(String, Object[])` method.

For example:

```java
checkState(transation.isValid(), "20151119:120238", "Invalid transaction: %s, transaction);
```
Will produce output similar to;
```
pl.wavesoftware.eid.exceptions.EidIllegalStateException: [20151119:120238]<xf4j1l> => Invalid transaction: <Transaction id=null, buyer=null, products=[]>
```
#### Functional try to execute blocks
Using functional blocks to handle operations, that are intended to operate properly, simplify the code and makes it more readable. It's also good way to deal with untested, uncovered `catch` blocks. It's easy and gives developers nice way of dealing with countless operations that suppose to work as intended.
You can use functional blocks to handle operations, that are intended to operate properly. This approach simplify the code and makes it more readable. It's also good way to deal with untested, uncovered `catch` blocks. It's easy and gives developers nice way of dealing with countless operations that suppose to work as intended.
There are two versions. One with `UnsafeSupplier` and one with `UnsafeProcedure`. The difference is that unsafe procedure do not return anything.
Example:
```java
InputStream is = EidPreconditions.tryToExecute(new RiskyCode<InputStream>() {
InputStream is = EidPreconditions.tryToExecute(new UnsafeSupplier<InputStream>() {
@Override
public InputStream execute() throws IOException {
public InputStream get() throws IOException {
return this.getClass().getClassLoader()
.getResourceAsStream("project.properties");
}
}, "20150718:121521");
```
or with Java 8:
```java
import static pl.wavesoftware.eid.utils.EidPreconditions.tryToExecute;
// [..]
InputStream is = tryToExecute(() -> { resource("project.properties"); }, "20150718:121521");
```
#### Logging
Eid object can also be useful in logging. That are `makeLogMessage` method provided to do that. Message formatting is done using `String.format(String, Object[])` method.
For example:
```java
log.debug(new Eid("20151119:121814").makeLogMessage("REST request received: %s", request));
```
will unfold to something similar to:
```
2017-01-08T16:45:34,334 DEBUG [a.b.c.RestBroker] [20151119:121814]<d1afca> REST request received: <RestRequest user=<User id=345> flow=ShowLastTransactions step=Confirm>
```
###Contributing
Contributions are welcome!
Expand All @@ -141,8 +184,12 @@ Even if you can't contribute code, if you have an idea for an improvement please
### Releases
- 1.1.0
- Adding support for formatted messages in exceptions and also in utility methods of `EidPreconditions`
- 1.0.1
- Fixed handling for throwables as a cause with `message == null`. `cause.toString()` method is used
- 1.0.0
- Support for JDK >= 1.6
- Support for JDK >= 1.6
- 0.1.0
- initial release
- idea imported from Guava Library and COI code
- initial release
- idea imported from Guava Library and COI code
124 changes: 114 additions & 10 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

<groupId>pl.wavesoftware</groupId>
<artifactId>eid-exceptions</artifactId>
<version>1.0.2-SNAPSHOT</version>
<version>1.1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>EID Runtime Exceptions and Utilities</name>
Expand All @@ -22,9 +22,13 @@
<properties>
<netbeans.hint.license>apache20</netbeans.hint.license>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<sonar.working.directory>${project.build.directory}/sonar</sonar.working.directory>
<sonar.host.url>https://sonar.wavesoftware.pl</sonar.host.url>
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<sonar.java.source>6</sonar.java.source>
<java.source.version>${sonar.java.source}</java.source.version>
<maven.compiler.source>1.${java.source.version}</maven.compiler.source>
<maven.compiler.target>${maven.compiler.source}</maven.compiler.target>
<coveralls.skip>${skipTests}</coveralls.skip>
</properties>

Expand All @@ -41,6 +45,7 @@
<developerConnection>scm:git:git@github.com:wavesoftware/java-eid-exceptions.git</developerConnection>
<url>https://github.com/wavesoftware/java-eid-exceptions</url>
</scm>

<ciManagement>
<system>travis-ci</system>
<url>https://travis-ci.org/wavesoftware/java-eid-exceptions</url>
Expand All @@ -65,7 +70,7 @@
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.0</version>
<version>3.0.1</version>
<type>jar</type>
</dependency>
<dependency>
Expand All @@ -87,8 +92,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<!-- Version pin because 0.7.5 fails on SONAR -->
<version>0.7.4.201502262128</version>
<version>0.7.5.201505241946</version>
<executions>
<execution>
<id>jacoco-initialize</id>
Expand All @@ -99,7 +103,54 @@
</execution>
<execution>
<id>jacoco-site</id>
<phase>verify</phase>
<phase>post-integration-test</phase>
<goals>
<goal>report</goal>
<goal>report-integration</goal>
</goals>
</execution>
</executions>
<configuration>
<includes>
<include>pl/wavesoftware/**</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</profile>

<profile>
<id>sonar</id>
<activation>
<property>
<!-- tries to determine is interactive user session -->
<name>env.GDMSESSION</name>
</property>
</activation>
<properties>
<sonar.analysis.mode>preview</sonar.analysis.mode>
<sonar.issuesReport.console.enable>true</sonar.issuesReport.console.enable>
<sonar.issuesReport.html.enable>true</sonar.issuesReport.html.enable>
<sonar.report.export.path>issues.json</sonar.report.export.path>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
<goal>prepare-agent-integration</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>post-integration-test</phase>
<goals>
<goal>report</goal>
<goal>report-integration</goal>
Expand All @@ -112,6 +163,48 @@
</includes>
</configuration>
</plugin>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<executions>
<execution>
<id>default</id>
<phase>post-integration-test</phase>
<goals>
<goal>sonar</goal>
</goals>
</execution>
</executions>
</plugin>

<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>groovy-maven-plugin</artifactId>
<version>2.0</version>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>
<configuration>
<defaults>
<sonar.issues.file>${sonar.working.directory}/${sonar.report.export.path}</sonar.issues.file>
</defaults>
<source>${project.basedir}/src/test/groovy/verify-sonar-issues.groovy</source>
</configuration>
<executions>
<execution>
<id>verify-sonar-issues</id>
<phase>verify</phase>
<goals>
<goal>execute</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
Expand Down Expand Up @@ -155,6 +248,7 @@
<configuration>
<compilerArgs>
<arg>-Werror</arg>
<arg>-Xlint:-deprecation</arg>
<arg>-Xlint:all</arg>
</compilerArgs>
</configuration>
Expand All @@ -172,7 +266,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<version>2.19</version>
<configuration>
<trimStackTrace>false</trimStackTrace>
</configuration>
Expand All @@ -181,7 +275,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.18.1</version>
<version>2.19</version>
<configuration>
<trimStackTrace>false</trimStackTrace>
<encoding>UTF-8</encoding>
Expand All @@ -196,6 +290,16 @@
</executions>
</plugin>
</plugins>

<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>2.7.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>

</project>
</project>
29 changes: 23 additions & 6 deletions src/main/java/pl/wavesoftware/eid/exceptions/Eid.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
*/
package pl.wavesoftware.eid.exceptions;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.Serializable;
import static java.lang.Math.abs;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.annotation.Nullable;

import static java.lang.Math.abs;

/**
* <strong>This class shouldn't be used in any public API or library.</strong> It is designed to be used for in-house development
Expand Down Expand Up @@ -93,7 +95,6 @@ public Eid(String id) {
* @throws IllegalArgumentException if given format hasn't got two format specifiers <tt>"%s"</tt>, or if given format was
* null
*/
@SuppressWarnings("UnusedReturnValue")
public static String setMessageFormat(String format) {
validateFormat(format, MESSAGE_FORMAT_NUM_SPEC);
String oldFormat = Eid.messageFormat;
Expand Down Expand Up @@ -157,6 +158,23 @@ public static String setRefFormat(String refFormat) {
return previously;
}

/**
* Makes a log message from this EID object
* <p>
* <p>This method is for convenience of usage of EID in logging. You can use it like this:
* <p>
* <pre>
* log.debug(new Eid("20151025:202129").makeLogMessage("A request: %s", request));
* </pre>
* @param logMessageFormat a log message format as accepted by {@link String#format(String, Object...)}
* @param parameters a parameters for logMessageFormat to by passed to {@link String#format(String, Object...)}
* @return a formatted message
*/
public String makeLogMessage(@Nonnull String logMessageFormat, @Nonnull Object... parameters) {
String message = String.format(logMessageFormat, parameters);
return String.format(getMessageFormat(), this.toString(), message);
}

@Override
public String toString() {
if ("".equals(ref)) {
Expand Down Expand Up @@ -238,11 +256,10 @@ public String generateUniqId() {
long first = abs(random.nextLong() + 1);
int second = abs(random.nextInt(Integer.MAX_VALUE));
int calc = (int) (first + second);
return Integer.toString(calc, BASE36);
return Integer.toString(abs(calc), BASE36);
}

@SuppressWarnings("squid:S2245")
private Random getUnsecuredFastRandom() {
private static Random getUnsecuredFastRandom() {
return new Random(System.currentTimeMillis());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
*
* @author Krzysztof Suszyński <krzysztof.suszynski@wavesoftware.pl>
*/
@SuppressWarnings("WeakerAccess")
public interface EidContainer {

/**
Expand Down
Loading

0 comments on commit 5d51bef

Please sign in to comment.