[Tutorial] Create Restful Web Server using Google "libphonenumber" API

Create Restful Web Server using Google "libphonenumber" API

Brief Introduction:

This is a simple tutorial for creating a Restful web server by using Java. The web server accept a string from URL and return phone numbers which are found in the string by using GET method. It also accept a file and return phone numbers from file by using POST method. All phone numbers will be shown in JSON format.

The final result is shown below:

GET: http://localhost:8080/libnumber/api/phonenumbers/parse/text/Seneca%20Phone%20Number%3A%20416-491-5050

POST: http://localhost:8080/libnumber/api/phonenumbers/parse/file

Here's data in file:


Preparation:

1. Set up Java environment. 
2. Download and install Eclipse Java EE. Click HERE to download the installator and select Java EE when install.
5. Download Google "libphonenumber" API HERE.

Creating a Java project:

1. Open Eclipse, select a workspace wherever you like, click "Launch"
2. File - New - Dynamic Web Project
3. Name the project, 
4. In "Target runtime", select an Apache Tomcat if there is. If the list is empty, you need to config runtime environment. Click "New Runtime" button.

5. Select an Apache Tomcat version which you download, click "Next".


6. Click "Browse" and select your Apache Tomcat package(you need to unzip the package first). Then click "Finish".



7. It shows like below. Click "Next" twice.



8. Check "Generate web.xml deployment descriptor" then click "Finish".


You successfully create a java project!

Import JAX-RS API:

1. Unzip your JAX-RS package you downloaded.
2. Copy all .jar files inside these three folder: "/api", "/ext", "/lib". Paste them to your project. The position is: YourProject/WebContent/WEB-INF/lib.

3. Right click your project name in "Project Explorer" and click "Properties".
4. Select "Java Build Path - Libraries - Add JARs"

5. Select all .jar files in "lib" which you just pasted and click "ok"

6. Click "Apply and Close"

Import "libphonenumber" library:

1. Unzip "libphonenumber" package, go inside "java/libphonenumber" copy the whole "src" folder, paste it in you project under "build" folder:
2. Right click "src" inside "build", select "Build Path - Use as Source Folder".

The Google "libphonenumber" is successfully added to your project!

Writing Core Code:

From now on, you can write code as a normal java project. In "Java Resources/src" create package and class, then you can write your code!

Here is my code example:

package mypackage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.i18n.phonenumbers.AsYouTypeFormatter;
import com.google.i18n.phonenumbers.CountryCodeToRegionCodeMap;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;

import apple.laf.JRSUIConstants.SegmentTrailingSeparator;

@Path("phonenumbers")
public class LibPhoneNumber {
    private static ArrayList<String> phoneNumbers = new ArrayList<String>();
    private PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    
    @GET
    @Path("/parse/text/{i}")
    @Produces(MediaType.APPLICATION_JSON)
    public String libNumber(@PathParam("i") String i) throws Exception {
        return "["+getPhoneNumberFromString(i)+"]";
    }
    
    @POST
    @Path("/parse/file")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String receiveFile(InputStream incomingData) throws Exception {
        String context = "";
        String res = "";
        ArrayList<String> tempContext = new ArrayList<String>();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
            
            String line = null;
            Integer lineNumber = 0;
            while ((line = in.readLine()) != null) {
                tempContext.add(line);
                lineNumber++;
            }
                        
            for(int i = 4 ; i < lineNumber-1 ; i++) {
                context = tempContext.get(i);               
                String ss = getPhoneNumberFromString(context);      
                
                if(ss != null) {
                    res += ss+",";
                }
            }
            
            res = res.substring(0, res.length() - 1);
            res = "["+res+"]";

        } catch (Exception e) {
            System.out.println("Error Parsing: - ");
        }
        return res;
    }
    
    public static String getPhoneNumberFromString(String i) throws Exception{
        String finalNumber = "";
        
        Map<Integer, List<String>> countryCodeToRegionCodeMap =
                CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap();
        for(Integer countryCode : countryCodeToRegionCodeMap.keySet()) {
            finalNumber = parseContact(i, Integer.toString(countryCode));
            if(finalNumber!=null) {
                finalNumber = "\"("+finalNumber+"\"";
                break;
            }
        }
        
     return finalNumber;
    }
        
    public static String parseContact(String contact, String countrycode) {
     PhoneNumber phoneNumber = null;
     PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
     String finalNumber = null;
     String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(countrycode));
     boolean isValid = false;
     PhoneNumberType isMobile = null;
     try {
     phoneNumber = phoneNumberUtil.parse(contact, isoCode);
     isValid = phoneNumberUtil.isValidNumber(phoneNumber);
     isMobile = phoneNumberUtil.getNumberType(phoneNumber);

     } catch (NumberParseException e) {
     e.printStackTrace();
     } catch (NullPointerException e) {
     e.printStackTrace();
     }

     if (isValid
     && (PhoneNumberType.MOBILE == isMobile || PhoneNumberType.FIXED_LINE_OR_MOBILE == isMobile)) {
     finalNumber = phoneNumberUtil.format(phoneNumber,
     PhoneNumberFormat.NATIONAL).substring(1);
     }

     return finalNumber;
    }    
}

*** There will be an error around line 86: 

"CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap();"

What you need is to change "getCountryToRegionCodeMap()" function as public function.


Save all your code.

Deployment:

After finish your code, you need to config web.xml file. Use this code to config:

<servlet>
    <servlet-name>Phone Number Library</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>mypackage</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Phone Number Library</servlet-name>
    <url-pattern>/api/*</url-pattern>
  </servlet-mapping>

 - servlet-name : whatever you like. keep both same in servlet and servlet-mapping.
 - param-value : mypackage.
 - url-pattern : here is to set web server url starting at. 
        For example: http://localhost:8080/libnumber/api/phonenumbers/parse/text/{string}
- http://localhost:8080 : is your server hosting.
- /libnumber : is your web app name, which you named when you create the project.
- /api/ : This is url-pattern you set in web.xml. All the pattern after are designed in you main java code, like: @Path("phonenumbers"), @Path("/parse/text/{i}").


Run: 

To run the project, right click you project name in "Project Explorer", Select "Run as - Run on Server".

Select the Apache Tomcat version you config before. Click "Finish".


Test: 

Test GET and POST by using software "Postman".

GET: 
http://localhost:8080/libnumber/api/phonenumbers/parse/text/Seneca%20Phone%20Number%3A%20416-491-5050

POST: 
http://localhost:8080/libnumber/api/phonenumbers/parse/file
Headers:
Key: Content-Type
Value: multipart/form-data
Body:
Key:file
Value: File you choose.

Test result see "Brief Introduction".










Comments

Popular posts from this blog

OSD - Release 03

OSD600 - Lab 6: Fixing URL bug in Brave browser

Studying for open standard