<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Janel</title>
    <description>The latest articles on DEV Community by Janel (@logronj).</description>
    <link>https://dev.to/logronj</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F524242%2Fbc02d93c-7237-4cfc-a7ff-91ba46d06a58.png</url>
      <title>DEV Community: Janel</title>
      <link>https://dev.to/logronj</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/logronj"/>
    <language>en</language>
    <item>
      <title>Step by step procedure on how to implement custom-like javax.validator using Jersey and Jax-rs in Springboot Application</title>
      <dc:creator>Janel</dc:creator>
      <pubDate>Sat, 06 Mar 2021 09:57:35 +0000</pubDate>
      <link>https://dev.to/logronj/step-by-step-procedure-on-how-to-implement-custom-like-javax-validator-using-jersey-and-jax-rs-in-springboot-application-3m45</link>
      <guid>https://dev.to/logronj/step-by-step-procedure-on-how-to-implement-custom-like-javax-validator-using-jersey-and-jax-rs-in-springboot-application-3m45</guid>
      <description>&lt;p&gt;Today I'm trying to implement a validator using jaxrs, I'm only familiar with springmvc using spring-starter-validator and hibernate-validator wherein the errors are bind in the BindingResult using @restController. So as I was working around I made this solution works.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;create a custom global mapper for constraintViolationException.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ConstraintValidatorExceptionMapper implements ExceptionMapper&amp;lt;ConstraintViolationException&amp;gt;{

    @Override
    public Response toResponse(ConstraintViolationException exception) {
        final Map&amp;lt;String, String&amp;gt; errorResponse =
                exception.getConstraintViolations()
                  .stream()
                  .collect(Collectors.toMap(o -&amp;gt; o.getPropertyPath().toString(), o -&amp;gt; o.getMessage()));

        return Response
                 .status(Response.Status.BAD_REQUEST)
                 .entity(errorResponse)
                 .build();
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Next create a payload request for your API.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@CompareDates
public class ViewTransactionHistoryRequest {

    @JsonProperty
    private String customerId;
    @JsonProperty
    private String cardSerNo;
    @JsonProperty 
    @NotBlank(message="contact id must not be null or empty")
    private String contactId;
    @JsonProperty
    private String dateFrom;
    @JsonProperty
    private String dateTo;
    @JsonProperty 
    private Double amountFrom;
    @JsonProperty
    private Double amountTo;
    @JsonProperty
    private int page;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Notice the &lt;code&gt;@CompareDates&lt;/code&gt; I created a sample annotation validator for validating dates.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Constraint(validatedBy = DateValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface CompareDates {

    String message() default "dateTo should not be less than dateFrom!";

    Class&amp;lt;?&amp;gt;[] groups() default {};
    Class&amp;lt;? extends Payload&amp;gt;[] payload() default {};

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Next for our endpoint we need to add &lt;code&gt;@Valid&lt;/code&gt; to trigger the validation.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @POST
    @Path("/view-transaction")
    @Consumes("application/json")
    @ApiOperation(value = "Get transaction history")
    public Object fiterBy(@RequestBody @Valid ViewTransactionHistoryRequest request) {
        LOGGER.info("Get account contact transaction history"); 
        return accountContactService.viewTransactionHistory(request);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Then register your custom validator in your jersey configuration file.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component
public class JerseyConfig extends ResourceConfig {

  @Value("${spring.jersey.application-path}")
  private String basePath;

  public JerseyConfig() {
    register(ConstraintValidatorExceptionMapper.class);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it! Sample response in postman should be something like this: &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---xBhF__y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zsi3043n7zt17m48esm.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---xBhF__y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zsi3043n7zt17m48esm.PNG" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this way we can provide to the client which fields have errors instead of just relying the 400 bad request exception response.&lt;/p&gt;

</description>
      <category>java</category>
      <category>spring</category>
      <category>jersey</category>
      <category>jaxrs</category>
    </item>
  </channel>
</rss>
