Monday, May 31, 2021

Consume Rest Service Using GSON jar

I am going to demonstrate how to consume rest API service Using Google Json jar that GSON jar .First you need to down the GSON jar .I am using gson-2.8.6.jar for my demo.

Rest service that i am is hosted at http://localhost:8080/employees .when hit GET request to this in postman or in browser i get response as below.

Response-

{

    "employeeList": [

        {

            "employeeId": "1234",

            "employeeName": "Dhiraj Shigavi",

            "departmentName": "Information technology"

        },

        {

            "employeeId": "7777",

            "employeeName": "John Den",

            "departmentName": "Electronic andtele communication"

        }

    ]

}


To Consume this in java follow below steps.
1. create java project in jdeveloper ( you can user any IDE of your choice).
2.add the GSON jar file downloaded in project properties as below



3. Create java Class and name it ConsumeRestServiceWrapper.java.
4. Now first we need to understand the response and create java equivalent classes of  it so we can parse the response using Gson jar file

In this case my response contains employeeList which is list so i will create a class which contains list object of employeeList ,now type of List object contains employeeId,employeeName,departmentName so will create another class which will have these three names of String object in as below.
So My Employee Class is as below.
 
public class Employee {
    private String employeeId;
    private String employeeName;
    private String departmentName;

    public Employee(String employeeId, String employeeName, String departmentName) {
        this.employeeId = employeeId;
        this.employeeName = employeeName;
        this.departmentName = departmentName;
    }
    public String getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }
    public String getDepartmentName() {
        return departmentName;
    }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
   public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public Employee() {
        super();
    }
}
My EmployeeResponse class will contain List<Employee>  with name employeeList. 
Please note here name has to match with name in your rest response.
import java.util.List;
public class EmployeeResponse {
    List<Employee> employeeList;
    public EmployeeResponse() {
        super();
    }
    public void setEmployeeList(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }
    public List<Employee> getEmployeeList() {
        return employeeList;
    }
}
















Now main part is to write method in service wrapper class which will call the service and populate the data in object of EmployeeResponse class.
I have written getEmployees method which returns me object of EmployeeResponse created above.
Please note below line which populated the String response into Object that we can use in object format

EmployeeResponse employeeResponse = new Gson().fromJson(response.toString(), EmployeeResponse.class);






























package com.service;

import com.google.gson.Gson;
import com.payload.Employee;
import com.payload.EmployeeResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConsumeRestServiceWrapper {
    public ConsumeRestServiceWrapper() {
        super();
    }

    public static void main(String[] args) {
        ConsumeRestServiceWrapper service = new ConsumeRestServiceWrapper();
        try {
            EmployeeResponse response = service.getEmployees();
            if (response != null) {
                if (response.getEmployeeList() != null && response.getEmployeeList().size() > 0) {
                    System.out.println("Employee  list");
                    System.out.println("*****************");
                    for (Employee e : response.getEmployeeList()) {
                        System.out.println("Employee Id-" + e.getEmployeeId());
                        System.out.println("Employee Name-" + e.getEmployeeName());
                        System.out.println("Employee Department-" + e.getDepartmentName());
                        System.out.println("*****************");
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public EmployeeResponse getEmployees() throws Exception {

        URL url = new URL(null, "http://localhost:8080/employees", new sun.net.www.protocol.http.Handler());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");

        int responseCode = conn.getResponseCode();
        System.out.println("URL...: " + url + "  Response Code..: " + responseCode);
        if (responseCode >= 200 && responseCode < 300) {

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = br.readLine()) != null) {
                response.append(line);

            }
            br.close();
            System.out.println("Rest response for employee is -" + response);

            EmployeeResponse employeeResponse = new Gson().fromJson(response.toString(), EmployeeResponse.class);


            return employeeResponse;
        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String line;
            StringBuffer errorResponse = new StringBuffer();

            while ((line = in.readLine()) != null) {
                errorResponse.append(line);
            }
            in.close();
            throw new RuntimeException(conn.getResponseCode() + " Invalid Response " + errorResponse);
        }

    }
}


when i run above class i get response as below















Some of rest service response just contains the list without the name as below

























In this case when you run above code ,you would get exception as com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

so change the line in getEmployees method as below and it will directly populate in List<Employee>

List<Employee> employeeResponse = new Gson().fromJson(response.toString(), List.class);




hope this helps to know how to consume rest API using Gson jar file.

Wednesday, May 26, 2021

ADF dropdown Adjusting width with af:panelFormLayout

In ADF width of af:selectOneChoice is adjusted to fit its content and sometime we dont want that to happen specifically when we use af:panelFormLayout with multiple input components like af:inputText af:selectoneChoice.

In this example i am using below code 











My UI Looks like Below and you can see dropdown is not align with input textbox.










To align this af:selectOneChoice with af:inputText set  contentStyle="width:100%;"  of af:selectOneChoice as shown below






With this your dropdown will be aligned as below



Sunday, May 23, 2021

Call Stored procedure with Array as input parameter from java

Requirement-It is very common requirement to call stored procedure which takes array as input parameter. In below example i am calling the stored procedure from Impl class of application module.

My procedure is having String of array as second parameter.When we want to pass String of array to Stored procedure we need to convert this String of array to Sql array type.For this we need below two things 

  1. The array that we pass should be declared in data as type in database as shown in below CST_LTG_ARRAY_VARCHAR2 is declared as type in database.Same type will be used in stored procedure input parameter as shown in screenshot 2
  2. We need to convert the java.sql.Connection to oracle.jdbc.OracleConnection object as shown in code snippet
Now use this OracleConnection reference to create array reference that we need to pass to stored procedure using below line.Remember minute details here -dont forget to mention schema name dot your type name in database in all uppercase otherwise code will throw java.sql.SQLException: invalid name pattern.


       Array subSetCodesArray = oraConn.createARRAY("EL_EGWH_EXT_WORK.CST_LTG_ARRAY_VARCHAR2", subSetCodes);

Now final step is to pass this subSetCodesArray  array to callableStatement setArray method as below

 statement.setArray(2, subSetCodesArray);


Final method looks like below initializeDataSource is methd used to get connection reference from dataSource in weblogic server.

    public String callApplyClusterStoredProcedure(Long batchNumber, String[] subSetCodes) {


        DBTransactionImpl dbtrx = (DBTransactionImpl) getDBTransaction();

        CallableStatement statement =

            dbtrx.createCallableStatement(("BEGIN " + "SCHEMA_NAME.PROCEDURE_NAME(?,?,?,?);" + "END;"), 0);

        try {

            DataSource ds = initializeDataSource();

            java.sql.Connection conn = ds.getConnection();

            OracleConnection oraConn = conn.unwrap(OracleConnection.class);

            statement.setLong(1, batchNumber);

            if (subSetCodes != null) {

                Array subSetCodesArray = oraConn.createARRAY("EL_EGWH_EXT_WORK.CST_LTG_ARRAY_VARCHAR2", subSetCodes);

                statement.setArray(2, subSetCodesArray);

            } else {

                //use below code to set Null if array is empty or null

                statement.setNull(2, java.sql.Types.ARRAY,"EL_EGWH_EXT_WORK.CST_LTG_ARRAY_VARCHAR2");

            }


            statement.registerOutParameter(3, java.sql

                                                  .Types

                                                  .VARCHAR);

            statement.registerOutParameter(4, java.sql

                                                  .Types

                                                  .VARCHAR);

            statement.execute();

            //Long balanceToInclude = statement.getLong(4);

            String result = statement.getString(3);

            String message = statement.getString(4);

            System.out.println("result -" + result);

            System.out.println("message-" + message);

            return result;

        } catch (SQLException sqlerr) {

            throw new JboException(sqlerr.getMessage());

        } finally {

            try {

                if (statement != null) {

                    statement.close();

                }

            } catch (SQLException closeerr) {

                throw new JboException(closeerr.getMessage());

            }

        }

    }


    private DataSource initializeDataSource() {

        InitialContext ctxt = null;

        DataSource dataSource = null;

        try {

            ctxt = new InitialContext();

            dataSource = (DataSource) ctxt.lookup("jdbc/EgwhDS");

            ctxt.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

        return dataSource;

    }

Thursday, May 20, 2021

ADF view object with bind parameter and like operator .

 Requirement:

In this post i am explaining how to create ADF view object with like operator and bind parameter in where clause. requirement is very simple get all rows from employee table with employee containing runtime value entered by user.


In this case while we create new object in Jdeveloper give query as below

Query here is -


select EMPLOYEE_NAME,EMPLOYEE_ID from EMPLOYEE 

where  ( (UPPER(EMPLOYEE_NAME) LIKE UPPER('%' || :pEmployeeName || '%') )
















In the next screen give bind parameter pEmployeeName of type string as below














After this pass the bind parameter from UI as user entered value .Hope this helps