Labels

Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Thursday, December 6, 2018

Authenticate Non-Fusion Application via the Oracle Fusion Cloud


Hi Folks,

Today, I’ll explain you to implement authentication mechanism to Non-Fusion application through the Oracle Fusion cloud.  Basically my business flow is, user should log into Oracle Fusion cloud first and then access to Non-Fusion application through the external URL available in Fusion Springboard or Navigator.

Following diagram depicted the authentication flow, I’ll explain each process flows, it will easy to understand the authentication process.

Authentication Flow

Fusion user to Application Session Bean

First user should log into the Oracle Fusion cloud. Then the user click the icon on Oracle fusion springboard/Navigator. Oracle Fusion provide JWT (JSON Web Token) to identify logged user uniquely, we should have implement a mechanism to pass the generated JWT key as an URL parameter to Non-Oracle application. For generate JWT, we can use simple expression language like this.

https://<Non-Fusion Application URL>?jwtparam= #{applCoreSecuredToken.trustToken}  

JSON Web Token validation 
   
This step bit tricky, because we have mechanism to avoid misusage of JWT key. Each time user click the URL, oracle generate JWT on demand. This key has 4hrs lifetime within this time period user can use generated JWT key multiple times. For avoid that, we can implement validation to allow fresh JWT each time by looking JWT generated time.
To get JWT generated time, you can simply decode JWT header using standard library provide by jwt.io web. Here’s the implementation of validation method.  



Validate the Logged User

Now we have Oracle generated JWT, but we are unable to decode verify signature for identified user details directly. So we need to use SOAP service for get the logged user details. In hcmService/UserDetailsServiceV2 request we can pass the JWT as Authorization Header along with Bearer keyword.

In above mentioned flow, I used internal user details stored data base to verify against fusion result. But it’s not mandatory.

Happy Coding,

Regards,
Denuwan Himanga Hettiarachchi

Saturday, November 17, 2018

Switching between Default mood to Accessibility mode, without additional clicks in Oracle ADF Application


Hi Folks,

This post onward, I’ll publish my technical articles in both Medium & Blogger accounts. I believe this option allow me to reach new technical enthusiasm audience.

Few months back, I have opportunity to allocate really interesting task. In my organization we have a requirement to allow our Time Entry application to the visual impact users. According to W3.org accessibility mean,

Accessibility addresses discriminatory aspects related to equivalent user experience for people with disabilities, including people with age-related impairments. For the web, accessibility means that people with disabilities can perceive, understand, navigate, and interact with websites and tools, and that they can contribute equally without barriers. For more information, see the Accessibility introduction.

In this post I’m not going to explain the way to modification you should do to achieve accessibility in Oracle ADF application. Oracle provide advanced documentation for develop application with the aim of accessibility feature. “Fusion Middleware Web User Interface Developer's Guide for OracleApplication Development Framework” this should be your bible.

But, the way documentation suggest to switch in between accessible mode and default mode is really painful. So I come up with a totally new solution to switching these modes.

If you already refereed Oracle documentation (I highly recommend you to go through it, before try to understand my solution) you have idea about the importance of trinidad-config.xml file. In order to switch application to different modes we should add screenReader/default values to accessibility-mode property.

But we have to configure above mentioned values permanently or we need to provide additional pop-up to choose accessibility preferences and based on the value we should fully refresh web application in each time user login to the system.

Stored a permanent value is not an elegant design, Couse this will ruin ordinary users experience. Providing an additional pop-up also damage minimum click approach in web design world.

Option I

I have two solutions to avoid, above mentioned design problems. In my scenario we have pre known user based, so I created a new attribute in USER_DETAILS table and store accessibility_mode based on user preferences.

But how to change accessibility-mode property in trinidad-config.xml,

Kudos to Session Bean objects, we can simply create a variable in Session Bean scope and assign to accessibility-mode property in trinidad-config.xml. Final solution should be like this.

Option II

Option I, sort of a mediocre solution. Because we need to pre-identified our user’s accessibility preferences. Option II come up with an innovative way, but you have to log Oracle Fusion Cloud first and navigate to your application through Fusion Cloud.

In my organization Time Entry application host as a Non-Fusion application, but authentication through the Fusion Cloud (I’ll write a separate post to describe authentication process).

If I simply explain the authentication process. When you’re Non-Fusion application load, you can generate JSON Web Token (JWT) and pass it as a URL parameter. Oracle HCM Cloud provide SOAP web services to get user details, by passing JWT as an Authorization Header simply call findSelfUserDetails SOAP service to get a AccessibilityMode value. 

Same as the Option I, you can execute the above process inside the Session bean scope and assign SOAP result to accessibilityMode variable.

Hope you got a clear idea about these two options, please feel free to comment your questions.

Happy Coding!

Regards,
Denuwan Hettiarachchi

Sunday, April 2, 2017

Implementing SharePoint Online REST client on JAVA platform.

Hi folks,

SharePoint 2013 hosts a Representational State Transfer (REST) service. Using REST API, Developers can interact remotely with SharePoint data by using any technology that supports REST web requests.

SharePoint Online (SPO) REST client request should need to authorize. SharePoint Online Single Sign On (SSO) process validate the REST call and establish connection between SPO and REST client.

In order to establish connection between SPO and REST client, needs to provide following authentication values.

1) rtFa Cookies
2) FedAuth Cookies
3) FormDigestValue

In this post, I’ll demonstrate only implementing a JAVA based RESTful client part and way of passing the above mention authentication values as headers in RESTful call. How to generate the auth values explained in this post. We can simply use generated auth values using POSTMAN case, these values never expire and platform independent.



Happy Coding....

Regards,
Denuwan Himanga

Friday, March 31, 2017

Generate SharePoint Online Rest API Authentications Details Using POSTMAN

Hi folks,
Today, SharePoint Online is the most preferred cloud based platform in many of the organizations to collaborate with external and internal parties, with organizing documents and access the information from any time anywhere.
SharePoint 2013 hosts a Representational State Transfer (REST) service. Using REST API, Developers can interact remotely with SharePoint data by using any technology that supports REST web requests.
In order to communicate SharePoint online REST services you needs to have following authentications keys.

1) BinarySecurityToken
2) rtFa & FedAuth Cookies
3) FormDigestValue 


In this post, I’ll demonstrate how to generate SharePoint Online Rest API authentications keys using Google chrome POSTMAN App.

Generate BinarySecurityToken

In order to get BinarySecurityToken, needs to use Microsoft Security Token Service put above mentioned address as the URL


Needs to add following XML Envelope as a message body, replace [username], [password] & [yourdomain] as per your environment.



When you go through the respond from STS Service, you should notice two main tags among respond envelope. Those are <wst:Lifetime> & <wst:RequestedSecurityToken>. Within RequestedSecurityToken tag we can identify the BinarySecurityToken, which we try to generate in this step, but make sure to follow the second step before the time period within <wst:Lifetime> token. Cause BinarySecurityToken is time based temporary key.   

Generate rtFa & FedAuth Cookies

Now, we need to POST generated BinarySecurityToken to SharePoint Online, if it is valid token SharePoint Online single sign on processes responding with two authentication cookies called rtFa & FedAuth.

In order to get the cookies, you need to enable POSTMAN interceptor. It’s allow to send requests which use browser’s cookies through POSTMAN.

https://[YourDomain].sharepoint.com/_forms/default.aspx?wa=wsignin1.0

Postman : Important sections are Highlighted


Generate FormDigestValue

Form digest value use as a credential validation key in SharePoint architecture. REST API call run inside the firewall, so REST calls are authenticated using the current user's credentials and they can get the form digest value.


Following values should declare as a headers in POSTMAN.
Cookie: rtFa=[rtFa]
Cookie: FedAuth=[ FedAuth]
Origin: [YourDomain].sharepoint.com




REST Call Demo

Using generated authentication values, we can simply test GET request. You need to replace following request as per your environment. Needs to add FormDigestValue as X-RequestDigest in header alone with above mentioned headers in Generate FormDigestValue step.

Additionally, I add optional header which format response as a JSON object.
Accept:application/json;odata=verbose



Happy Coding.
Regards,
Denuwan Himanga

Sunday, October 23, 2016

Customize Databound Fixed List of Values in Oracle ADF


Hi folks,

Oracle ADF is a one of the most advanced framework use by many of companies nowadays. It will allow developers to build an MVC architecture based applications, basically ADF make developer life essayer than any other framework existing in today.

This post for developers who has basic knowledge with ADF.

Creating a fixed list dropdown, usually used for some static values. Let’s assume that we have a requirement of the selecting two type of age ranges for some app. 45> allowed and 45< not allowed, in DB side these operation handle by the Boolean type variable. 45> true and 45< false.

When we are checking the documentations of Oracle ADF, the recommended way is using a databound fixedlist,


But it will be a mess, when we need to customize the display value and DB item value, because we need to mention the exact same list which include in DB side, If we consider the scenario like above mentioned, we can’t use different value and label like this,

1:  <af:selectOneChoice value="#{bindings.Userstatus.inputValue}"  
2:            label="#{bindings.Userstatus.label}: ">  
3:   <f:selectItems value="#{bindings.Userstatus.items}" itemLabel="#{bindings.Userstatus.items == true ? Above 45 : Bellow 45}"/>  
4:  </af:selectOneChoice>  

Because it doesn’t allow to customize with different itemLabel and value, this drop down always display true and false instead of “Above 45” and “Bellow 45”.

In order to solve that, we can create a programmatic fixed list, this approach allows you to customize value and label according to our requirement.

According to SelectItem documentation, six (6) override constructors allow us to define following parameters,


  •          java.lang.Object value
  •          java.lang.String label
  •          java.lang.String description
  •          boolean disabled
  •          boolean escape

We can define fixed list in bean class and, simply customize dropdown value list.

1:  List<SelectItem> userStatus;  
2:    public void setUserStatus(List<SelectItem> userStatus) {  
3:      this.userStatus = userStatus;  
4:    }  
5:    public List<SelectItem> getUserStatus() {  
6:            if (userStatus == null) {  
7:        userStatus = new ArrayList<SelectItem>();  
8:        userStatus.add(new SelectItem(true,"Above 45"));  
9:        userStatus.add(new SelectItem(false,"Bellow 45"));  
10:            }  
11:      return userStatus;  
12:    }  
MyBean.java

1:  <af:selectOneChoice value="#{bindings.Userstatus.inputValue}"  
2:            label="#{bindings.Userstatus.label}: ">  
3:   <f:selectItems value="#{MyBean.userStatus}" />  
4:  </af:selectOneChoice>  

Happy Coding,

Regards,
Denuwan Himanga


Monday, April 18, 2016

JAVA Interface Implementation

Hi folks,

In this post, I decide to cover little bit confused area in programming, most of the candidates are little bit straggle in when they faced a job interview. On OOP inheritance concept depend on these two methodologies. I explained OOP & Abstract concept, in the previous post. Today I’m figuring out major differentiations between Interfaces & Abstract concepts.


Basically Interfaces & Abstract class are looks like same, when most of the programmers deal with those both methodologies in very first time. But the reality is these two techniques are introduced for the two different things. As well as in a very complex scenario, we must identify which technique implements in to the system. Otherwise, most probably we face difficulties in developing/maintaining stages in SDLC.   


Use Case Diagram

Ok, let’s try to implement above scenario, for the implementation process I use to unique features of the interface. Following list listed down those features. 

1.                  Interface variables are by default Constant.
2.                  The interface allows only method signatures / doesn’t allow method body (Above JAVA 8)
3.                  The interface allows to implement multiple interfaces.
4.                  Interface, Interface implementation can use extends keyword
5.                  Class, Interface implementation can using implements keyword
6.                  An interface can extend multiple interfaces.

Following code segments depict how Mobile Phone class extending using interface wise implementation. For the demonstration I used highlighted segment in above UML diagram. Try to implement whole scenario by yourself.  

package com.interfaces;

public interface Secondary {
    
    public double MEGA_PIXELS = 13;
    public int Resolution = 1080;
   
}
Secondary.java
package com.interfaces;

public interface Primary {
    
    public double MEGA_PIXELS = 13;
    public double FLASH_RANGE = 4;
    public int [] SENSITIVITY = { 100, 200, 400, 800, 1600 };
    public double ZOOM = 3;
    
    public boolean zoomLence(int zoomRange);
    
    public void onFlash();
    
    public void offFlash();
    
    public void autoFocus();
    
    public int changeSensitivity(int Sensitivity);
}
Primary.java

package com.interfaces;

public interface Display {
    
    public String TYPE = "CAPACITIVE TOUCHSCREEN, 16M COLORS";
    public double SIZE = 5.0;
    public int[] RESOLUTION = {720 , 1280};
    
    public boolean multiTouch();
    
    public boolean turnOnDisplay();
    
    public boolean turnOffDisplay();
    
}
Display.java
package com.interfaces;

public interface Camera extends Primary, Secondary{
    
    public String FILE_FORMAT = ".jpeg";
    
    public boolean saveFile(String fileName);
    
    public boolean capture();

}
Camera.java
package com.application;

import com.interfaces.Camera;
import com.interfaces.Display;

public class MobilePhone implements Camera, Display{
    
    private String brandName;
    private int year;
    private String price;
    
    @Override
    public boolean zoomLence(int zoomRange){
        return true;
    }
    
    @Override
    public boolean saveFile(String fileName){
        return true;
    }
    
    @Override
    public void onFlash(){
    }
    
    @Override
    public void offFlash(){
    }
    
    @Override
    public int changeSensitivity(int Sensitivity){
        return 0;
    }
    
    @Override
    public boolean turnOnDisplay(){
        return true;
    }
    
    @Override
    public boolean multiTouch(){
        return true;
    }
    
    @Override
    public boolean turnOffDisplay(){
        return true;
    }
    
    @Override
    public boolean capture(){
        return true;
    }
    
    @Override
    public void autoFocus(){
    }    
}
MobilePhone.java
Additionally, JAVA 8 allow to implement method body inside interface, it looks like the evolution of Interface concept. Following example, I explained how to implement a method body in the interface. Using default & static key word we can implement a method body inside an interface scoop. Also override a default method is not a mandatory, but two interfaces, content same name compiler doesn’t identify which method belongs to which interface. So mitigate demanding issues if there any method to contain the same method signature in two different interfaces, overriding is mandatory. But method which are implements using the static key word can’t override in any concern.
 interface Java8Interface {  
   static void playCaptureSound(){  
     System.out.println("Click !!!");  
   }  
   default void formatMemory(){  
     //Do stuff here;  
   }  
 }  


Happy coding,
Regards,
Denuwan Himanaga

Monday, March 21, 2016

String vs. StringBuffer/StringBulider

Hi all,

In this post, I’ll demonstrate how memory behave while string type data involving scenario in our JAVA program. Basically, when we execute JAVA program on our PC, Java mange PCs main memory in its own way. For string type operations are handled through following 3type of memory segments.
  • Stack
  • Heap
  • Pool






String data type is immutable, mean when changes happen to literals particular literals never change, instead of that reference variable pointed to new value. This behavior helps to manage literals which have more than one reference.

When we consider above scenario, step 1 to 4 nameList variable reference to new literals in each step of the loop, at the same time previous values of literals are reaming inside the pool without any references, instead of JAVA garbage collector involving to clear pool, String pool will be full of garbage value.

For mitigate these kind of scenario JAVA 5 introduces StringBuffer & StringBulider both of the classes are not immutable. Let’s see how to implement above code segment using StringBuffer class.


Happy Coding,
Regards,
Denuwan Himanga

Saturday, March 12, 2016

Solution for Apache POI Date format Issue

Hi folks,

Today I’m here with some tricky solution, if you are familiar with Apache POI you might be facing this problem before. I’ll explain in fundamental level.

What is Apache POI

POI is the one of the common open source libraries introduced by Apache for interact (Inserting/Deleting/Reading) with applications in MS office package. Using POI library, we can easily create an interconnection with MS office application and our JAVA app.  

But most of the time, Apache POI doesn’t support for large Excel files. Because of that, most of developers are useing another third partition library call Streaming Reader for filtering specified excel sheets from large excel file.  But when we use this library some time reader doesn’t identify the exact cell type in excel file. Most of the time the cells, which we change the cell type as Date, Streaming reader, read this cell without any exception, but then we can notice, it displays a totally different number when we compare with exact value in the Excel cell.

Actually the reality is Streaming reader little bit intelligent than our eye, usually excel assign some formulated value for each date formatted cell for their calculation purpose. So what happens is streaming reader read that value instead of actual displayed value in excel cell.  

The reading value is not a random value, 01/Jan/1900 excel numbering as 01. So using a small conversion method we can easily convert these numbers in to actual date.

Here's the code, or you can simply use Convert Serial To Date library for that conversion process,


Regards, 
Denuwan Himanga

Monday, July 13, 2015

Concepts Behind Abstract & Inheritance in Object Oriented Programming



Hi guys,

In this post I’ll decide to cover two basic concepts behind OOP. Object oriented programing concepts memorizing or hard coding is impractical, because OOP is the pure conceptual thing. If you need to geek of this area you should try to understand this concept rather than memorizing. I’ll go through the OOP design pattern based on Abstract & Inheritance concepts. Following a practical approach will be lead to better understanding of above two concepts. Today's post I’ll organize in two different approaches, first I’ll explain the OOP concepts with an aid of in real world scenarios and then I’ll implement explained concept using JAVA technical aspect. Ok, let’s start our OO journey with JAVA. 




Real world scenario - 

When we depict above diagram, every human being in the world owns above 4 properties which is listed under person. But when we want to categorize every human being in the whole world under person category it will be a disaster, because 7 billion humans in the world can be put into person category. In order to introduce well organized approach as well as a resource utilization approach, we can categorize persons into two major categories. Female & Male, now see above approach how to lead to well-organized resource utilization approach. I’m highlighting in the beginning of this paragraph, every human beings own 4 properties in their life. These four properties didn’t depend on the gender. In order to maintain well-organized approach we divide persons into two categories, but still we listed above properties under person category. We reuse listed properties rather than duplicating. We divide the whole world into two categories, but still we listed common features under person category. Now we can put the whole world into female & male category, but still we maintain person category for listed common features of females & males.

Technical approach – 

Now I’m instructing to how to implement the technical approach of the above real world scenario using JAVA, This three category implementing as three different Classes, But in order to implement this scenario, according to OO concepts, we will use Inheritance for avoiding duplicating resources also maintain the well-organized approach. Let’s see how we utilize resources, I’ll implement person class and include all common properties in the person class. Additionally, I’ll implement female & male classes for maintaining well-organized approach. 


public class person {
  
    private String name;
    private int age;
    private genderType gender;
    private Date birthDay;

    public person(String name, int age, genderType gender, Date birthDay) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.birthDay = birthDay;
    }
}

public class female extends person{

    public female(String name, int age, genderType gender, Date birthDay) {
        super(name, age, gender, birthDay);
    }
}

public class male extends person{

  
    public male(String name, int age, genderType gender, Date birthDay) {
        super(name, age, gender, birthDay);
    }
}

enum – If you want to implement user defined data type like ‘genderType’, you can easily add an enum and define data within curly brackets and using when we want. But you can’t assign user defined data type data just like a standard data type. You should assign values like this,
<Defined Data type>.< Data> 
Ex: genderType.female


enum genderType{
      
        Female,
        Male
    }

Real world scenario –

Now we will listed what are the specified features and common features of female and male lives. Following table explain about that. You can see the study level of each person didn’t depend on the gender, but when we consider marital status of each person it will be depend on gender. 




Technical approach – 

When illustrate the real world scenario, you can see a ‘Marital Status’ is depend on the gender type, I mean marital status, we can categorize as a common feature of both male & female. But when we using that usually both married an unmarried male as a “Mr.” and married female as a “Mrs.” & Unmarried female as “Miss.” So you can see these common features how to depend on gender. What I want to do is, I will define a method in person class and, method, body defined in both female and male classes according to changes.


public abstract String getMaritalStatus(boolean status); 

public String getMaritalStatus(boolean status)
    {
        if(status)
            return "Miss";
        else
            return "Mrs.";
    }

public String getMaritalStatus(boolean status)
    {
        return "Mr.";
    }

Real world scenario –

Now we will categorize 3 persons into these three categories, I’ll put the mark these real world data represented category. You can see each real world data can be put into female or male category, because of this reason person category is empty.


 

Technical approach – 

Let’s implement the JAVA technical approach, according to real world scenarios, according to above table you can see any real world data can’t categorize as person, but still common features listed under person class. What I am going to change is, I’ll change person class as the Abstract class, my target maintains person class as a super class and as well as a method of resource utilization but never create any of the object of it.


public abstract class person{ //rest of the class }

Method overriding – This is another important feature in OO programing, But here I’ll not go into that much detail about this. I will just quickly go through it, when we implement any of the class we can see by default methods automatically generated for us, in the class. ToString (), compareTo (), Equals () are the common method which we can see when we disassemble the code using Java. We can override those methods according to our requirements. Following example, I’ll override auto generated method inside the person class. Additionally, when we want to override compareTo () method we need to implant comparable interface inside the class. You can simply implement needed interfaces after the class name as you wish.      
Another thing is, when we want to compare different properties we can’t override the same comparator () method in the same class. We can use separate class and implement the comparator interface in JAVA and simply override the compare () method according to our requirements.


public abstract class person implements Comparable<person>

//rest of the class
@Override
    public int compareTo(person t) {
       
        if(t.name.compareTo(name) == 1)
        {
            return -1;
        }else
        {
            if(t.name.compareTo(name) == -1)
            {
                return 1;
            }else
            {
                return 0;
            }
        }
    } 

}

@Override
    public String toString() {
        return "person{" + "name=" + name + ", age=" + age + ", gender=" + gender + ", birthDay=" + birthDay + '}';
    }

@Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final person other = (person) obj;
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return true;
    }

import java.util.Comparator;
public class compareByAge implements Comparator<person>{

    @Override
    public int compare(person t, person t1) {
       
        if(t.getAge() > t1.getAge())
        {
            return 1;
        }else
        {
            if(t.getAge() < t1.getAge())
            {
                return -1;
            }else
            {
                return 0;
            }
        }
    }  
   
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class RealWorldApplication {

    public static String sortByName(List<person> personList)
    {
      Collections.sort(personList);
      return "Sort by name";
    } 
   
    public static String sortByAge(List<person> personList)
    {
      Collections.sort(personList,new compareByAge());
      return "Sort by age";
    }
   
    public static void displayPersons(List<person> personList)
    {
        for(person tempPerson : personList)
        {
            System.out.println(tempPerson);
        }
    }
   
    public static void main(String[] args) {
       
        Scanner Scan = new Scanner(System.in);
               
        List humanList = new ArrayList<person>();
       
        humanList.add( new male("Saman Ranpitiya", 25, genderType.Male, null));
        humanList.add( new male("Nuwan Kumara", 30, genderType.Male, null));
        humanList.add( new female("Kumari Silva", 20, genderType.Female, null));
       
        boolean status = true;
       
        do
        {
            System.out.println("Enter your choise >> ");
            int option = Scan.nextInt();
           
            switch(option)
            {
                case 1 : displayPersons(humanList);
                    break;
                case 2 : sortByAge(humanList);
                    break;
                case 3 : sortByName(humanList);
                    break;
                case 4 : status = false;
                   
            }
           
        }while(status);
     
    }
}

Happy Coding.....

Regards,
Denuwan Himanga.