Showing posts with label ADF. Show all posts
Showing posts with label ADF. Show all posts

10 March, 2019

ADF : Scope Variables

Oracle ADF uses many variables and each variable has a scope.
There are five scopes in ADF (Application, Request, Session, View and PageFlow).
The below code snippest explains how to get value of each variable scope.

        AdfFacesContext adfCtx = AdfFacesContext.getCurrentInstance();
                
        //Page Flow Scope
        Map pageFlowMap  = adfCtx.getPageFlowScope();
        Object pageFLowVariable = pageFlowMap.get("VARIABLE_NAME");
        
        //View Scope
        Map viewMap  = adfCtx.getViewScope();
        Object viewVariable = viewMap.get("VARIABLE_NAME");
        
        //Session Scope
        HttpServletRequest request =
            (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession session = request.getSession(false);
        Object sessionVariable = session.getAttribute("VARIABLE_NAME");
        
        //Request Scope
        Object requestVariable = request.getAttribute("VARIABLE_NAME");
        
        //Application Scope
        Map applicationMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
        Object applicationVariable = applicationMap.get("VARIABLE_NAME");




Thanks

18 September, 2017

ADF : Send Parameter to actionListener method inside Bean

actionListener method method can be invoked by Adf Button , Link and Image.
actionListeners methods have only one parameter of type javax.faces.event.ActionEvent.

if requirement is to send some parameter to that bean method who’s signature is something like
public void myActionListener(ActionEvent actionEvent)

The solution to achieve this requirement is putting an attribute tag from the JSF.Core inside the commandButton (or whatever actionable component you are using). So the code in the jsp page looks like this:



Now i can get the value in the bean method by using below code

public void myActionListener(ActionEvent actionEvent) {
  // Add event code here...
  String paramValue = (String)actionEvent.getComponent().getAttributes().get("paramName");
  System.out.println("paramValue = " + paramValue);
}


03 June, 2015

ADF ::: Creating View Criteria Programmatically

We can add view criteria programmatically at run-time to ViewObject. So that we not only depend on Design View Criteria.

The following is an example used to create View Criteria in Application Module Impl

ViewObject empVO= this.findViewObject("EmpVO");
ViewCriteria vc = empVO.createViewCriteria();
ViewCriteriaRow vcRow = vc.createViewCriteriaRow();

// ViewCriteriaRow attribute name is case-sensitive.
// ViewCriteriaRow attribute value requires operator and value.
// Note also single-quotes around string value.
ViewCriteriaItem enameItem= vcRow.ensureCriteriaItem("Ename");
enameItem.setOperator("=");
enameItem.getValues().get(0).setValue("Mahmoud Elsayed");
vc.add(vcRow);

empVO.applyViewCriteria(vc);

 

Thanks

02 June, 2015

ADF ::: Handle af:query search Button Programatically

The following code snippets is to execute search button in ADF Query search button programmatically without interact from User

    public void onQueryListener(QueryEvent queryEvent) {
        // Add event code here...
        try{
        FacesContext fcsCtx = FacesContext.getCurrentInstance();
        ELContext elCtx = fcsCtx.getELContext();
        ExpressionFactory expFactory = fcsCtx.getApplication().getExpressionFactory();
        MethodExpression mthdExp =
            expFactory.createMethodExpression(elCtx, "#{bindings.EmpVOCriteriaQuery.processQuery}", null,
                                              new Class[] { queryEvent.getClass() });
        mthdExp.invoke(elCtx, new Object[] { queryEvent });
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

Thanks

20 April, 2015

ADF & OAF ::: Missing IN or OUT parameter

If the bind variable required property wrongly defined into View Object, then it will cause following exception
"java.sql.SQLException: Missing IN or OUT parameter at index:: 1 "

To avoid this exception, you have to keep in mind when you are creating bind variable.
 1- If you are directly passing the bind variable in view object main query then in this case bind variable require property should be selected.

2- If you are using bind variable in view criteria only  then in this case the bind variable require property should not be selected.

Thanks

30 September, 2013

JAVA : Convert InputStream to String

You can use the following snippet to convert InputStream to String
 
    private static String getStringFromInputStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

Thanks

23 September, 2013

ADF : Working with ViewCriteria

View Criteria's are additional where clause added at runtime to base View Object Query.


 Programmer can create view criteria declaratively or programatically.

1. Create View Criteria Declaratively Open View Object in Edit and in "Query" tab you can click "+" add pencil to create new view criteria

 
2. Control View Criteria Programatically.


 a- Get View Criteria from View Criteria manager within View Object and then apply it  
ViewCriteria applyVC = myViewObject.getViewCriteria("MyViewCriteriaName");
myViewObject.applyViewCriteria(applyVC);
myViewObject.executeQuery();

b- Applying Multiple view Criteria's

 
When multiple view criteria's are applied to the view object, the view criterias gets appended or replaced depending upon the way you use applyViewCriteria API
Replacing Existing view criteria's :

 
myViewObject.applyViewCriteria(applyVC) or

myViewObject.applyViewCriteria(applyVC,false)
will erase all previously applied view criterias and apply the current view criteria only.
Appending to the Existing view criteria:


myViewObject.applyViewCriteria(applyVC, true) 

 Will append this view criteria to the existing view criteria(s) which is applied already.

c- Unapplying && Removing View Criteria

vo.removeApplyViewCriteriaName()
Unapply the view criteria if it is applied. The view criteria will still remain in View Criteria Manager (which means you can't apply this view criteria whenever you require in the future).
vo.removeViewCriteria()
Removes the view criteria from View Criteria Manager. If it is applied it is first unapplied and then removed. (which means you cant apply this View Criteria to the view object next time in the future.).


For example the below code returns null after removeViewCriteria has been applied.
ViewCriteria applyVC = myViewObject.getViewCriteria("
MyViewCriteriaName")

vo.clearViewCriterias()
Unapplies and removes all view criteria, both applied and unapplied from View Criteria Manager. Which means that you can't apply any View Criteria against View Object.
For example the below code returns null after clearViewCriterias() has been applied.
ViewCriteria applyVC = myViewObject.getViewCriteria("
MyViewCriteriaName")
myViewObject.applyViewCriteria(null)
The above statement unapplies all existing View Criterias and not remove it.



myViewObject.setNamedWhereClauseParam("MyParameter", "myValue)
The above statement set Named Parameter Value. It set the value of "MyParameter" to "myValue".

I post in previous post about  ADF : Change View Criteria Columns at Runtime

Thanks

16 September, 2013

Random Numbers in Java

Previously I posted  about Generate Random Passwords in Oracle that was using PLSQL.
Today I will post about java randoms.

Java provides two classes to generate random numbers: Random and SecureRandom.
Random is faster than SecureRandom, but it uses a 48 bits seeds which is not enough for the long type.
Moreover, it is not 'random enough' for cryptography. SecureRandom, is slower than Random, but can be used for cryptography.

The following code example shows how to generate a random number within a range for int, long, float and double.

Note rangeStart , rangeEnd is range period of generated numbers .

        int rangeStart = 50;
        int rangeEnd = 100;

        SecureRandom secRandom = new SecureRandom();
        int inclusive = rangeEnd - rangeStart + 1;
        int exclusive = rangeEnd - rangeStart;


        int randomIntInclusive = secRandom.nextInt(inclusive) + rangeStart;
        int randomIntExclusive = secRandom.nextInt(exclusive) + rangeStart;

        System.out.println("randomIntInclusive : " + randomIntInclusive);
        System.out.println("randomIntExclusive : " + randomIntExclusive);

        long randomLongInclusive =
            (secRandom.nextLong() % inclusive) + rangeStart;
        long randomLongExclusive =
            (secRandom.nextLong() % exclusive) + rangeStart;

        System.out.println("randomLongInclusive : " + randomLongInclusive);
        System.out.println("randomLongExclusive : " + randomLongExclusive);

        float randomFloat = (secRandom.nextFloat() * exclusive) + rangeStart;
        System.out.println("randomFloat : " + randomFloat);

        double randomDouble =
            (secRandom.nextDouble() * exclusive) + rangeStart;
        System.out.println("randomDouble : " + randomDouble);

The output will be
randomIntInclusive : 60
randomIntExclusive : 73
randomLongInclusive : 11
randomLongExclusive : 63
randomFloat : 65.19333
randomDouble : 84.14220368726888



Thanks

12 September, 2013

Close Resources in Java

In java when using any resources like Files, Streams, Database Connection and DataSets etc .... , you must close resources at end of processing at your code.

For Example : Streams 

        File f = new File("myFile.txt");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
            // Do something...
        } catch (FileNotFoundException ex) {
            // Display error message
        } finally {
            // Closing resource
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    //Here , Hide Exception
                }
            }
        }

All previous code in Blue color are used to close resources.
So to save time and make code more readability you can use IOUtils Appache packages  to close resources quietly
      finally{
   IOUtils.closeQuietly(fos);
      }


For Example : Database Statement

 finally{
   DBTransaction txn = this.getDBTransaction();
        String sqlStmt =
            "Begin plsqlCode; END;";
        CallableStatement callStmt =
            txn.createCallableStatement(sqlStmt, DBTransaction.DEFAULT);
        try {
             //Write your code here to work with CallableStatement 
        } catch (SQLException e) {
             //Handle SQL Exception
        }finally {
            // Closing resource
            if (callStmt != null) {
                try {
                    callStmt .close();
                } catch (SQLException ex) {
                    //Here , Hide Exception
                }
            }
        }

All previous code in Blue color are used to close resources.
So to save time and make code more readability you can use DBUtils Appache packages  to close resources quietly

      finally{
   DbUtils.closeQuietly(callStmt );
      }

Thanks

08 September, 2013

Run JavaScript from Native Java

I wrote in previous post Execute Javascript code from Java Code how to execute java script in Oracle ADF.
But in this post I will explain how to call Javascript from native Java.



The following code snippets will illustrate how to evaluate Javascript code and invoke functions and get return value.

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class CallJavaScript {
    public static void callJsCode(String jsCode) throws ScriptException,
                                                        NoSuchMethodException {

        // Retrieving the Javascript engine
        ScriptEngine se =
            new ScriptEngineManager().getEngineByName("javascript");
        try {
            se.eval(jsCode);
        } catch (ScriptException e) {
            e.printStackTrace();
        }

        try {
            Invocable jsinvoke = (Invocable)se;
            System.out.println("myFunction(2) returns: " +
                               jsinvoke.invokeFunction("myFunction", 2, 4));
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }
}

Then You can call this code using for example
       try {
            String jsCode =
                "function myFunction(x,y){return x+y;}";
            CallJavaScript.callJsCode(jsCode);
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }      

The output of previous code will be

myFunction(2) returns: 6.0

Thanks

05 September, 2013

Iterate Through Java Map

There are multiple ways to iterate through a Java Map.

Assuming the following map declaration:
Map mapObj = new HashMap();

//Use Iterator [Generic]
Iterator> iter= mapObj.entrySet().iterator();
while ( iter.hasNext() ) {
    Entry item = iterator.next();
    System.out.println(item.getKey() + " - " + item.getValue());
}


//User Iterator [Without Generic]
Iterator iter= mapObj.entrySet().iterator();
while ( iterator2.hasNext() ) {
    Entry item = (Entry) iterator.next();
    System.out.println(item.getKey() + " - " + item.getValue());
}


// Use For Each [Generic]
for ( Entry item : mapObj.entrySet() ) {
    System.out.println(item.getKey()+ " - " + item.getValue());
}


// Use For Each [Without Generic]
for ( Entry item : mapObj.entrySet() ) {
    System.out.println(item.getKey()+ " - " + item.getValue());
}


//Fetch Value using Key
for ( String key : mapObj.keySet() ) {
    System.out.println(key + " - " + mapObj.get(key));
}



// Loop through Keys only
for ( String key : mapObj.keySet() ) {
    System.out.println(key);
}



// Loop through Values only
for ( Object value : mapObj.values() ) {
    System.out.println(value);
}


Thanks

21 August, 2013

ADF : Change View Criteria Columns at Runtime


When creating view criteria related to view object, then all querable attributes are displayed in view criteria by default.
So I want to change the properties of this attributes at run time pragmatically to display or hide specific attributes in view criteria.

I developed the following method for this purpose, You can add this method to ViewObjectImpl class.

I pass attribute name and a Boolean value to determine display in view criteria or no.

 public void setQuerable(String attributeName, Boolean isQuerable) {  
   
     int indx = this.getAttributeIndexOf(attributeName);  
   
     ViewAttributeDefImpl attr = (ViewAttributeDefImpl)this.getAttributeDef(indx);  
   
     attr.setQueriable(isQuerable);  
   
   }  


Thanks

20 August, 2013

Uncommitted data warning

If you are working entry data page and some feilds has been changed and you moved to another page, data still in cache but not posted or commited.

So to show warning of unsaved data before moving to another page you can do this by setting "Uncommitted data warning" property of af:document to "true". Then whenever user change data and  move out of current page or close the browser, it will display a warning of unsaved data



11 May, 2013

Set Sequence Number by Groovy Expression

Before I posted how to set Sequence Number using Code Get Sequence Next Value in ADF

Today I will illustrate how to set sequence number using groovy language.
You can do it by setting default value expression at primary key 

(new oracle.jbo.server.SequenceImpl("My_seq_name",adf.object.getDBTransaction())).getSequenceNumber()

Thanks

03 May, 2013

Compare JBO Date Programatically

To compare two jbo date programatically, l convert jbo date to sql date and then compare sql dates

oracle.jbo.domain.Date jboDate1 = new oracle.jbo.domain.Date();
oracle.jbo.domain.Date jboDate2 = new oracle.jbo.domain.Date();

java.sql.Date sqlDate1 =jboDate1.dateValue();
java.sql.Date sqlDate2 =jboDate2.dateValue(); 

//Compare sql Date
if (sqlDate1.before(sqlDate2 )) {     
  //Write Your Code
}

Thanks

29 March, 2013

Start Weblogic without user and password

When you want to launch your weblogic server at production, you need to use the startWeblogic.sh in your bin folder.

But each time it's launched it's asking you to authenticate yourself by typing a user and password. It's a problem when you want to automate the execution of your server...

To avoid this problem all you need to do is creating a file named "boot.properties" and insert into the two following lines :

username=<yourUserName>
password=<yourPassword>
this file must be placed in each server security folder : $WLS_HOME/user_projects/domains/<domainName/servers/<serverName>/security

Then, start server, it shouldn't ask you for anythin, then reopen your boot.properties file, password and username should be automatically encrypted !
Thanks

25 March, 2013

Avoid java out of memory with Weblogic

This is common exception always exists if you install weblogic and doesn't extend memory arguments in server.

The file "setDomainEnv.sh" in $WLS_HOME/user_projects/domains/<domainName>/bin/ has configuration of domain.

If you edit this file it will have the following default values.
MEM_ARGS="-Xms256m -Xmx512m"
export MEM_ARGS
MEM_PERM_SIZE="-XX:PermSize=48m"
export MEM_PERM_SIZE
MEM_MAX_PERM_SIZE="-XX:MaxPermSize=128m"
export MEM_MAX_PERM_SIZE

you should modify the MEM_ARGS java memory value depending of your server, here is the suggested to increase.
MEM_ARGS="-Xms2024m -Xmx3036m"
export MEM_ARGS
MEM_PERM_SIZE="-XX:PermSize=128m"
export MEM_PERM_SIZE
MEM_MAX_PERM_SIZE="-XX:MaxPermSize=512m"
export MEM_MAX_PERM_SIZE


Note : choosing the values depend on you server hardware.

Thanks

08 March, 2013

Redirect to ParentAction Programatically

In your task flow you can redirect parent action programatically using the following method.
   
public void redirectToParentAction(String parentAction) {
        ControllerContext ctrlCtx = ControllerContext.getInstance();
        ViewPortContextImpl portImpl = (ViewPortContextImpl)ctrlCtx.getCurrentViewPort();
        ParentActionEvent parentEvent = new ParentActionEvent(parentAction, true);
        portImpl.queueParentActionEvent(parentEvent);
    }



Thanks

04 March, 2013

Generate View URL in ADF

The following  getUrl method generates URL for you view in ADF application.
You pass servlet name and view id, I also overloaded getUrl method for making default servlet name as "faces".

   public static FacesContext getFacesContext() {  
     return FacesContext.getCurrentInstance();  
   }  
   
   public static ExternalContext getExternalContext() {  
     return getFacesContext().getExternalContext();  
   }  
   
   
   public static String getURL(String servletName, String viewId) {  
     HttpServletRequest request = (HttpServletRequest)getExternalContext().getRequest();  
   
     String requestUrl = request.getRequestURL().toString();  
   
     StringBuilder newUrl = new StringBuilder();  
   
     newUrl.append(requestUrl.substring(0, requestUrl.lastIndexOf(servletName)));  
   
     newUrl.append(servletName);  
   
     newUrl.append(viewId.startsWith("/") ? viewId : "/" + viewId);  
   
     return newUrl.toString();  
   }  
   
   public static String getURL(String viewId) {  
     return getURL("faces", viewId);  
   }  

Import the following Classes

 import javax.faces.context.ExternalContext;  
 import javax.faces.context.FacesContext;  
   
 import javax.servlet.http.HttpServletRequest;  

Thanks

29 December, 2012

Controlling TaskFlow Programatically


One of the generic solution is handling  taskflow programatically, To achieve this  you should get an object of a taskflow at managed bean and then you can call its methods for controlling in taskflow.

You can use the below method for this purpose.
Note you pass to the method taskFlowName used in page definition not the original taskflow name.

   public static DCTaskFlowBinding getTaskFlow(String taskFlowName) {  
   
     BindingContext bindingCtx = BindingContext.getCurrent();  
   
     DCBindingContainer dcbCon = (DCBindingContainer)bindingCtx.getCurrentBindingsEntry();  
   
     DCTaskFlowBinding taskFlow = (DCTaskFlowBinding)dcbCon.findExecutableBinding(taskFlowName);  
   
     return taskFlow;  
   }  

Thanks

ADF : Scope Variables

Oracle ADF uses many variables and each variable has a scope. There are five scopes in ADF (Application, Request, Session, View and PageFl...