Search code examples
javahibernaterestquarkusquarkus-panache

in Java when Using Hibernate for CRUD how could we access a Header value from the initial Resteasy request


please I need help from a Java expert.

I would like to store the user how modified the record in a field of a database table using Hibernate’s @PreUpdate.

The user name is set in header field x-remote-user by the reverse proxy. I can access it as shown below

@GET
@Path("/getuser")
public String get( @HeaderParam("x-remote-user") String userName) {
  return userName;
}

Is there a way to inject @HeaderParam in my JPA entity bean? Should I lookup reflections?

This didn’t work:

@Entity
@Table(name = "t_companies")
public class TBusiness extends PanacheEntityBase {
  @Column(name = "company_name", nullable = true)
  public String companyName;
  @Column(name = "updated_by", nullable = true)
  public String updatedBy;
  
  @PreUpdate
  public void preUpdate(@HeaderParam("x-remote-user") String userName) {
    updatedBy = userName;
  }
}

Let me reformulate my question

I am using Panache data REST CRUD generation

Is there a way to have access to the header value that holds the username from a @RequestScoped class

Then use this value in the JPA entities on @PreUpdate?


Solution

  • got this to work by adding undertow dependency :

        <dependency>
          <groupId>io.quarkus</groupId>
          <artifactId>quarkus-undertow</artifactId>
        </dependency>
    

    then in an EntityListener class created below PrePersist method:

    
    @RequestScoped
    // @Path("api/v1/Header")
    public class AuditingEntityListener {
      private static final Logger LOG = Logger.getLogger(AuditingEntityListener.class);
    
      // Inject the bean so that Quarkus does not remove it at build time (IMPORTANT)
      @Inject
      HttpServletRequest requestNotUsed;
    
      @PrePersist
      void onPrePersist(TBusiness myEntity) {
        HttpServletRequest HSR = CDI.current().select(HttpServletRequest.class).get();
        LOG.info("HSR getRequestHeader user: " + HSR.getHeader("x-remote-user"));
      }
    }