Sunday, February 5, 2017

ADF: Execute code before page load

Problem description: In ADF there are multiple ways to execute a piece of code before page load. In this blog I would like to point out those options and their usecases.

Solution
1. If you have a Bounded task-flow and a pagefragment. You want to run a piece of code before fragment load and you want to do it only once. It means if you take any action on your page you do not want to run that piece of code again.

In such case you can simply add a method activity before your page in task-flow. Such method activities gets executed only once before page load.

While writing such methods, you will not have any handle for page components and its binding because you have not yet reached to your page.

Generally we use this approach when we want to do something model side for example I want to execute a VO and before showing its data on page. We can write method in AMImpl, expose it and drop it before fragment on task-flow.


2. If you want a piece of code to get executed anytime you take action on your page. You don't want page components but you want bindings to be available. 

In such case you can add such methods and operation binding in pageDef file and also add corresponding executable. Set executable's refresh property as per your need. Also placing of this executable binding is important as it gets executed from top to bottom. If you expect some VO to have data then you may want to keep this executale binding after that.

If its a bean method that you want to execute in this approach, I would suggest you to write a separate class and keep only that method in that java class and expose it as datacontrol. In any way you are not going to get page components. Getter/Setter of bean will return null so no point in mixing bean with this method. Keep bean and this Java method separately. Actually its not a bean method you are invoking but a datacontrol pojo kind of method.

If you keep your method in different java file but you want to access your bean. You can invoke ADFUtils method to get beanscope first and then get bean instance.


3. If you want a piece of code to get executed anytime you take action on your page. You also want page components to be available. 

In such case you should add hidden outputtext (visible=false) to your page and bind it with bean. In its getter/setter method you can place your code. Keep outputText at the bottom of your page so that by the time its getter/setter runs all other page components are already bound to bean.



In approach 2 and 3 although your method will get execute everytime you make server request but you can control its behaviour by keeping a variable in pageFlowScope and set its value to Y when method got executed first time and next time ownwards check if pageFlowScope variable value is Y then only execute. Something like below

public void initMyPage(){

     String value = ADFUtils.getPageflowScope().get("isPageAlreadyInitialised");

    if(!"Y".equals(value)){

           //write your initialization code here. This piece will get executed only once.
 
         ADFUtils.getPageFlowScope().put("isPageAlreadyInitialised", "Y");


   }

}

4. Using PagePhaseListener: If you are working with jspx page you can have PhaseListeners as well. Here challenge is carefully picking the phase in which you want to execute your code.

You can use ViewScope variable if you want to make sure code only runs on very first load of page.

@Override
    public void afterPhase(PagePhaseEvent pagePhaseEvent) {

        if (pagePhaseEvent.getPhaseId() == Lifecycle.INIT_CONTEXT_ID) {
                
           String value = ADFUtils.getViewScope().get("isPageAlreadyInitialised");

             if(!"Y".equals(value)){

                        initMyPage();

                      ADFUtils.getViewScope().put("isPageAlreadyInitialised", "Y");


            }


         }
    }



As bindings are already in place so you should be able to use bindingContext and bindingContainer to use bindings. Also to get UI component you can get handle of bean and get getter for bean. To get bean handle you can use expressions like
MyBean myBean = ADFUtils.evalueageEL("#{backingBeanScope.myBean}");



Thanks
Sanjeev

Saturday, January 28, 2017

ADF/SOA/Weblogic: Enabling fiddler for all webservice requests made by weblogic server

Problem Description: In ADF/SOA or simple J2EE application we may have requirement to enable third party webservices and we want to see exact request and response messages. Fiddler comes handy to me. In this blog I want to set fiddler to show all request/response messages sent by weblogic.

Solution
1. Install Fiddler: You can download and install fiddler from https://www.telerik.com/download/fiddler

2. Modify setDomainEnv.sh and add below line
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dhttp.proxySet=true -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=8888

Thats all. Now whenever your weblogic server will make a request to third party server, that request will go via fiddler and you can see exact Request/Response messages is fiddler.

Its very useful in SOA framework where you need to invoke services very frequently.


Tuesday, January 3, 2017

Oracle Cloud: Using Cloud Berry to connect with Cloud Storage

Problem Description: In this blog I just want to show how can we use cloud berry to connect with Oracle Cloud Storage.

Solution
1. Get Oracle Cloud storage: To use Oracle Cloud storage you must have cloud storage account. You can get it from https://cloud.oracle.com/en_US/storage


2. Get details from Cloud environment: Once you have Oracle Cloud login you will have username/password and identity domain. Using this you can see you dashboard. From Dashboard you can launch cloud storage home page.



2. Install Cloud Berry: You can download and install Cloud Berry from http://www.cloudberrylab.com/explorer/openstack.aspx

3.Run Cloud Berry and Navigate to File > New Oracle Cloud Account


     Before filling details in above shown form keep your REST endpoint handy. Its shown in Step-2

  • Display Name: It could be anything, which helps you to recognize cloud environment.
  • User Name: This is important. Most of the time mistake we make is we directly provide username. It actually has two parts. First part is last part of REST endpoint url [Storage-<IdentityDomain>]. Second part is your oracle cloud username. Now join both of them using colon (:)
  • Password: Your oracle cloud password.
  • Authentication Service: This is another important part. You can provide two values here. 
    • Take REST endpoint url and remove /v1/Storage-<IdentityDomain> and replace it with /auth/V1.0 as shown in above diagram.
    • Another way is if you have us2 datacenter you can use https://us2.storage.oraclecloud.com/auth/v1.0

4. Thats all, Now you can start managing cloud using Cloud Berry
         

Friday, November 11, 2016

Oracle JET: RequireJS How it works

In this blog I would like to show how requireJS. As I am exploring Oracle JET technology so I will keep my blog in context of Oracle JET

What is requireJS and its purpose: This library solves three problems
1. Download and execute a javascript library only when needed.
2. Reduce global variables
3. Provide modular structure to your javascript libraries.

To understand RequireJS, its better to see what generally happens when we don't have any such library. In that case we add all required javascript libraries in our html file using <script> tag. Browser will download all of them and execute them even though I don't need some of them while loading page initially. I may need to them later when user performs some action on page.
Also These libraries may by creating some global variables as well.
Also we need to be double sure about sequence of libraries in html. For example I can't use jquery selectors (like $("#lastname")) in my code unless I have jquery library mentioned. I definitely need to put jquery library script tag in html before using its feature in any subsequent library.

To overcome above limitations I need something which can
1. download and execute library only when needed.
2. reduce global variables
3. manage dependencies

That something is what requireJS is

Let see how it works. I have Oracle JET quickstart basic template project running. If you don't know Oracle JET, its a javascript based framework with rich set of UI components. Its open source and uses various third party libraries like knockout, jquery, promise, and requireJS etc.

I see in my index.html there is only one script tag

<script data-main="js/main" src="js/libs/require/require.js"></script>

The moment browser see this line in html, it download require.js and loads (execute) it.
require.js library validates data-main property of script tag and found that its js/main, which means its will look for a library main.js in js folder. It downloads it and run it. So atleast two libraries are going to get downloaded at page load. Lets use browser developer tools and verify it. I have put a debug point at first line of my main.js file. This line is requirejs.config call.

I found that
a. First require.js is downloaded, which is because we have <script> tag for that. It gets loaded immediately
b. After few milliseconds main.js is also getting download. Its not there in html script tag but its getting downloaded because require.js loads it asynchronously.
c. I also see two global variable require and requirejs added by require.js library. (NOTE we no other library has got executed till now)



main.js: First thing it does is calls requirejs.config function. This function is used to configure your all js library locations with require. All these library locations are given a name. For example knockout library is at libs/knockout/knockout-3.4.0 location. Its registered with name 'knockout'.
NOTE: we are not registering each and every js file. For example we have lots of oj libraries inside libs/oj/v2.1.0/debug but we are not mentioning them individually. We just mention parent directory here and associate it with ojs name. Which means if we want to refer any individual js from that directly we can simple say ojs/<that-library>



Next big call is require function call. It takes two inputs
a. Array of String
b. callback function

 require(['ojs/ojcore', 'knockout', 'appController', 'ojs/ojknockout', 'ojs/ojrouter',
   'ojs/ojmodule', 'ojs/ojdialog', 'ojs/ojnavigationlist', 'ojs/ojtoolbar',
   'ojs/ojbutton', 'ojs/ojmenu'],
   function (oj, ko, app) { // this callback gets executed when all required modules are loaded

       //Some code eliminated from here.
     
   }
 );

each entry in array of string can actually points to a js file if we join it with configuration done previously. For example ojs/ojcore, points to libs/oj/v2.1.0/debug/ojcore.js file. Each entry in this list is nothing but a dependency for the function. Each entry in terms of require is called a module.

job of require function is to call callback function once all the dependencies are loaded. So require function is going to load each js file mentioned as dependency here and once all are loaded its going to run callback function. By above require call I can say its going to load
libs/oj/v2.1.0/debug/ojcore.js, 
libs/knockout/knockout-3.4.0.js, 
appController.js, 
libs/oj/v2.1.0/debug/ojknockout.js, 
libs/oj/v2.1.0/debug/ojknockout.js, 
libs/oj/v2.1.0/debug/ojrouter.js, 
libs/oj/v2.1.0/debug/ojmodule.js, 
libs/oj/v2.1.0/debug/ojdialog.js
libs/oj/v2.1.0/debug/ojnavigationlist.js
libs/oj/v2.1.0/debug/ojs/ojtoolbar.js
libs/oj/v2.1.0/debug/ojbutton.js
libs/oj/v2.1.0/debug/ojmenu.js


NOTE: appContorller.js is not mentioned in config call as its present in same directory as main.js. So if all your libraries are present where you have main.js then you need not to mention anything in configure. But it would be a bad design


Lets put a debug point at very first line of our callback function
But as I know require is going to load dependencies first lets add few more debug points
First line of ojcore.js,
First line of ojmenu.js
First line of ojdialog.js etc

What I observe is it definitely downloads all js before calling callback function.


Now I am stopped at first line of ojcore.js
First line of ojcore.js is
define(['require', 'ojL10n!ojtranslations/nls/ojtranslations', 'promise'], function(require, ojt) {
   //Some code here
})

Its a call to define function.
Here define function is taking two arguments
1. Array of String
2. Callback function

Array of String is again nothing but dependcies and define function is also going to download all dependencies and then call callback function. It means ojcore is also dependent on some other js file or better to say module.
One question arise why not to use require when define is also doing something similar.

Require vs Define: As name suggest require is to download required libraries and then call callback function but Define is something to define. Define is actually defining a module. If you see the callback function of define must return a value. It could be anything but it must return a value. That value is associated with module and module name is nothing but what is mentioned in require call.

Effectively define is not only downloading dependencies and calling callback but also defining a module using moduleName and value.

What is the purpose of this module? This is what is passed to callback function as an input. If you see require function is taking oj, ko and app as three input. They are nothing but module value of ojs/ojcore, knockout and appcontroller first three dependencies mentioned in require call.



Now if I stop my bebugger at first line of require callback I see lots of other files are also downloaded


Can I assume that by the time require's callback is running all modules of JET are loaded. Definitely NOT. If we have to load all modules then why not to load using script tag itself. Only few required modules are loaded. Rest you will be loading when you create a viewModule.

When we create a viewModule, its js file again start of define call. Using that viewModule will load its dependencies separately. That is the advantage a module is loaded when its needed.

Few things you should notice
1. RequireJS tries to divide our code in modules. With that we should also change of coding style. We should write one module (function) in one js file. These functions should clearly know their dependencies.

2. require has so many dependencies but callback only takes three oj, ko, app as input. Why we have other dependencies. If you see first is ojs/ojcore. It creates oj global variable (namespace). All other dependencies adds its methods to oj namespace. For example ojs/ojrouter at Router related functions to oj namespace.

That's all I have here.

ADF: Token replacement for resource bundle af:formatNamed

Problem Description: There is a common usecase to have a translatable string in resource bundle with tokens. In this blog I want to show how to use such strings using af:formatNamed apis

Let say we have a string in bundle as

WELCOME_MESSAGE=Hello {USER_NAME}. Welcome to Benefits Application.

We want to replace username token at run-time.

Solution: You can simply use af:formatNamed apis to do so

<af:outputText value="#{af:formatNamed(viewcontrollerBundle.WELCOME_MESSAGE,'USER_NAME','Sanjeev')}" id="ot1"/>

In above you make 'Sanjeev' to an expression like securityContext.userName to show actual username.
<af:outputText value="#{af:formatNamed(viewcontrollerBundle.WELCOME_MESSAGE,'USER_NAME',securityContext.userName)}" id="ot1"/>



If you have two tokens you can use af:formatNamed2, It can replace two tokens
WELCOME_MESSAGE=Hello {USER_NAME}. Welcome to {APPLICATION_NAME}.

<af:outputText value="#{af:formatNamed2(viewcontrollerBundle.WELCOME_MESSAGE,'USER_NAME','Sanjeev', APPLICATION_NAME, 'Benefits Application')}" id="ot1"/>

Similarly for 3 tokens, use af:formatNamed3 and 4 tokens use af:formatNamed4 apis

Token name in bundle must be surrounded by curly braces as {USER_NAME}


What if I don't use token but simply break strings in multiple parts. For example instead of
WELCOME_MESSAGE=Hello {USER_NAME}. Welcome to Benefits Application.
I create a bundle as
WELCOME_MESSAGE_PART1=Hello
WELCOME_MESSAGE_PART2=Welcome to Benefits Application.

Now in expression I write it like
<af:outputText value="#{viewcontrollerBundle.WELCOME_MESSAGE_PART1} Sanjeev. #{viewcontrollerBundle.WELCOME_MESSAGE_PART2}"
                         id="ot2"/>

If you run application you may not find any difference but I suggest NOT to do that. This approach has some hidden problems

a. Your translator will not be able to understand whole message. Breaking message in parts can be very difficult to translate and may end up having a completely different meaning.
b. Also I have my doubts that it may not work properly with RTL language. Need to verify this point.






Thursday, October 20, 2016

ADF: Know if VO attribute is currently changed

Problem description: We have isAttributeChanged(String) method available in VORowImpl, which can tell if a particular attribute in vo row has changed or not. Problem with this method is if we change attribute once and then restore its value back, method still returns that attribute has changed. I would not say this is bug as this might be requirement at times to know if attribute is ever changed. but at times we are interested in knowing if attribute's current value is different from the database value.
In this blog I want to come up with another method isAttributeCurrentlyChanged(String), which can compare database value with current value and let us know if attribute is actually changed at this time. If value is restored, we should get false as there is no effective change.

Solution: Idea is to use getPostedAttribute method of entity to get database value and compare it with attribute's current value to know if its actually changed. We also want to add this method to be available on each vo row so we would be writing our own base classes and introduce method in those.

1. Create an Entity Impl (say SanEntityImpl) base class and introduce a method getDataBaseValue as

import oracle.jbo.server.EntityImpl;
public class SanEntityImpl extends EntityImpl {

    public Object getDataBaseValue(String attributeName){
        return getPostedAttribute(this.getAttributeIndexOf(attributeName));
    }
}

2. Create a View Row Impl (say SanViewRowImpl) base class as 

import oracle.jbo.server.AttributeDefImpl;
import oracle.jbo.server.ViewAttributeDefImpl;
import oracle.jbo.server.ViewRowImpl;

public class SanViewRowImpl extends ViewRowImpl {
  
    
    public boolean isEOBasedAttribute(String voAttributeName){
        ViewAttributeDefImpl voAttrDef = (ViewAttributeDefImpl)this.getViewDef().findAttributeDef(voAttributeName);
        byte attributeKind = voAttrDef.getAttributeKind();
        if(AttributeDefImpl.ATTR_PERSISTENT == attributeKind){
            return true;
        }
        else{
            return false;
        }
        
    }
    
    public boolean isTransientAttribute(String voAttributeName){
        ViewAttributeDefImpl voAttrDef = (ViewAttributeDefImpl)this.getViewDef().findAttributeDef(voAttributeName);
        byte attributeKind = voAttrDef.getAttributeKind();
        if(AttributeDefImpl.ATTR_TRANSIENT == attributeKind){
            return true;
        }
        else{
            return false;
        }
    }
    
    public Object getDatabaseValue(String voAttributeName){
        if(this.isEOBasedAttribute(voAttributeName)){
            ViewAttributeDefImpl voAttrDef = (ViewAttributeDefImpl)this.getViewDef().findAttributeDef(voAttributeName);
            AttributeDefImpl eoAttrDef = voAttrDef.getEntityAttributeDef();//voAttrDef.getReferenceAttribute()
            String entityAttributeName = eoAttrDef.getName();
            return ((SanEntityImpl)this.getEntity(this.getViewDef().getEntityIndex(voAttrDef.getEntityReference()))).getDataBaseValue(entityAttributeName);
            
        }
        else if(this.isTransientAttribute(voAttributeName)){
            return null;//Better if we can return initial value of attribute
        }
        else{
            return this.getAttribute(voAttributeName); 
        }
        
        
    }
    
    public boolean isAttributeCurrentlyChanged(String voAttributeName){
        Object dbValue = this.getDatabaseValue(voAttributeName);
        Object ctValue = this.getAttribute(voAttributeName);
        if(dbValue == null && ctValue == null){
            return false;
        }
        else if(dbValue == null && ctValue != null){
            return true;
        }
        else if(dbValue != null && ctValue == null){
            return true;
        }
        else if(dbValue.equals(ctValue)){
                return false;
        }
        else{
            return true;
        }
    }
   
}


3. Configure these classes as base classes in project properties



4. Test behavior of isAttributeChanged and isAttributeCurrentlyChanged

    Create EmployeeEO, EmployeeVO based on HR schema and add it in AM. Generate AMImpl and have below method in AM to verify


    public static void main(String[] args){
        String amDef = "com.san.adf.model.am.HRAppModule"; //Replace it with your AM
        String config = "HRAppModuleLocal";  //Replace it with your AM configuration
        HRAppModuleImpl am = (HRAppModuleImpl) Configuration.createRootApplicationModule(amDef, config);
        
        ViewObjectImpl empVO = am.getEmployeeVO();
        empVO.executeQuery();        
        SanViewRowImpl empRow = (SanViewRowImpl)empVO.first();
        
        
        String attrValue = null;
        String attributeName = "FirstName";
        if(empRow != null){
            
            
            attrValue = (String)empRow.getAttribute(attributeName);
            
            //When there is no change
            System.out.println("Without any change");
            System.out.println("isAttributeChanged: " + empRow.isAttributeChanged(attributeName));
            System.out.println("isAttributeCurrentlyChanged: " + empRow.isAttributeCurrentlyChanged(attributeName));
            
            //Change value of attribute and verify
            System.out.println("Changing attribute value to Sanjeev");
            empRow.setAttribute(attributeName, "Sanjeev");            
            System.out.println("isAttributeChanged: " + empRow.isAttributeChanged(attributeName));
            System.out.println("isAttributeCurrentlyChanged: " + empRow.isAttributeCurrentlyChanged(attributeName));
            
            
            //Restore value of attribute and verify
            System.out.println("Restoring attribute value");
            empRow.setAttribute(attributeName, attrValue);            
            System.out.println("isAttributeChanged: " + empRow.isAttributeChanged(attributeName));
            System.out.println("isAttributeCurrentlyChanged: " + empRow.isAttributeCurrentlyChanged(attributeName));
        }
        
        
        Configuration.releaseRootApplicationModule(am, true);
    }


If you run the AMImpl, output is something like this.

Without any change
isAttributeChanged: false
isAttributeCurrentlyChanged: false

Changing attribute value to Sanjeev
isAttributeChanged: true
isAttributeCurrentlyChanged: true

Restoring attribute value
isAttributeChanged: true
isAttributeCurrentlyChanged: false

We can see that after restoring value isAttributeCurrentlyChanged returns false, which means no change. 

Other utility method added in base class VORowImpl are 
isEOBasedAttribute: This method returns true if attribute is database driven.
isTransientAttribute: This method returns true if attribute is transient
getDatabaseValue: This attribute returns value of attribute from database.

Thats all.

Friday, July 29, 2016

Weblogic integrated server Demo Identity Keystore and Demo Trust Keystore


Weblogic has two kinds of keystore, one is IdentityKeyStore and other is TrustStore.

IdentityKeyStore: This keystore contains the identity for WebLogic Server. It means if any client wants to make an SSL request to server, server will send him this certificate. By default, file is located in <WL_HOME>\server\lib\DemoIdentity.jks. Its password is DemoIdentityKeyStorePassPhrase. Private key password is DemoIdentityPassPhrase. 

If you want clients to call an application on weblogic server over SSL then you need to set IdentityKeyStore and you need to add a certificate in it. You have two options to get certificate.
1. Contact verisign or other certificate authority to provide you a certificate.
2. You can yourself generate a certificate using keytool
keytool -genkey -keystore keystorename -storepass keystorepassword

You will use CA provided certificate if you want browser not to throw any warning of certificate when user tries to access your site. With self-signed certificate, browser throws exception and user needs to accept that OR alternatively they need to add that certificate to browser. 


TrustStoreThis keystore establishes trust for WebLogic Server. It means if this weblogic server needs to make a call to some secured server over SSL then its going to use this certificate. If you are making a call to thirdpart webservice using a java code, which is deployed on weblogic then weblogic will use this keystore to verify identity of thirdpart-server. This keystore is located at 
<WL_HOME>\server\lib\DemoTrust.jks. Its password is DemoTrustKeyStorePassPhrase. 

In truststore you generally need to add those certificates which are provided by third-party services, which weblogic is going to call. To get those cerficate is simple.
1. Access their service in IE, it will be an https call and you will see a lock icon.
 Install certificate as shown above.

2Export certificate from browser Tools >> Internet Options >> Content >> Certificate >> Other People >> Select Certificate >> Export
Import certificate in DemoTrust.jks by following these steps
a. Navigate to <WL_HOME>\server\lib and Take backup of DemoTrust.jks
b. Import certificate
keytool -importcert -file <location-of-your-cer-file> –keystore <location-of-trust-keystore> -alias <youraliasname> -storepass DemoTrustKeyStorePassPhrase
For example
keytool -importcert -file D:\temp\OracleOutSourcing_DER.cer –keystore D:\Oracle\Product\11.1.1.7.1-Cloud\Middleware64\wlserver_10.3\server\lib\DemoTrust.jks -alias oracleoutsourcing -storepass DemoTrustKeyStorePassPhrase

Once certificate is imported then you should be able to call thirdparty webservices over SSL.

NOTE: Jdeveloper also using same DemoTrust.jks for standalone program. If you run a java program in jdeveloper,
<your-jdk>\bin\javaw.exe -client -classpath <your-jars> -Djavax.net.ssl.trustStore=<WL_HOME>\server\lib\DemoTrust.jks <Your-java-class>

You can configure it in jdev using Tools > Preferences > Credentials


You can also change keystore/truststore in weblogic console and point to completely new keystore files. 




NOTE: keystore/trustore is server specific. It means all applications of one server are forced to use same keystore/truststore. If you want different keystore/truststore, you may need to create a new managed server.

NOTE: If you get bad-certificate issue after importing certificate in trusstore, then verify if certificate has entries like *.<domain>.com kind of entries. If yes, then you need to remove host verification in weblogic as wildcard host certificates are not allowed if host verification is enabled.