Skip to content

marcosvidolin/copy-properties-assembler

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
src
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

copy-properties-assembler

Codacy Badge Build Status

A simple copy properties wrapper to convert domain into resource/dto and vice versa. Take a look at Ditiow.

Setup

Gragle

compile 'com.vidolima:copy-properties-assembler:v1.1.0'

Maven

<dependency>
	<groupId>com.vidolima</groupId>
	<artifactId>copy-properties-assembler</artifactId>
	<version>v1.1.0</version>
	<type>pom</type>
</dependency>

How to use

My entity class (usually)

@Entity
public class User {
  private String firstname;
  private String lastname;
  private String username;
  private String email;
  private String birthdate;
  // ...
}

User resource with some basics information that all users can see

public class BasicUserResource {
  private String firstname;
  private String username;
  // ...
}

User resource with full information. Only Admin can see

public class FullUserResource {
  private String firstname;
  private String lastname;
  private String username;
  private String email;
  private String birthdate;
  // ...
}

Assembler to convert the domain class (User) into a resource

public class UserAssembler extends GenericResourceAssembler<UserDomain> {
  public UserAssembler() {
    super(UserDomain.class);
  }
}

A rest controller exemplo that converts the User domain to a specific resource

@RestController
@RequestMapping(value = "/api/v1", produces = MediaType.APPLICATION_JSON_VALUE)
class UserController {
  
  private UserAssembler assembler = new UserAssember();

  /** Will return the basic user information. */
  @GetMapping(path = "/users/{username}")
  public ResponseEntity getBasicUser(@PathVariable String username) {
    User domain = this.service.findUserByUsername(username);
    BasicUserResource resource = this.assembler.fromDomain(domain, BasicUserResource.class);
    return ResponseEntity.ok(resource);
  }
  
  /** Will return all the user information (Admin only). */
  @GetMapping(path = "/admin/users/{username}")
  public ResponseEntity getBasicUser(@PathVariable String username) {
    User domain = this.service.findUserByUsername(username);
    FullUserResource resource = this.assembler.fromDomain(domain, FullUserResource.class);
    return ResponseEntity.ok(resource);
  }

}

Contributors