Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 97 additions & 69 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,75 +1,103 @@

# Stringify Object for Java

[![Build Status](https://travis-ci.org/wavesoftware/java-stringify-object.svg?branch=master)](https://travis-ci.org/wavesoftware/java-stringify-object) [![Quality Gate](https://sonar.wavesoftware.pl/api/badges/gate?key=pl.wavesoftware.utils:stringify-object)](https://sonar.wavesoftware.pl/dashboard/index/pl.wavesoftware.utils:stringify-object) [![Coverage Status](https://coveralls.io/repos/github/wavesoftware/java-stringify-object/badge.svg?branch=master)](https://coveralls.io/github/wavesoftware/java-stringify-object?branch=master)
[![Maven Central](https://img.shields.io/maven-central/v/pl.wavesoftware.utils/stringify-object.svg)](https://bintray.com/bintray/jcenter/pl.wavesoftware.utils%3Astringify-object)


A utility to safely inspect any Java Object as String representation. It's best to be used with JPA entity model to be dumped
to log files.

It utilize `@Inspect` annotation to indicate which fields
should be displayed. It has support for cycles, and Hibernate lazy loaded elements.

## Usage

```java
// define fields to inspect
# Stringify Object for Java

[![Build Status](https://travis-ci.org/wavesoftware/java-stringify-object.svg?branch=master)](https://travis-ci.org/wavesoftware/java-stringify-object) [![Quality Gate](https://sonar.wavesoftware.pl/api/badges/gate?key=pl.wavesoftware.utils:stringify-object)](https://sonar.wavesoftware.pl/dashboard/index/pl.wavesoftware.utils:stringify-object) [![Coverage Status](https://coveralls.io/repos/github/wavesoftware/java-stringify-object/badge.svg?branch=master)](https://coveralls.io/github/wavesoftware/java-stringify-object?branch=master) [![Maven Central](https://img.shields.io/maven-central/v/pl.wavesoftware.utils/stringify-object.svg)](https://bintray.com/bintray/jcenter/pl.wavesoftware.utils%3Astringify-object)


A utility to safely inspect any Java Object as String representation. It's best to be used with domain model (also with JPA entities) with intention to dump those entities as text to log files.

It runs in two modes: `PROMISCUOUS` (by default) and `QUIET`. In `PROMISCUOUS` mode every defined field is automatically inspected, unless the field is annotated with `@DoNotInspect` annotation.
In `QUIET` mode only fields annotated with `@Inspect` will gets inspected.

This library has proper support for object graph cycles, and JPA (Hibernate) lazy loaded elements.

## Usage

### In Promiscuous mode

```java
// In PROMISCUOUS mode define fields to exclude
class Person {
private int id;
@DisplayNull
private Person parent;
private List<Person> childs;
private Account account;
@Inspect(conditionally = IsInDevelopment.class)
private String password;
@DoNotInspect
private String ignored;
}

// inspect an object
List<Person> people = query.getResultList();
ObjectStringifier stringifier = new ObjectStringifier(people);
stringifier.setMode(Mode.PROMISCUOUS);
// stringifier.setBeanFactory(...);
assert "<Person id=15, parent=<Person id=16, parent=null, "
+ "childs=[(↻)], account=⁂Lazy>, childs=[], "
+ "account=⁂Lazy>".equals(stringifier.toString());
```

### In Quiet mode
```java
// In QUIET mode define fields to inspect
class Person {
@Inspect private int id;
@Inspect private Person parent;
@Inspect @DisplayNull private Person parent;
@Inspect private List<Person> childs;
@Inspect private Account account;
private String ignored;
}

// inspect an object
List<Person> people = query.getResultList();
ObjectStringifier stringifier = new ObjectStringifier(people);
assert "<Person id=15, parent=<Person id=16, parent=null, "
+ "childs=[(↻)], account=⁂Lazy>, childs=[], "
+ "account=⁂Lazy>".equals(stringifier.toString());
```

## Features

* String representation of any Java class
* Fine tuning of which fields to display
* Support for cycles in object graph - `(↻)` is displayed instead
* Support for Hibernate lazy loaded entities - `⁂Lazy` is displayed instead

## vs. Lombok @ToString

Stringify Object for Java is designed for **slightly different** use case then Lombok.

Lombok `@ToString` is designed to quickly inspect fields of simple objects by generating static simple implementation of this mechanism.

Stringify Object for Java is designed to inspect complex objects that can have cycles and can be managed by JPA provider like Hibernate (introducing Lazy Loading problems).

#### Pros of Lombok vs Stringify Object

* Lombok is **fast** - it's statically generated code without using Reflection API.
* Lombok is **easy** - it's zero configuration in most cases.

#### Cons of Lombok vs Stringify Object

* Lombok can't **detect cycles** is object graph, which implies `StackOverflowException` being thrown in that case
* Lombok can't detect a **lazy loaded entities**, which leads to force loading it from JPA by invoking SQL statements. It's typical **n+1 problem**, but with nasty consequences - your `toString()` method is invoking SQL without your knowledge!!

## Requirements

* JDK >= 7
* [EID Exceptions](https://github.com/wavesoftware/java-eid-exceptions)

### Contributing

Contributions are welcome!

To contribute, follow the standard [git flow](http://danielkummer.github.io/git-flow-cheatsheet/) of:

1. Fork it
1. Create your feature branch (`git checkout -b feature/my-new-feature`)
1. Commit your changes (`git commit -am 'Add some feature'`)
1. Push to the branch (`git push origin feature/my-new-feature`)
1. Create new Pull Request


// inspect an object
List<Person> people = query.getResultList();
ObjectStringifier stringifier = new ObjectStringifier(people);
stringifier.setMode(Mode.QUIET);
assert "<Person id=15, parent=<Person id=16, parent=null, "
+ "childs=[(↻)], account=⁂Lazy>, childs=[], "
+ "account=⁂Lazy>".equals(stringifier.toString());
```

## Features

* String representation of any Java class in two modes `PROMISCUOUS` and `QUIET`
* Fine tuning of which fields to display
* Support for cycles in object graph - `(↻)` is displayed instead
* Support for Hibernate lazy loaded entities - `⁂Lazy` is displayed instead

## vs. Lombok @ToString

Stringify Object for Java is designed for **slightly different** use case then Lombok.

Lombok `@ToString` is designed to quickly inspect fields of simple objects by generating static simple implementation of this mechanism.

Stringify Object for Java is designed to inspect complex objects that can have cycles and can be managed by JPA provider like Hibernate (introducing Lazy Loading problems).

#### Pros of Lombok vs Stringify Object

* Lombok is **fast** - it's statically generated code without using Reflection API.
* Lombok is **easy** - it's zero configuration in most cases.

#### Cons of Lombok vs Stringify Object

* Lombok can't **detect cycles** is object graph, which implies `StackOverflowException` being thrown in that case
* Lombok can't detect a **lazy loaded entities**, which leads to force loading it from JPA by invoking SQL statements. It's typical **n+1 problem**, but with nasty consequences - your `toString()` method is invoking SQL without your knowledge!!

## Dependencies

* Java >= 7
* [EID Exceptions](https://github.com/wavesoftware/java-eid-exceptions) library

### Contributing

Contributions are welcome!

To contribute, follow the standard [git flow](http://danielkummer.github.io/git-flow-cheatsheet/) of:

1. Fork it
1. Create your feature branch (`git checkout -b feature/my-new-feature`)
1. Commit your changes (`git commit -am 'Add some feature'`)
1. Push to the branch (`git push origin feature/my-new-feature`)
1. Create new Pull Request

Even if you can't contribute code, if you have an idea for an improvement please open an [issue](https://github.com/wavesoftware/java-stringify-object/issues).
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

<groupId>pl.wavesoftware.utils</groupId>
<artifactId>stringify-object</artifactId>
<version>0.1.1-SNAPSHOT</version>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Stringify Object for Java</name>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,40 @@
package pl.wavesoftware.utils.stringify;

import lombok.RequiredArgsConstructor;
import pl.wavesoftware.utils.stringify.annotation.Inspect;
import lombok.Setter;
import pl.wavesoftware.utils.stringify.configuration.BeanFactory;
import pl.wavesoftware.utils.stringify.configuration.Inspect;
import pl.wavesoftware.utils.stringify.configuration.Mode;
import pl.wavesoftware.utils.stringify.impl.ToStringResolver;
import pl.wavesoftware.utils.stringify.impl.ToStringResolverFactory;
import pl.wavesoftware.utils.stringify.impl.ToStringResolverFactoryImpl;

/**
* @author <a href="krzysztof.suszynski@wavesoftware.pl">Krzysztof Suszyński</a>
* @since 2018-04-18
*/
@Setter
@RequiredArgsConstructor
public final class ObjectStringifier {
private static final ToStringResolverFactory RESOLVER_FACTORY =
new ToStringResolverFactoryImpl();
private final Object target;
private Mode mode = Mode.DEFAULT_MODE;
private BeanFactory beanFactory;

/**
* Creates string representation of given object using {@link Inspect} on given fields.
*
* @return a string representation of given object
*/
public CharSequence stringify() {
return new ToStringResolver(target).resolve();
ToStringResolver resolver = RESOLVER_FACTORY
.create(target)
.withMode(mode);
if (beanFactory != null) {
resolver = resolver.withBeanFactory(beanFactory);
}
return resolver.resolve();
}

@Override
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package pl.wavesoftware.utils.stringify.configuration;

import java.lang.reflect.Field;

/**
* @author <a href="mailto:krzysztof.suszynski@coi.gov.pl">Krzysztof Suszynski</a>
* @since 27.04.18
*/
public final class AlwaysTruePredicate implements Predicate<Field> {
@Override
public boolean test(Field field) {
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package pl.wavesoftware.utils.stringify.configuration;

/**
* @author <a href="mailto:krzysztof.suszynski@coi.gov.pl">Krzysztof Suszynski</a>
* @since 27.04.18
*/
public interface BeanFactory {
<T> T create(Class<T> contractClass);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package pl.wavesoftware.utils.stringify.configuration;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* This annotation can be used to specify if given field should be displayed even
* if it holds a null value.
*
* @author <a href="mailto:krzysztof.suszynski@coi.gov.pl">Krzysztof Suszynski</a>
* @since 27.04.18
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DisplayNull {

boolean BY_DEFAULT = false;

/**
* Do show null value on field annotated with this annotation
*
* @return true if should display
*/
boolean value() default true;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package pl.wavesoftware.utils.stringify.configuration;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

/**
* When running in {@link Mode#PROMISCUOUS} this annotation can be used to exclude a
* field from inspection.
*
* @author <a href="mailto:krzysztof.suszynski@coi.gov.pl">Krzysztof Suszynski</a>
* @since 27.04.18
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DoNotInspect {
/**
* If given this predicate will be used to conditionally check if annotated field should not
* be inspected. This can lead to implementing conditional logic of field inspection.
*
* @return a class of predicate to be used to determine if field should not be inspected
*/
Class<? extends Predicate<Field>> conditionally() default AlwaysTruePredicate.class;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package pl.wavesoftware.utils.stringify.configuration;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

/**
* If {@link Mode} is set to {@link Mode#QUIET} (by default), this annotation
* marks a field to be inspected to String representation of parent object.
* <p>
* If {@link Mode} is set to {@link Mode#PROMISCUOUS} this annotation has no function.
*
* @author <a href="krzysztof.suszynski@wavesoftware.pl">Krzysztof Suszyński</a>
* @since 2018-04-18
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Inspect {
/**
* If given this predicate will be used to conditionally check if annotated field should
* be inspected. This can lead to implementing conditional logic of field inspection.
*
* @return a class of predicate to be used to determine if field should be inspected
*/
Class<? extends Predicate<Field>> conditionally() default AlwaysTruePredicate.class;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package pl.wavesoftware.utils.stringify.configuration;

/**
* A mode of operation. In {@link #PROMISCUOUS} mode every defined field is
* automatically inspected unless the field is annotated with {@link DoNotInspect} annotation.
* <p>
* In {@link #QUIET} mode only fields annotated with {@link Inspect} will get inspected.
*
* @author <a href="mailto:krzysztof.suszynski@coi.gov.pl">Krzysztof Suszynski</a>
* @since 27.04.18
*/
public enum Mode {
PROMISCUOUS, QUIET;

public static final Mode DEFAULT_MODE = PROMISCUOUS;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package pl.wavesoftware.utils.stringify.configuration;

/**
* Represents a predicate (boolean-valued function) of one argument.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #test(Object)}.
*
* @param <T> the type of the input to the predicate
*
* @author <a href="mailto:krzysztof.suszynski@coi.gov.pl">Krzysztof Suszynski</a>
* @since 27.04.18
*/
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
Loading