<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Carl Mapada on Medium]]></title>
        <description><![CDATA[Stories by Carl Mapada on Medium]]></description>
        <link>https://medium.com/@cmmapada?source=rss-fb7e7b43a19e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AestI3DPGuh-jUFmB53ekQ.jpeg</url>
            <title>Stories by Carl Mapada on Medium</title>
            <link>https://medium.com/@cmmapada?source=rss-fb7e7b43a19e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:27:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cmmapada/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Advanced Search and Filtering using Spring Data JPA Specification and Criteria API]]></title>
            <link>https://medium.com/@cmmapada/advanced-search-and-filtering-using-spring-data-jpa-specification-and-criteria-api-b6e8f891f2bf?source=rss-fb7e7b43a19e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6e8f891f2bf</guid>
            <dc:creator><![CDATA[Carl Mapada]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 05:57:46 GMT</pubDate>
            <atom:updated>2022-02-21T05:57:46.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W6um08VCwpzhs8nA" /><figcaption>Photo by <a href="https://unsplash.com/@nixcreative?utm_source=medium&amp;utm_medium=referral">Tyler Nix</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>The Spring Data JPA makes it easy for developers to implement data access layers. You will just need to write the repository interfaces including the custom finder method and Spring Data will provide the implementation automatically. Database queries are generated based on method names.</p><pre>@Repository <br>public interface EmployeeRepository extends JPARepository&lt;  <br>                                                   Employee,Long&gt;        <br>{<br>     List&lt;Employee&gt; findAll();<br>     Optional&lt;Employee&gt; findById(Long employeeId);<br>     List&lt;Employee&gt; findByFirstNameAndLastName(String firstNm, <br>                                               String lastNm);<br>}</pre><p>However, certain cases in our application require complex queries to fetch the needed data, and using a simple method name query generator for Spring Data will no longer suffice.</p><p>For this tutorial’s purpose, for example, you have a page that shows a list of employees, and the list contains thousands of records. The application allows you to filter employees based on some filter keys and criteria using the employee search functionality as shown below. The question right now is how do we implement the SQL queries to be able to fetch the records that we need based on the inputted search criteria considering that the application user is allowed to input multiple search criteria.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLJvg64O9nMHvX7wIj2lqQ.png" /><figcaption>Advanced Search Modal</figcaption></figure><p>One way to solve this problem is to create dynamic queries and luckily for us, Spring allows us to generate dynamic queries through the use of the Spring Data Specification and Criteria API.</p><h3><strong>Specification and Criteria API in Action</strong></h3><p>To illustrate how to use Specification and Criteria API to perform dynamic queries, let’s create a simple employee search REST service that will return a list of employees based on the search criteria. The endpoint and sample JSON payload is shown below. Basically, the payload contains a list of search criteria and each search criteria has a “filter key”, “operation” and “value”.</p><p><strong><em>API Endpoint:</em></strong><em> http://localhost:8080/</em>api/v1/search</p><p><strong>Payload:</strong></p><pre>{<br>    &quot;dataOption&quot;:&quot;all&quot;,<br>    &quot;searchCriteriaList&quot;:[<br>       {<br>          &quot;filterKey&quot;:&quot;deptName&quot;,<br>          &quot;operation&quot;:&quot;eq&quot;,<br>          &quot;value&quot;:&quot;MARKETING&quot;<br>       },<br>       {<br>          &quot;filterKey&quot;:&quot;salary&quot;,<br>          &quot;operation&quot;:&quot;lt&quot;,<br>          &quot;value&quot;:2957<br>       },<br>       {<br>          &quot;filterKey&quot;:&quot;emplastNm&quot;,<br>          &quot;operation&quot;:&quot;ne&quot;,<br>          &quot;value&quot;:&quot;Stella&quot;<br>       },<br>       {<br>          &quot;filterKey&quot;:&quot;commission&quot;,<br>          &quot;operation&quot;:&quot;gt&quot;,<br>          &quot;value&quot;:0<br>       },<br>       {<br>          &quot;filterKey&quot;:&quot;empId&quot;,<br>          &quot;operation&quot;:&quot;eq&quot;,<br>          &quot;value&quot;:64989<br>       }<br>    ]<br>}</pre><p>As a reference, the summary of available filter keys and its corresponding operations is shown on the below table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*gnN5bBZkfKvtY2Q_bsuH_g.png" /></figure><p>Now that we have define our endpoint and our payload let us now proceed in defining the table structure for our data. Looking at the table structure we can then create 3 entity classes namely Employee, Department, and SalaryGrade. One thing to note here is the relationship of Department and Employee, this relationship has to be implemented in both entities (i.e. ManyToOne and OneToMany).</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*gLCQlpwCF9I2tsT1gHOn7A.png" /><figcaption>Database Structure — <a href="https://www.w3resource.com/sql-exercises/employee-database-exercise/index.php">Source</a></figcaption></figure><p><strong><em>Entities</em></strong></p><pre>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Entity<br>public class Employee {<br><br>    @Id<br>    @Column(name = &quot;EMP_ID&quot;)<br>    private Long emp_id;<br><br>    @Column(name = &quot;EMP_LASTNM&quot;)<br>    private String emp_lastNm;<br><br>    @Column(name = &quot;EMP_FIRSTNM&quot;)<br>    private String  emp_firstNm;<br><br>    @Column(name = &quot;JOB_NM&quot;)<br>    private String jobNm;<br><br>    @Column(name = &quot;MGR_ID&quot;, nullable = true)<br>    private Long manager_id;<br><br>    @Column(name = &quot;HIREDT&quot;)<br>    private Date hireDt;<br><br>    @Column(name = &quot;SALARY&quot;)<br>    private double salary;<br><br>    @Column(name = &quot;COMMISSION&quot;, nullable = true)<br>    private double commission;<br><br>    @ManyToOne<br>    @JoinColumn(name = &quot;DEPT_ID&quot;)<br>    private Department department;<br><br>}</pre><pre>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Entity<br>public class Department {<br><br>    @Id<br>    private Long dept_id;<br><br>    @Column(name = &quot;DEPT_NAME&quot;)<br>    private String dept_name;<br><br>    @OneToMany(mappedBy = &quot;department&quot;)<br>    @JsonIgnore<br>    private List&lt;Employee&gt; emps;<br><br>}</pre><pre>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Entity<br>public class SalaryGrade {<br><br>    @Id<br>    private Long grade;<br>    private double min_salary;<br>    private double max_salary;<br>}</pre><p>We will define all possible search operation and data option inside an Enum. I will explain later on the purpose of the data option which has two possible values: ANY and ALL.</p><pre>public enum SearchOperation {<br><br>    <em>CONTAINS</em>, <em>DOES_NOT_CONTAIN</em>, <em>EQUAL</em>, <em>NOT_EQUAL</em>, <em>BEGINS_WITH, <br>    DOES_NOT_BEGIN_WITH</em>, <em>ENDS_WITH</em>, <em>DOES_NOT_END_WITH</em>, <br>    <em>NUL</em>, <em>NOT_NULL</em>, <em>GREATER_THAN</em>, <em>GREATER_THAN_EQUAL</em>, <em>LESS_THAN</em>,<br>    <em>LESS_THAN_EQUAL</em>, <em>ANY</em>, <em>ALL</em>;</pre><pre>    public static final String[] <em>SIMPLE_OPERATION_SET </em>= {<br>             &quot;cn&quot;, &quot;nc&quot;, &quot;eq&quot;, &quot;ne&quot;, &quot;bw&quot;, &quot;bn&quot;, &quot;ew&quot;,<br>             &quot;en&quot;, &quot;nu&quot;, &quot;nn&quot;, &quot;gt&quot;, &quot;ge&quot;, &quot;lt&quot;, &quot;le&quot; };<br><br>    public static SearchOperation getDataOption(final String<br>                                                dataOption){<br>         switch(dataOption){<br>            case &quot;all&quot;: return <em>ALL</em>;<br>            case &quot;any&quot;: return <em>ANY</em>;<br>            default: return null;<br>        }    <br>    }<br><br>    public static SearchOperation getSimpleOperation(<br>                                  final String input) {<br>        switch (input){<br>            case &quot;cn&quot;: return <em>CONTAINS</em>;<br>            case &quot;nc&quot;: return <em>DOES_NOT_CONTAIN</em>;<br>            case &quot;eq&quot;: return <em>EQUAL</em>;<br>            case &quot;ne&quot;: return <em>NOT_EQUAL</em>;<br>            case &quot;bw&quot;: return <em>BEGINS_WITH</em>;<br>            case &quot;bn&quot;: return <em>DOES_NOT_BEGIN_WITH</em>;<br>            case &quot;ew&quot;: return <em>ENDS_WITH</em>;<br>            case &quot;en&quot;: return <em>DOES_NOT_END_WITH</em>;<br>            case &quot;nu&quot;: return <em>NUL</em>;<br>            case &quot;nn&quot;: return <em>NOT_NULL</em>;<br>            case &quot;gt&quot;: return <em>GREATER_THAN</em>;<br>            case &quot;ge&quot;: return <em>GREATER_THAN_EQUAL</em>;<br>            case &quot;lt&quot;: return <em>LESS_THAN</em>;<br>            case &quot;le&quot;: return <em>LESS_THAN_EQUAL</em>;<br><br>            default: return null;<br>        }<br>    }<br>}</pre><p>We will represent the search criteria (filterKey, value, and operation) as a class, and let’s name it as <strong><em>SearchCriteria</em></strong>. The corresponding POJO equivalent of the JSON payload will also be created and we will name it as <strong><em>EmployeeSearchDto</em></strong>.</p><pre>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>public class SearchCriteria {<br><br>    private String filterKey;<br>    private Object value;<br>    private String operation;<br>    private String dataOption;<br><br>    public SearchCriteria(String filterKey, String operation, <br>                          Object value){<br>        super();<br>        this.filterKey = filterKey;<br>        this.operation = operation;<br>        this.value = value;<br>    }<br>}</pre><pre>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class EmployeeSearchDto {<br><br>    private List&lt;SearchCriteria&gt; searchCriteriaList;<br>    private String dataOption;<br><br>}</pre><h3>Specification</h3><p>Criteria API was introduced in JPA 2.0 which you can use to build queries programmatically. One of the advantages of Criteria API is that it prohibits the construction of queries that are syntactically incorrect which is one of the limitations of JPQL in JPA 1.0. By writing <strong><em>criteria</em></strong>, you define the where clause of a query for a domain class. These criteria can be regarded as a predicate over the entity that is described by the JPA criteria API constraints.</p><p>The Specification interface is another tool in the Spring Data JPA that is built on top of the Criteria API which makes it easier for developers to build atomic predicates and combine these predicates to build complex dynamic queries.</p><p>So, our next step is to create <strong><em>EmployeeSpecification</em></strong> class that implements the Specification interface. We will then override the<strong><em> toPredicate</em></strong> method. Inside this method, we will implement different reusable predicates depending on the search operation (i.e. CONTAINS, DOES_NOT_CONTAIN, EQUAL, NOT_EQUAL..). A special <strong><em>departmentJoin </em></strong>method is added to implement the inner join of the Employee and Department table. The join is performed when the department name is included in the search criteria.</p><pre>public class EmployeeSpecification implements  <br>             Specification&lt;Employee&gt; {</pre><pre>    private final SearchCriteria searchCriteria;<br><br>    public EmployeeSpecification(final SearchCriteria<br>                                 searchCriteria){<br>        super();<br>        this.searchCriteria = searchCriteria;<br>    }<br><br>    @Override<br>    public Predicate toPredicate(Root&lt;Employee&gt; root,<br>                     CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb) {<br>        String strToSearch = searchCriteria.getValue()<br>                                          .toString().toLowerCase();<br>     <br>        switch(Objects.<em>requireNonNull</em>(<br>                               SearchOperation.<em>getSimpleOperation<br>                               </em>(searchCriteria.getOperation()))){<br>            case <em>CONTAINS</em>:<br>                if(searchCriteria.getFilterKey().equals(&quot;deptName&quot;))<br>                {<br>                   return cb.like(cb.lower(departmentJoin(root).<br>                       &lt;String&gt;get(searchCriteria.getFilterKey())),<br>                       &quot;%&quot; + strToSearch + &quot;%&quot;);<br>                }<br>                return cb.like(cb.lower(root<br>                         .get(searchCriteria.getFilterKey())), <br>                         &quot;%&quot; + strToSearch + &quot;%&quot;);<br><br>            case <em>DOES_NOT_CONTAIN</em>:<br>                if(searchCriteria.getFilterKey().equals(&quot;deptName&quot;))<br>                {<br>                   return cb.notLike(cb.lower(departmentJoin(root).        <br>                       &lt;String&gt;get(searchCriteria.getFilterKey())),<br>                       &quot;%&quot; + strToSearch +&quot;%&quot;);<br>                }<br>                return cb.notLike(cb.lower(root<br>                         .get(searchCriteria.getFilterKey())), <br>                         &quot;%&quot; + strToSearch + &quot;%&quot;);</pre><pre>            .....<br>            .....<br>        }<br>     }</pre><pre>     private Join&lt;Employee,Department&gt; departmentJoin(Root&lt;Employee&gt;  <br>                                       root){<br>            return root.join(&quot;department&quot;);<br>     }<br>}</pre><h3>Specification Builder</h3><p>Since our search can contain multiple search criteria, we need to be able to combine all predicates. This is where the EmpSpecificationBuilder class comes in to picture. The build method in the builder class combines all predicates. It does an “OR” operation when the dataOption is “ANY” and “AND” operation when the “dataOption” is “ALL”.</p><pre>public class EmpSpecificationBuilder {<br><br>    private final List&lt;SearchCriteria&gt; params;<br><br>    public EmpSpecificationBuilder(){<br>        this.params = new ArrayList&lt;&gt;();<br>    }<br><br>    public final EmpSpecificationBuilder with(String key, <br>                          String operation, Object value){<br>        params.add(new SearchCriteria(key, operation, value));<br>        return this;<br>    }<br><br>    public final EmpSpecificationBuilder with(SearchCriteria<br>                    searchCriteria){<br>        params.add(searchCriteria);<br>        return this;<br>    }<br><br>    public Specification&lt;Employee&gt; build(){<br>        if(params.size() == 0){<br>            return null;<br>        }<br><br>        Specification&lt;Employee&gt; result = <br>                   new EmployeeSpecification(params.get(0));<br>        for (int idx = 1; idx &lt; params.size(); idx++){<br>            SearchCriteria criteria = params.get(idx);<br>            result =  SearchOperation.<em>getDataOption</em>(criteria<br>                     .getDataOption()) == SearchOperation.<em>ALL<br>                     </em>? Specification.<em>where</em>(result).and(new    <br>                       EmployeeSpecification(criteria))<br>                     : Specification.<em>where</em>(result).or(<br>                       new EmployeeSpecification(criteria));<br>        }<br>        return result;<br>    }<br>}</pre><h3>EmployeeRepository</h3><p>To support the specification we have to modify the Repository and extend the <strong><em>JpaSpecificationExecutor </em></strong>interface. By doing this, there are methods that will be available for us to use to execute specifications. One particular example is the <strong>List&lt;T&gt; findAll(Specification&lt;T&gt; spec).</strong></p><pre>@Repository<br>public interface EmployeeRepository extends JpaRepository&lt;Employee, Long&gt;, <strong>JpaSpecificationExecutor</strong>&lt;Employee&gt; {<br>}</pre><h3><strong>Controller and Service</strong></h3><p>In the controller class we create an instance of the EmpSpecificationBuilder class and we invoke the builder method for each search criteria. We then call the <strong>findBySearchCriteria </strong>from the EmployeeService passing in the specification returned by the build method.</p><pre>@RestController<br>@RequestMapping(&quot;api/v1&quot;)<br>public class AdvSearchController {<br><br>    @Autowired<br>    private EmployeeService empService;<br><br>   <br>    @PostMapping(&quot;/search&quot;)<br>    public ResponseEntity&lt;APIResponse&gt; searchEmployees<br>                         (@RequestParam(name = &quot;pageNum&quot;, <br>                           defaultValue = &quot;0&quot;) int pageNum,<br>                          @RequestParam(name = &quot;pageSize&quot;, <br>                           defaultValue = &quot;10&quot;) int pageSize,<br>                          @RequestBody EmployeeSearchDto <br>                           employeeSearchDto){</pre><pre>        APIResponse apiResponse = new APIResponse();<br>        <strong>EmpSpecificationBuilder builder = new <br>                                          EmpSpecificationBuilder();</strong><br>        List&lt;SearchCriteria&gt; criteriaList = <br>                          employeeSearchDto.getSearchCriteriaList();<br>        if(criteriaList != null){<br>            criteriaList.forEach(x-&gt; <br>                                {<strong>x.setDataOption(employeeSearchDto<br>                                  .getDataOption());<br>                                  builder.with(x)</strong>;<br>            });<br>        }<br><br>        Pageable page = PageRequest.<em>of</em>(pageNum, pageSize, <br>                               Sort.<em>by</em>(&quot;empfirstNm&quot;)     <br>                                   .ascending()<br>                                   .and(Sort.<em>by</em>(&quot;emplastNm&quot;))<br>                                   .ascending()<br>                                   .and(Sort.<em>by</em>(&quot;department&quot;))<br>                                   .ascending());<br><br>        Page&lt;Employee&gt; employeePage = <br>              <strong>empService.findBySearchCriteria(builder.build(),   <br>                                              page</strong>);<br>        apiResponse.setData(employeePage.toList());<br>        apiResponse.setResponseCode(HttpStatus.<em>OK</em>);<br>        apiResponse.setMessage(&quot;Successfully retrieved employee <br>                                record&quot;);<br><br>        return new ResponseEntity&lt;&gt;(apiResponse, <br>                            apiResponse.getResponseCode());<br>    }<br>}</pre><pre>@Service<br>public class EmployeeService {<br><br>    @Autowired<br>    private EmployeeRepository empRepository;<br><br>    public EmployeeDto addEmployee(EmployeeDto employeeDto){<br>        Employee emp = DomainDtoMapper.<em>getEmployee</em>(employeeDto);<br>        return DomainDtoMapper.<br>               <em>getEmployeeDto</em>(empRepository.saveAndFlush(emp));<br>    }<br><br>    public List&lt;Employee&gt; findAllEmployee(){<br>        return empRepository.findAll();<br>    }<br><br>    public Page&lt;Employee&gt; findBySearchCriteria<br>              <strong>(Specification&lt;Employee&gt; spec, Pageable page){<br>        Page&lt;Employee&gt; searchResult = empRepository.findAll(spec,<br>                                                             page);</strong><br>        return searchResult;<br>    }<br>}</pre><h3>Testing in Postman</h3><p>Below is the sample response of the API tested in POSTMAN. Code can be found on my <a href="https://github.com/carlmaps/AdvancedSearch/tree/master/advanced-search-api/advanced-search">github </a>account. Happy Coding :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uy_ZUK2pjRZJYknssrDSCw.png" /><figcaption>Advanced Employee Search in Postman</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pigxd35uK4pbR-3_66b4cQ.png" /><figcaption>Employee Search API Response</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6e8f891f2bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Use The Spring Validator]]></title>
            <link>https://medium.com/@cmmapada/how-to-use-the-spring-validator-7679de300a7?source=rss-fb7e7b43a19e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7679de300a7</guid>
            <category><![CDATA[spring-validation]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[spring-mvc]]></category>
            <dc:creator><![CDATA[Carl Mapada]]></dc:creator>
            <pubDate>Sun, 02 Jan 2022 04:34:42 GMT</pubDate>
            <atom:updated>2022-01-02T04:34:42.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhoci9oyAuNB2lWGcAha9g.jpeg" /><figcaption>Validation — <a href="https://www.dreamstime.com/illustration-validation-concept-image139299774">source</a></figcaption></figure><h3>Introduction</h3><p>Data validation is an essential part of any web application. This is the process of checking the data to ensure its correctness based on the application requirements. Validation rules are used to verify the validity and correctness of the data. These validation rules can be implemented in the client-side or in the server-side.</p><p>In Spring, the de facto standard for validation is the Bean Validation. The API contains standard validators which can be used easily by using simple annotations. Example of the annotations are:</p><ul><li>@NotNull — validates that the annotated property is not null</li><li>@NotEmpty — validates that the annotated property is not null or empty</li><li>@Min — validates that the annotated property has a value no smaller than the value attribute</li><li>@Max — validates that the annotated property has a value no greater than the value attribute</li><li>@Email — validates that the annotated property is a valid email address</li><li>@Past — validates that the date property is in the past</li><li>@PastOrPresent — validates that the date property is in the past</li></ul><p>In most cases, these validator will suffice. However, there are cases where in we need to validate the input data based on some custom business rule. The way to handle this type of situation is to create our own custom validator.</p><h3>Spring Validator Interface</h3><p>Spring features a Validator Interface that be used to validate objects. The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.</p><h4>Implementing Custom Validator Using Validator Interface</h4><p>Let say we have a hypothetical FielTrip form that contains the following fields: student name, age, guardian name. Business rule requires the guardian’s name as a required field if the age of the student is less than 18 otherwise this field is optional. Since the guardians name has a dependency on the age of the student, we need to write our custom validator. One way to do this is to use the Validator interface.</p><pre>public class FieldTripForm{</pre><pre>     private String name;<br>     private int age;<br>     private String guardian;</pre><pre>     //constructor ...<br>     <br>     //getter and setter ...<br>}</pre><h4>Steps to implement custom validator</h4><ul><li><strong><em>Create a class that implements the Validator interface.</em></strong></li></ul><p>There are two methods that you need to override when you implement the Validator interface, the support and the validate method. The support method is invoked by Spring prior to the validation. Inside the support method you have to specify the instance of class that the custom validator can validate. This can be done by calling the isAssignableFrom method.</p><p>The validate method validates the given object and, in case of validation errors, registers those with the given Errors object. In the example below, we used the <strong><em>rejectIfEmptyOrWhitespace</em></strong><em> </em>to check if the field is either null or an empty string. In the case of the guardian field, we only perform the validation if age is greater than 18. If any of these form fields is empty, the <em>rejectIfEmptyOrWhitespace </em>method will create a field error and bind it to the field.</p><pre>@Component<br>public class FieldTripFormValidator implements Validator{</pre><pre>     @Override<br>     public boolean supports(Class clazz) {<br>           return FieldTripForm.class.isAssignableFrom(clazz);<br>     }</pre><pre>     @Override<br>     public void validate(Object target, Errors errors){<br>          <br>          FieldTripForm form = (FieldTripForm) target;<br>          </pre><pre>          if(errors.getErrors == 0){<br>             ValidationUtils.rejectIfEmptyOrWhitespace(<br>                          errors, &quot;age&quot;,<br>                          &quot;error.age&quot;, <br>                          &quot;Age is required.&quot;);</pre><pre>             ValidationUtils.rejectIfEmptyOrWhitespace(<br>                          errors, &quot;name&quot;,<br>                          &quot;error.name&quot;, <br>                          &quot;Nameis required.&quot;);<br> <br>              if(form.getAge() &lt; 18){<br>                  ValidationUtils.rejectIfEmptyOrWhitespace(       <br>                                   errors, &quot;guardian&quot;, <br>                                   &quot;error.guardian&quot;, <br>                                   &quot;Guardian name is required.&quot;);<br>              }<br>           }</pre><pre>       }<br>}</pre><ul><li><strong><em>Add the validator reference in the Controller class</em></strong></li></ul><pre>@Autowired<br>private FieldTripFormValidator ftfValidator;</pre><ul><li><strong><em>Bind the custom validator to the controller</em></strong></li></ul><pre>@InitBinder(value = &quot;fieldTripForm&quot;)<br>protected void initBinder(WebDataBinder binder) {<br>      binder.setValidator(ftfValidator);<br>}</pre><ul><li><strong><em>Annotate the controller method parameter with @Valid.</em></strong></li></ul><p>Exception is thrown when validation on an argument annotated with @Valid fails. Specifically, it will throw the MethodArgumentNotValidException.</p><pre>@RestController<br>@RequestMapping(&quot;/&quot;)<br>public class FieldTripController{</pre><pre>    @Autowired<br>    private FieldTripFormValidator ftfValidator;</pre><pre>    @Autowired <br>    private FieldTripService ftService;</pre><pre>    @InitBinder(value = &quot;fieldTripForm&quot;)<br>    protected void initBinder(WebDataBinder binder) {<br>      binder.setValidator(ftfValidator);<br>    }</pre><pre>    @PostMapping(value = &quot;/fieldtrip&quot;)<br>    public ResponseEntity&lt;APIResponse&gt; signUp(<strong>@Valid</strong> @RequestBody<br>                                     FieldTripForm ftf){</pre><pre>        APIResponse apiResponse = new APIResponse();<br>        //perform your logic here</pre><pre>        return new ResponseEntity&lt;&gt;(apiResponse, HttpStatus.<em>OK</em>);</pre><pre>    }</pre><pre>}</pre><ul><li><strong><em>Create a GlobalExceptionHandler</em></strong></li></ul><p>It is important to annotate the GlobalExceptionHandler with @ControllerAdvice. This will allow you to handle exception across your application. Inside the GlobalExceptionHandler class, we define a method handleMethodArgumentNotValid which will handle exception of this type.</p><pre>@ControllerAdvice<br>public class GlobalExceptionHandler{</pre><pre>    @ExceptionHandler({MethodArgumentNotValidException.class})</pre><pre>    public final ResponseEntity&lt;Object&gt; handleException(<br>         Exception ex, WebRequest request){<br>       HttpHeaders headers = new HttpHeaders();</pre><pre>       if(ex instanceof MethodArgumentNotValidException){<br>            return handleMethodArgumentNotValid(<br>            (MethodArgumentNotValidException) ex, headers,<br>             HttpStatus.BAD_REQUEST, request);<br>       }<br>       return null;<br>    }</pre><pre>    private ResponseEntity&lt;Object&gt; handleMethodArgumentNotValid(<br>             MethodArgumentNotValidException ex, <br>             HttpHeaders headers, HttpStatus status,<br>             WebRequest request){</pre><pre>      Map&lt;String, Object&gt; fieldError = new HashMap&lt;&gt;();<br>      List&lt;FieldError&gt; fieldErrors = ex.getBindingResult()<br>                                       .getFieldErrors();<br>      fieldErrors.stream().forEach(error -&gt; fieldError.put(<br>                  error.getField(), error.getDefaultMessage()));</pre><pre>      Map&lt;String, Object&gt; response= new HashMap&lt;&gt;();<br>      response.put(&quot;isSuccess&quot;, false);<br>      response.put(&quot;data&quot;, null);<br>      response.put(&quot;status&quot;, status);<br>      response.put(&quot;fieldError&quot;, fieldError);</pre><pre>      return new ResponseEntity&lt;&gt;(response, status);<br>   }<br>}</pre><h4>Testing on Postman</h4><p>As you can see on the response body of the request, there is a fieldError on the guardian field with a message “Guardian name is required”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEUKVxeFfVDLE1Fihh1B7w.jpeg" /></figure><p>I hope you learn something from this tutorial. Code used in this tutorial can be found on my <a href="https://github.com/carlmaps/customValidator">github</a>. Enjoy and keep on coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7679de300a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hand Gesture Recognition]]></title>
            <link>https://medium.com/@cmmapada/hand-gesture-recognition-5cdc0e380854?source=rss-fb7e7b43a19e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cdc0e380854</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Carl Mapada]]></dc:creator>
            <pubDate>Thu, 30 Dec 2021 17:08:30 GMT</pubDate>
            <atom:updated>2021-12-30T17:08:30.862Z</atom:updated>
            <content:encoded><![CDATA[<p>An ML transfer learning project using VGG-16 CNN model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pf-Rgg0SAcN7UuCS" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this project, I will walk you through on how I implemented a hand gesture recognition system by performing a transfer learning on VGG16. VGG16 is a convolutional neural network proposed by K. Simonyan and A. Zisserman from the University of Oxford in the paper “Very Deep Convolutional Networks for Large-Scale Image Recognition”. In this project, since I couldn’t find an existing dataset that I can play around, I created my own dataset by taking a picture of my hand with different hand gestures. I also asked 2 of friends to take a sample pictures of their hand for the same hand gesture that I took. The goal is to be able to trained a model that can identify 4 different hand gesture namely, up, down, play mute. The model will then be used in a simple desktop application that will control the on and off of the computer speaker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mDssbIhzJHw2IFaZMZ_fdg.png" /><figcaption>Hand Gesture Sample Images for “UP”, “DOWN”, “MUTE”, PLAY”</figcaption></figure><h4>VGG-16 Architecture</h4><p>VGG stands for Visual Geometry Group. In a nutshell, VGG-16 is a deep convolutional neural network with 16 denoting the number of convolutional layers. The VGG16 network utilizes a fixed sized kernel is used instead of variable sized kernels. It achieves almost 92.7% top-5 test accuracy in ImageNet. ImageNet is a dataset consisting of more than 14 million images belonging to nearly 1000 classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*4lpDNqwFB4C2Wp10bsTMiA.jpeg" /><figcaption>VGG-16 Architecture — <a href="https://icmlviz.github.io/icmlviz2016/assets/papers/4.pdf">Source</a></figcaption></figure><p>The architecture basically contains the following:</p><ul><li>Input Layer</li><li>Convolutional Layer</li><li>Hidden Layer</li><li>Fully Connected Layer</li></ul><h4>Transfer Learning</h4><p>In cognitive psychology, transfer of learning means using the previously acquired knowledge and skills in solving a new problem. Similarly in deep convolutional neural network, transfer learning is common technique used by machine learning or AI engineer to re-use pre trained model and customize it to solve another task or problem.</p><h4>Experiment Workflow</h4><p>Since I’m generating my own dataset, I followed a simple experiment workflow and observe how the transfer learning model behaves as increase my dataset.</p><ol><li>Gather hand gesture dataset. Initial dataset is around 800 images, 200 sample pictures for each hand gesture.</li><li>Load the dataset, create labels, perform shuffling</li><li>Perform train_test_split on the dataset</li><li>Create a base model from the pre trained VGG-16.</li><li>Customized the model by creating a new model on top of the based model</li><li>Perform data augmentation</li><li>Train the model</li><li>Plot model accuracy and loss</li></ol><p>I made 5 iterations on the workflow, and in each iteration additional sample images are added to the dataset.</p><p><em>Loading the dataset</em></p><pre>#Transfer &#39;jpg&#39; images to an array IMG<br>def Dataset_loader(DIR, RESIZE, sigmaX=10):<br>    IMG = []<br>    read = lambda imname:np.asarray(Image.open(imname)<br>                                         .convert(&quot;RGB&quot;))     <br>    for IMAGE_NAME in tqdm(os.listdir(DIR)):<br>        PATH = os.path.join(DIR,IMAGE_NAME)<br>        _, ftype = os.path.splitext(PATH)<br>        if ftype == &quot;.jpg&quot;:<br>            img = read(PATH)<br>           <br>            img = cv2.resize(img, (RESIZE,RESIZE))<br>           <br>            IMG.append(np.array(img))<br>    return IMG</pre><pre>up = np.array(Dataset_loader(&#39;training_images/up&#39;,224))<br>down = np.array(Dataset_loader(&#39;training_images/down&#39;,224))<br>mute = np.array(Dataset_loader(&#39;training_images/mute&#39;,224))<br>play = np.array(Dataset_loader(&#39;training_images/play&#39;,224))</pre><p><em>Create labels</em></p><pre># Create labels<br>up_label = np.zeros(len(up))<br>down_label = np.ones(len(down))<br>mute_label = np.full((len(mute),), 2)<br>play_label = np.full((len(play),), 3)</pre><p><em>Performing shuffling</em></p><pre>data = np.concatenate((up, down, mute, play), axis = 0)<br>labels = np.concatenate((up_label, down_label, mute_label, play_label), axis = 0)</pre><pre>data = np.array(data, dtype=&quot;float32&quot;)<br>labels = np.array(labels, dtype=&quot;int&quot;)<br>data /= 255.0</pre><pre># shuffle data<br>arr = np.arange(len(data))<br>np.random.shuffle(arr)<br>data = data[arr]<br>labels = labels[arr]</pre><p><em>Train — Test — Split</em></p><pre>from sklearn.preprocessing import LabelBinarizer</pre><pre>le = LabelBinarizer()<br>labels = le.fit_transform(labels)<br>counts = labels.sum(axis=0)</pre><pre>from sklearn.model_selection import train_test_split<br>(trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.20, stratify=labels, random_state=42)</pre><h4>Creating the base model</h4><p>To make it easier to repeat the process of creating a base model, I made a function which is design to select the base model either DenseNet or Resnet or VGG-16. For the purpose of this project, the VGG-16 model is selected and instantiated with weights trained on ImageNet. The top layer which is the classification layer is excluded and the input shape of the image is set to 224x224x3.</p><pre>def createBackboneModel(denseNet=False, resnet=False, vgg=False, ):<br>    if denseNet: <br>       backbone = DenseNet201(weights=&#39;imagenet&#39;,include_top=False,<br>                  input_shape=(224,224,3))<br>    if resnet: <br>       backbone = ResNet50(weights=&#39;imagenet&#39;,include_top=False,<br>                  input_shape=(224,224,3))<br>    if vgg: <br>       backbone = VGG16(weights=&#39;imagenet&#39;,include_top=False,<br>                  input_shape=(224,224,3))</pre><pre>    output = backbone.layers[-1].output<br>    output = keras.layers.Flatten()(output)<br>    backboneModel = Model(backbone.input, outputs=output)</pre><pre>    for layer in backboneModel.layers:<br>        layer.trainable = False</pre><pre>    return backboneModel</pre><h4>Creating the model</h4><p>This is part where a new model is created on top base model. To easily configure the new model, a function is created with parameter set to some default values. This way I could easily adjust the learning rate, the dense layer and the dropout layer.</p><pre>def createModel(backbone, lr=1e-4, dense=128, drpout1=0.5, drpout2=0.25):<br>    EPOCHS = 50<br>    INIT_LR = 1e-1<br>    BS = 128<br>    model = Sequential()<br>    model.add(backbone)<br>    model.add(Dropout(drpout1))<br>    model.add(Dense(dense, activation=&#39;relu&#39;))<br>#     model.add(LeakyReLU(alpha=0.1))<br>#     model.add(BatchNormalization())<br>    model.add(Dropout(drpout2))<br>    model.add(Dense(4, activation=&#39;softmax&#39;))<br>    <br>  <br>    model.compile(<br>        loss=keras.losses.categorical_crossentropy,<br>        optimizer=Adam(learning_rate=lr),<br>        metrics=[&#39;accuracy&#39;]<br>    )<br>    <br>    return model</pre><h4>Loading the pretrained VGG-16 model</h4><pre>backbone = createBackboneModel(vgg=True)<br>backbone.summary()</pre><pre>Model: &quot;model_1&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>input_2 (InputLayer)         [(None, 224, 224, 3)]     0         <br>_________________________________________________________________<br>block1_conv1 (Conv2D)        (None, 224, 224, 64)      1792      <br>_________________________________________________________________<br>block1_conv2 (Conv2D)        (None, 224, 224, 64)      36928     <br>_________________________________________________________________<br>block1_pool (MaxPooling2D)   (None, 112, 112, 64)      0         <br>_________________________________________________________________<br>block2_conv1 (Conv2D)        (None, 112, 112, 128)     73856     <br>_________________________________________________________________<br>block2_conv2 (Conv2D)        (None, 112, 112, 128)     147584    <br>_________________________________________________________________<br>block2_pool (MaxPooling2D)   (None, 56, 56, 128)       0         <br>_________________________________________________________________<br>block3_conv1 (Conv2D)        (None, 56, 56, 256)       295168    <br>_________________________________________________________________<br>block3_conv2 (Conv2D)        (None, 56, 56, 256)       590080    <br>_________________________________________________________________<br>block3_conv3 (Conv2D)        (None, 56, 56, 256)       590080    <br>_________________________________________________________________<br>block3_pool (MaxPooling2D)   (None, 28, 28, 256)       0         <br>_________________________________________________________________<br>block4_conv1 (Conv2D)        (None, 28, 28, 512)       1180160   <br>_________________________________________________________________<br>block4_conv2 (Conv2D)        (None, 28, 28, 512)       2359808   <br>_________________________________________________________________<br>block4_conv3 (Conv2D)        (None, 28, 28, 512)       2359808   <br>_________________________________________________________________<br>block4_pool (MaxPooling2D)   (None, 14, 14, 512)       0         <br>_________________________________________________________________<br>block5_conv1 (Conv2D)        (None, 14, 14, 512)       2359808   <br>_________________________________________________________________<br>block5_conv2 (Conv2D)        (None, 14, 14, 512)       2359808   <br>_________________________________________________________________<br>block5_conv3 (Conv2D)        (None, 14, 14, 512)       2359808   <br>_________________________________________________________________<br>block5_pool (MaxPooling2D)   (None, 7, 7, 512)         0         <br>_________________________________________________________________<br>flatten_1 (Flatten)          (None, 25088)             0         <br>=================================================================<br>Total params: 14,714,688<br>Trainable params: 0<br>Non-trainable params: 14,714,688</pre><h4>Loading the new model</h4><pre>model = createModel(backbone,lr=1e-4, drpout1=0.3, drpout2=0.2)<br>model.summary()<br>Model: &quot;sequential_1&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>model_1 (Functional)         (None, 25088)             14714688  <br>_________________________________________________________________<br>dropout_2 (Dropout)          (None, 25088)             0         <br>_________________________________________________________________<br>dense_2 (Dense)              (None, 128)               3211392   <br>_________________________________________________________________<br>dropout_3 (Dropout)          (None, 128)               0         <br>_________________________________________________________________<br>dense_3 (Dense)              (None, 4)                 516       <br>=================================================================<br>Total params: 17,926,596<br>Trainable params: 3,211,908<br>Non-trainable params: 14,714,688</pre><h4>Fit and Plot</h4><p>Once the new model is created, the next step is to trained the new model and plot the model accuracy and loss. Using similar approach in create base model and new model, a function was made that accepts some parameters like EPOCHS, learning rate, data augmentation, etc. I used two callback available in Keras, in conjunction with the fit method. <strong>ModelCheckpoint </strong>is used to save the model or weights (in a checkpoint file) at some interval, so the model or weights can be loaded later to continue the training from the state saved. The other callback is the <strong>ReduceLROnPlateau </strong>which will reduce the learning rate once the metrics (i.e. accuracy) is no longer improving.</p><pre>def fitandPlot(model, dataAug, trainX, trainY, <br>               testX, testY, EPOCHS = 20, INIT_LR = 1e-1, BS = 64):<br>    <br>    # Learning Rate Reducer<br>    learn_control = ReduceLROnPlateau(<br>                             monitor=&#39;val_accuracy&#39;,<br>                             patience=5,<br>                             verbose=1,factor=0.2, <br>                             min_lr=1e-7)</pre><pre>    # Checkpoint<br>    filepath=&quot;weights.best.hdf5&quot;<br>    checkpoint = ModelCheckpoint(filepath, <br>                                 monitor=&#39;val_accuracy&#39;, <br>                                 verbose=1, <br>                                 save_best_only=True, <br>                                 mode=&#39;max&#39;)<br>    <br>    history = model.fit(<br>    dataAug.flow(trainX, trainY, batch_size=BS),<br>    steps_per_epoch=trainX.shape[0] / BS,<br>    epochs=EPOCHS,<br>    validation_data=(testX, testY),<br>    callbacks=[learn_control, checkpoint])<br>    <br>    plot_history(history)</pre><p>Below is the accuracy and loss curve at epoch set to 10</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZohawtERs24qTaa_N3gIQ.jpeg" /><figcaption>Accuracy and Loss Curve — 800 images</figcaption></figure><p>The model performed well based on the plot and it even score 100% accuracy on the 4th epoch. This could probably because the image are too simple and dataset are not enough. The experiment workflow is repeated 5 times and additional images is added in each repetition. The accuracy and loss curve of the model on the 5th iteration with 2200 images is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*pUo8a7SBAHgo237jV4yaUQ.png" /><figcaption>Accuracy and Loss Curve — 2200 images</figcaption></figure><h4>Grad-Cam</h4><p>Even if the model scored100% accuracy in each iteration, I have to verify the correctness of the model. To visualize and ensure that the model is looking at the correct area of the image, Grad-Cam was performed. Looking the grad-cam images, we can see the the heatmap is perfectly focused the hand gesture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmfoAnJ0VVrw3HHKbV53PQ.png" /><figcaption>Grad Cam Visualization</figcaption></figure><h4>Summary</h4><p>The personally collected hand gesture images might be too simple and dataset is not huge enough that’s why we get 100% accuracy easily on this model. Nevertheless, I have proven that you can utilize a pre-trained model and performed transfer learning technique to solve an image recognition use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cdc0e380854" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>