Open In App

Spring MVC – Get Probability of a Gender by Providing a Name using REST API

Last Updated : 18 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A lot of funful REST API calls are available as open source. Suppose if we like to keep a name to our nears and dears, we can just check that by means of a REST API call and get the gender, what is the probability of being that gender and how many times does it come with it? Relevant REST API call

https://api.genderize.io?name=<Provide your desired name here>

Example:

https://api.genderize.io?name=rachel

Resultant JSON Output:

Resultant JSON Output

 

Let us get these details by using the Spring MVC project which accesses the REST API call and gets the JSON response and parses the data and produces the output in the way we want. Let us check out the JUNIT test case as well. We are going to use the “org.springframework.test.web.servlet.MockMvc” for that.

Implementation

Project Structure:

Project Structure

 

This is a maven-driven project. 

pom.xml

XML




    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                        http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.findGender.findGender_Rest_API</groupId>
    <artifactId>genderFind_Rest_API</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>profileGenerator</name>
    <url>http://maven.apache.org</url>
    <properties>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <spring-version>5.1.0.RELEASE</spring-version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-version}</version>
        </dependency>
  
        <!-- JSTL Dependency -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
  
        <!-- Servlet Dependency -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
  
        <!-- JSP Dependency -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>GenderFinding</finalName>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <!-- This should be added to overcome Could not initialize 
                 class org.apache.maven.plugin.war.util.WebappStructureSerializer -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</version>
            </plugin>
        </plugins>
    </build>
</project>


Let us start by seeing the JSP file which sends the name to the controller file which accesses the REST API call and gets the details, parse, and render them on the screen.

findGender.jsp

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Finding Gender</title>
    <style type="text/css">
        .main-form, .profile-area {
            width: 500px;
        }
        .main-form {
            margin: 50px auto 0px;
        }
        .profile-area {
            margin: 10px auto;
        }
        .main-form section, .profile-area section {
            margin-bottom: 15px;
            background: #33FF7A;
            box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
        }
        .main-form section {
            padding: 30px;
        }
        .profile-area section {
            padding: 30px 30px 30px;
        }
        .profile-area section > div {
            text-align: center;
        }
        .main-form h3 {
            margin: 0 0 15px;
        }
        .form-control, .btn {
            min-height: 38px;
            border-radius: 2px;
        }
        .btn {
            font-size: 15px;
            font-weight: bold;
        }
        .hideElement {
            display: none;
        }
    </style>
</head>
<body>
<div class="main-form" id="main-form">
    <section>
        <h5 class="text-center">Enter a name to find Gender</h5>
        <div class="form-group">
            <input id="genderName" type="text" class="form-control" placeholder="Enter a name to find Gender..." required="required">
        </div>
        <div class="form-group">
            <button onclick="loadData()" class="btn btn-primary btn-block">Find Gender Details</button>
        </div>
    </section>
</div>
<div class="profile-area hideElement" id="profile-area">
    <section>
        <div id="loader" class="hideElement">
            <div class="spinner-border" role="status">
                <span class="sr-only">Loading...</span>
            </div>
        </div>
        <div id="profile" class="hideElement">
            <br><br>
              
<p><strong>Entered Name : <span id="name"></span></strong></p>
  
              
<p><strong>Gender : <span id="gender"></span></strong></p>
  
              
<p><strong>Probability : <span id="probability"></span></strong></p>
  
              
<p><strong>Count : <span id="count"></span></strong></p>
  
        </div>
    </section>
</div>
</body>
<script>
    function loadData() {
        document.getElementById("profile-area").classList.remove("hideElement");
        document.getElementById("loader").classList.remove("hideElement");
        document.getElementById("profile").classList.add("hideElement");
  
        var genderName = document.getElementById("genderName").value;
  
        var otherCurrency1,otherCurrency2;
        if(genderName != "" && genderName != null) {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    var jsonResponse = JSON.parse(this.responseText);
                    document.getElementById("name").innerHTML = jsonResponse.name;
                    document.getElementById("gender").innerHTML = jsonResponse.gender;
                    document.getElementById("probability").innerHTML = jsonResponse.probability;
                    document.getElementById("count").innerHTML = jsonResponse.count;
  
                    document.getElementById("loader").classList.add("hideElement");
                    document.getElementById("profile").classList.remove("hideElement");
                }
            };
            xhttp.open("GET", "getGenderDetails?genderName=" + genderName, true);
            xhttp.send();
            console.log("done");
        } else {
            console.log("Enter genderName...")
        }
    }
</script>
</html>


On execution of the file, we will get this

Output:

HTML UI Output

 

Testcase 1:

Testcase 1

 

Let us test whether the rendered output is correct or not by doing a call to the program and MockMVC. Let us see the java file for that.

FindingGenderControllerTest.java

Java




import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
  
import com.findGender.findGender_Rest_API.controller.FindingGenderController;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.StringTokenizer;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.StringUtils;
  
public class FindingGenderControllerTest {
    private MockMvc mockMvc;
  
    @Before public void setup()
    {
        this.mockMvc
            = MockMvcBuilders
                  .standaloneSetup(
                      new FindingGenderController())
                  .build();
    }
  
    @Test
    public void testGenderFindingDetails() throws Exception
    {
        // expected
        String expectedData = null;
        StringBuilder responseData = new StringBuilder();
        JsonObject expectedJsonObject = null;
        JsonArray expectedJsonArray = null;
        String expectedName = null, expectedGender = null,
               expectedProbability = null,
               expectedCount = null;
        // Let us call this REST API call and get the output
        URL url = new URL(
            "https://api.genderize.io?name=rachel");
        HttpURLConnection con
            = (HttpURLConnection)url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        try (BufferedReader in
             = new BufferedReader(new InputStreamReader(
                 con.getInputStream()))) {
  
            String line;
  
            while ((line = in.readLine()) != null) {
                responseData.append(line);
            }
  
            expectedJsonObject = new Gson().fromJson(
                responseData.toString(), JsonObject.class);
            expectedData
                = expectedJsonObject.toString().replaceAll(
                    "^\"|\"$", "");
            StringTokenizer jsonTokenizer
                = new StringTokenizer(expectedData, ",");
            String internalData[];
            String expectedGenderFindingOutput = null;
  
            while (jsonTokenizer.hasMoreTokens()) {
                expectedGenderFindingOutput
                    = jsonTokenizer.nextToken();
                internalData = StringUtils.split(
                    expectedGenderFindingOutput, ":");
                if (internalData[0]
                        .substring(
                            2, internalData[0].length() - 1)
                        .equalsIgnoreCase("name")) {
                    expectedName
                        = internalData[1].substring(
                            1,
                            internalData[1].length() - 1);
                }
                if (internalData[0]
                        .substring(
                            1, internalData[0].length() - 1)
                        .equalsIgnoreCase("gender")) {
                    expectedGender
                        = internalData[1].substring(
                            1,
                            internalData[1].length() - 1);
                }
                if (internalData[0]
                        .substring(
                            1, internalData[0].length() - 1)
                        .equalsIgnoreCase("probability")) {
                    expectedProbability = internalData[1];
                }
                if (internalData[0]
                        .substring(
                            1, internalData[0].length() - 1)
                        .equalsIgnoreCase("count")) {
                    expectedCount
                        = internalData[1].substring(
                            0,
                            internalData[1].length() - 1);
                }
            }
            // After parsing the JSON response,
            // all the details are available in
            // expectedName, expectedGender,
            // expectedProbability and expectedCount
            // variables
            System.out.println(expectedName + expectedGender
                               + expectedProbability
                               + expectedCount);
        }
  
        // actual
        // Using MockMVC, we need to call
        // /getGenderDetails?genderName=rachel
        MvcResult result
            = mockMvc
                  .perform(get(
                      "/getGenderDetails?genderName=rachel"))
                  .andReturn();
        String recievedResponse
            = result.getResponse().getContentAsString();
        JsonObject actualJsonObject = new Gson().fromJson(
            recievedResponse, JsonObject.class);
        String actualName
            = actualJsonObject.get("name").toString();
        actualName = actualName.replaceAll("^\"|\"$", "");
        String actualGender
            = actualJsonObject.get("gender").toString();
        actualGender
            = actualGender.replaceAll("^\"|\"$", "");
        String actualProbability
            = actualJsonObject.get("probability")
                  .toString();
        actualProbability
            = actualProbability.replaceAll("^\"|\"$", "");
        String actualCount
            = actualJsonObject.get("count").toString();
        actualCount = actualCount.replaceAll("^\"|\"$", "");
        // We need to store parsed JSON result into
        // actualName, actualGender, actualProbability and
        // actualCount Using assertEquals let us compare the
        // values
        // We should get positive result for all the 4
        // different values
        assertEquals(expectedName, actualName);
        assertEquals(expectedGender, actualGender);
        assertEquals(expectedProbability,
                     actualProbability);
        assertEquals(expectedCount, actualCount);
    }
}


On running the file as JUNIT Test

JUNIT Test

 

JUNIT Test

 

Now it is time to see important Java code.

Testcase 2:

 

AppConfig.java

Java




import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
  
@Configuration
@EnableWebMvc
@ComponentScan(basePackages
               = { "com.findGender.findGender_Rest_API" })
public class AppConfig {
    @Bean public InternalResourceViewResolver resolver()
    {
        InternalResourceViewResolver resolver
            = new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}


SpringMvcDispatcherServletInitializer.java

Java




import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  
public class SpringMvcDispatcherServletInitializer 
      extends AbstractAnnotationConfigDispatcherServletInitializer {
   
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }
   
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { AppConfig.class };
    }
   
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
   
}


FindingGenderController.java

Java




import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
  
@Controller
public class FindingGenderController {
  
    @RequestMapping("/getGenderDetails")
    public @ResponseBody
    JsonObject getGenderDetails(String genderName)
        throws IOException
    {
  
        JsonObject jsonObject = new JsonObject();
        jsonObject = findGender(genderName);
        String data = jsonObject.toString();
        data = data.replaceAll("^\"|\"$", "");
        StringTokenizer jsonTokenizer
            = new StringTokenizer(data, ",");
        String internalData[];
        String expectedGenderFindingOutput = null;
        while (jsonTokenizer.hasMoreTokens()) {
            expectedGenderFindingOutput
                = jsonTokenizer.nextToken();
            internalData = StringUtils.split(
                expectedGenderFindingOutput, ":");
            System.out.println(internalData[0]
                               + internalData[1]);
            if (internalData[0]
                    .substring(2,
                               internalData[0].length() - 1)
                    .equalsIgnoreCase("name")) {
                jsonObject.addProperty(
                    "name",
                    internalData[1].substring(
                        1, internalData[1].length() - 1));
            }
            if (internalData[0]
                    .substring(1,
                               internalData[0].length() - 1)
                    .equalsIgnoreCase("gender")) {
                jsonObject.addProperty(
                    "gender",
                    internalData[1].substring(
                        1, internalData[1].length() - 1));
            }
            if (internalData[0]
                    .substring(1,
                               internalData[0].length() - 1)
                    .equalsIgnoreCase("probability")) {
                jsonObject.addProperty("probability",
                                       internalData[1]);
            }
            if (internalData[0]
                    .substring(1,
                               internalData[0].length() - 1)
                    .equalsIgnoreCase("count")) {
                jsonObject.addProperty(
                    "count",
                    internalData[1].substring(
                        0, internalData[1].length() - 1));
            }
        }
  
        jsonObject.addProperty("data", data);
  
        return jsonObject;
    }
  
    private JsonObject findGender(String genderName)
        throws IOException
    {
  
        String data = null;
        StringBuilder responseData = new StringBuilder();
        JsonObject jsonObject = null;
  
        URL url = null;
  
        url = new URL("https://api.genderize.io?name="
                      + genderName);
  
        HttpURLConnection con
            = (HttpURLConnection)url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = con.getResponseCode();
  
        System.out.println(
            "\nSending 'GET' request to URL : " + url);
        // System.out.println("Response Code : " + responseCode);
  
        try (BufferedReader in
             = new BufferedReader(new InputStreamReader(
                 con.getInputStream()))) {
  
            String line;
  
            while ((line = in.readLine()) != null) {
                responseData.append(line);
            }
  
            jsonObject = new Gson().fromJson(
                responseData.toString(), JsonObject.class);
        }
        // System.out.println(data);
        return jsonObject;
    }
}




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads