Monday, December 30, 2013

PL/SQL Queries:

Query to get the body of a package:

select text

from   dba_source

where    NAME = 'GME_RESCHEDULE_BATCH_PVT'
;

Query to alter a session/ change the time and date format:

alter session set nls_date_format='mm/dd/yy hh24:mi:ss';

Query to insert multiple records:

INSERT ALL
  INTO LINE_DETAILS (Line_Number, Line_Name, Work_Start_time , Work_End_time, Working_Days) VALUES (1, 'Green', null,null,null)
  INTO LINE_DETAILS (Line_Number, Line_Name, Work_Start_time , Work_End_time, Working_Days) VALUES (2, 'Red', null,null,null)
  INTO LINE_DETAILS (Line_Number, Line_Name, Work_Start_time , Work_End_time, Working_Days) VALUES (3, 'Yellow', null,null,null)
  INTO LINE_DETAILS (Line_Number, Line_Name, Work_Start_time , Work_End_time, Working_Days) VALUES (4, 'Blue', null,null,null)
  INTO LINE_DETAILS (Line_Number, Line_Name, Work_Start_time , Work_End_time, Working_Days) VALUES (5, 'Voilet', null,null,null)
  --INTO LINE_DETAILS (column1, column2, column3) VALUES ('val2.1', 'val2.2', 'val2.3')
  --INTO LINE_DETAILS (column1, column2, column3) VALUES ('val3.1', 'val3.2', 'val3.3')
SELECT * FROM dual;

Query to delete the table records/ delete the table(Drop):

truncate table LINE_DETAILS;

Query to change the column name in table:

UPDATE LINE_DETAILS

   SET column = REPLACE(hr.Line_Details.Line_Name, 'Line1', 'Green');

Query to add a column in table:

ALTER TABLE LINE_DETAILS
ADD Line_Name Varchar2(100);

Query to change a value in table:

UPDATE LINE_DETAILS
SET Line_Name='Voilet'
WHERE Line_Number=5;




Thursday, December 26, 2013

Oracle ADF Task Flow concepts: Bounded and Unbounded Task Flows

ADF controller is an extension of java surfaces.
Bounded Task Flows:
-> They are reusable "whiteboxes" which provide navigation and processing.
-> Well defined boundary
-> Single point of entry
-> Can invoke code at the beginning of the task flow or at the end of the task flow allowing roll back or committing the changes accordingly.
-> Declarative transaction management.
-> Declarative back button support.
-> Bounded task flows communicate with the input/output parameters.

Unbounded Task Flows:
-> There are no well defined bounderies. There is no entry point or an exit point from an unbounded task     flow.
-> Usually used as a top level entry point.
-> They are used to declaratively use menu models.
-> Declarative bookmarking of the view activities. 

Programmatic Partial Page Refresh in ADF for a gantt component

My requirement:
Give the user the ease to schedule the products on a production line.
Use of PPR:
In the production scheduling gantt chart component i am unable to select the task bar component to set the PPR on it. Thats why i have gone for Programmatic PPR.

In the pseudo code:
       -> Get the ADF Faces context
       -> Get access to the UI component instance
       -> Make that component target for PPR.


-> First step bind the gantt component so that the UI component is accessible in the bean.
-> Using the ADFFacesContext get the current instance.
-> Add the component to the current instance partial target.

                    AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
                    adfFacesContext.addPartialTarget(getGetGantt());
         NOTE: here its a gantt component and i get getGetGantt() after i set the binding to the gantt       component. Like wise we can have what ever component we want to have.

add this code to the data change listener after you change the start date, resource_Id and other details in the back end. So that you are refreshing the gantt component after the changes are made.

Tuesday, November 19, 2013

ADF Naming Standards

Naming Standards are very important to organize the code, especially when you are working with large scale applications. Below are the naming conventions based on JUST my past experience


Business Components

  Entity                                  - Suffix with 'EO' - example : EmployeeEO
  Updateable View Object      - Suffix with 'VO' - example : EmployeeVO
  Programmatic View Object  - Suffix with 'TRVO' example : EmployeeTRVO
  ReadOnly View Object        -  Suffix with 'ROVO' example : EmployeeROVO
  List of Values View Object  -  Suffix with 'LOV' example : GenderLOV
  View Link                            - Suffix with 'VL' example : EmployeeDepartmentVL
   Association                         - Suffix with 'Assoc' Example : EmployeeDepartmentAssoc
  View Accessor                    - Suffix with 'VA' Example :  EmployeeNameVA
  Application Module               - Suffix with 'Service' example : EmployeeService

Packaging

Entities                            :     com.<application>.<project>.model.entities
Updateable View Object :     com.<application>.<project>.model.queries    
Application Module         :      com.<application>.<project>.model.services           
Programmatic View Object :     com.<application>.<project>.model.trvo
View Link                          :    com.<application>.<project>.model.vl
Association                        :    com.<application>.<project>.model.assoc
Read only View Object      :    com.<application>.<project>.model.readonly

Application Naming 
- Giver proper name to application , For eg : EmployeeMgmt, CustomerMgmt, VendorMgmt, etc.. The name of the application should be meaningful with respect to the functionality

Project Naming
 - Give meaningful name to each project you create in any application
 - Model Project :
   Example : EmployeeModel, CustomerModel,VendorModel - All the model projects suffix with 'Model'
- View Controller Project : 
 Example : EmployeeUI, CustomerUI, VendorUI - This project holds all the User Interface related components such as .jsff, jspx, xml, etc..

Web Service Projects
 Example : EmployeeWSService, CustomerWSService, VendorWSService - All these projects contains the web services related.

- Web Service Proxies
Example : EmployeeWSProxies, VendorWSProxies, CustomerWSProxies - All these projects contains the web service proxy related files.

Friday, November 15, 2013

Invoke Stored procedure (PL/SQL) and function using ADF

This blog explains about invoking PL/SQL Stored procedure using ADF


       

   public class PrintAndApplyServicesImpl extends ApplicationModuleImpl implements PrintAndApplyServices {
    /**
     * This is the default constructor (do not remove).
     */
    public PrintAndApplyServicesImpl() {
    }

    /**
     *This method takes the lot number as the input and gives the lot details as the output
     * @param pLotNumber
     * @return
     */

    public LotDetailsDTO getLotDetails(String pLotNumber) {
        //List lotDetailsList = new ArrayList();
        LotDetailsDTO lotInformation = new LotDetailsDTO();
        CallableStatement callableStatement = null;
        try {
            ResultSet rs = null;
             callableStatement = getDBTransaction().createCallableStatement("begin  " + "XHL_PRINT_APPLY_PKG.GET_LPN_INFO(?,?);" +  "end;", 0);                  
            // register the input parameter
            callableStatement.setString(1, pLotNumber);
           // register the out parameter
            callableStatement.registerOutParameter(2, OracleTypes.ARRAY, "ITEM_TAB_RESULT");
            // execute the statement
            callableStatement.execute();
            Array outArray = (Array)callableStatement.getArray(2);
            rs = outArray.getResultSet();
            while (rs.next()) {
                Struct row = (Struct)rs.getObject(2);
                if(row!=null) {
                    System.out.println("length"+row.getAttributes().length);
                    Object[] cols = row.getAttributes();
                    lotInformation.setBatchNumber((String)cols[0]);
                    //System.out.println(lotInformation.getBatchNumber());
                    lotInformation.setItemDescription((String)cols[1]);
                    lotInformation.setItemCode((String)cols[2]);
                    lotInformation.setRevision((String)cols[3]);
                    lotInformation.setLotNumber((String)cols[4]);
                    lotInformation.setTransactionQuantity((String)cols[5]);
                    lotInformation.setExpirationDate((String)cols[6]);
                    lotInformation.setUserName((String)cols[7]);
                    lotInformation.setPalletQuantity((String)cols[8]);
                    lotInformation.setPalletNumber((String)cols[9]);
                    lotInformation.setTransactionDate((String)cols[10]);
                    lotInformation.setTransactionId((String)cols[11]);
                    lotInformation.setBatchId((String)cols[12]);
                    lotInformation.setPrintStatus((String)cols[13]);
                    lotInformation.setExpiration((String)cols[14]);
                    lotInformation.setCurrentDate((String)cols[15]);
                    lotInformation.setGrossWeight((String)cols[16]);
                    lotInformation.setPalletHeight((String)cols[17]);
                    lotInformation.setPalletLength((String)cols[18]);
                    lotInformation.setPalletWidth((String)cols[19]);
                    lotInformation.setVolume((String)cols[20]);
                    lotInformation.setConcatCode((String)cols[21]);
                    lotInformation.setReponseStatus((String)cols[22]);
                    lotInformation.setResponseMessage((String)cols[23]);
                    for(Object col : cols) {
                        System.out.println(col);
                    }
                }
            }
                //lot.setItemDescription(rs.getString(2));
            if (callableStatement != null) {
                callableStatement.close();
            }
        } catch (Exception e) {
                e.printStackTrace();
        }
        return lotInformation;
    }
}
 

Tuesday, November 12, 2013

Generate PDF of a Table using ADF

How to download Oracle ADF tables in PDF format


          At this task we are going to convert ADF BC tables into PDF files and make it downloadable to users. It looks like very easy but it is not. To successfully complete this task I had to use several libraries such as apache fop library.
 
  • What is Apache FOP library.....??



          FOP stands for Formatting Object Processor. Apache FOP is a Java application which reads a Formatting Object (FO) tree and renders the resulting pages to a specific output. Currently supported outputs are:
           PDF, PS, PCL, AFP, XML, Print, AWT and PNG, and to a lesser extend RFT and TXT.
          Developers use Apache FOP libraries to change the output file format very commonly because it’s free and open source. You can download the Apache FOP library as a JAR file from the below link. (There are different links to download FOP.jar; but most of the jar files do not contain all the libraries required for this conversion.)


  •  How to convert ADF BC tables into PDF files
 
           If we try to analyse the process goes here we can simply represent it as below.

          First of all we want to get the table data and write it into a XML file. We can do it through JDeveloper framework. There is an inbuilt method called “printXML” at ViewObjectImpl class. It will generate the XML to the VO data. So if we can access the ViewObjectImpl class anyway we can generate the XML file. <VO>Impl class is a one which extends the ViewObjectImpl class. So we can generate the <VO>Impl class and generate the XML file.

  • Implement the <VO>Impl and <Application_Module>Impl classes for your MODEL project. (We need those method at those classes to generate the XML file.)
    (<VO>.xml Ã  Java Ã  Java Classes Ã  click on "pencil" icon.)

  • Create a Java class at “View Controller” project to create a managed-bean. We are going to do all the coding inside this bean. All the required codes are mentioned at the end of this article.
     
  • We can access the <VO>Impl class through this path:
    (FacesContext Ã  ExternalContext Ã  AdfFacesContext Ã  HttpServletRequest Ã  BindingContext Ã  DCDataControl Ã  ApplicationModule Ã  AppModuleImpl Ã  ViewObjectImpl)
     
  • When we are creating the Node object we have two options. You can select the one which suits your requirement. (refer code while "// Print the XML" )
    Parameter
    Description
    XML_OPT_ALL_ROWS
    All rows will be rendered in XML
    XML_OPT_ASSOC_CONSISTENT
    attribute accessors that return a RowSet should set the AssociationConsistent flag on, so that new (unposted) rows for the RowSet are also included in the output.
    XML_OPT_CHANGES_ONLY
    For internal framework use only.
    XML_OPT_LIMIT_RANGE
    Rows in the current range will be rendered in XML
  • Then we have to generate the PDF using  a style sheet. Before genarate PDF files you should have to build the style sheet. Then we can generate the output file using FOP libraries (we can select the output format). Output format depends on the MimeConstant you select. There are several output formats supported by FOP libraries as follows. (refer code while "// Generate PDF" )

    MIME Constant
    Output Format
    MIME_PDF
    pdf
    MIME_PLAIN_TEXT
    txt
    MIME_PNG
    png
    MIME_FOP_AREA_TREE
    xml
    MIME_POSTSCRIPT
    ps
    MIME_AFP
    afp
    MIME_TIFF
    tiff
  •   
  • Then insert a Command Button next to your ADF BC table. Create a web page backing bean and write an Action Method. Then set that action method as the “action” property of the created command button. Inside the action method we have to write some codes which will make the generated pdf file to be downloadable.
     
  • When user press the command button pdf file shold be generated and downloadable. To do that  we have to go through the Context layers of the framework, get the http servlet response and set the content type of the response.
     
  • Here we have set the content type as “application/pdf” because we have generated a pdf file. That parameter depends on your file type. (refer code while "// download the PDF" )

      
All the required codes are given below.....

 
// Access the <VO>Impl
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
AdfFacesContext context = AdfFacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
BindingContext ctx = DCUtil.getBindingContext(request);
DCDataControl dc = ctx.findDataControl("AppModuleDataControl");
ApplicationModule service = (ApplicationModule)dc.getDataProvider();
ApplicationModule am = service.findApplicationModule("AppModule");
AppModuleImpl amImpl = (AppModuleImpl)am;
ViewObjectImpl VOImlp = (EmpVOImpl)amImpl.findViewObject("EmpVO1");
HashMap viewDefMap = new HashMap();

// Print the XML
Node n = VOImlp.writeXML(XMLInterface.XML_OPT_ALL_ROWS, viewDefMap);
java.io.File file = new java.io.File(<path to save XML file>);
PrintWriter output = null;
try {  output = new java.io.PrintWriter(file);
          ((XMLNode)n).print(output);
} catch (Exception e) { System.out.println(e.getMessage());
} finally {
try {output.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } }

// Generate PDF
File xmlfile = new File(<path to generated XML file>);
File xsltfile = new File(<path to styleSheet>);
File pdffile = new File(<path to save PDF file>);
FopFactory fopFactory = FopFactory.newInstance();
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
OutputStream out = new java.io.FileOutputStream(pdffile);
out = new java.io.BufferedOutputStream(out);
try {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
TransformerFactory factory = new TransformerFactoryImpl();
Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));
transformer.setParameter("versionParam", "2.0");
Source src = new StreamSource(xmlfile);
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
} finally { out.close(); }

// download the PDF
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse)externalContext.getResponse();
File file = new File(dir1, pdffile1);
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
          response.reset();
          response.setContentType("application/pdf");
          response.setContentLength((int)file.length());
response.setHeader("Content-disposition","inline;filename=\""+pdffile1+"\"");
output = new BufferedOutputStream(response.getOutputStream(),DEFAULT_BUFFER_SIZE);
          byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
          int length;
          while ((length = input.read(buffer)) > 0) {
              output.write(buffer, 0, length); }
          output.flush(); } finally { close(output); close(input); }
facesContext.responseComplete();

   USEFULL SITE relating to this

Monday, November 11, 2013

Scopes in ADF

Scopes in Fusion Web Applications


Scope indicates life time of an object. In ADF and JSF it is possible to define backing beans with particular scope.

Types of Scopes

There are seven types of scopes in a Fusion web application:

Scopes listed below in descending order with first one having longest life time and last one lowest life time.

Application scope -> Session scope ->Page flow scope  -> View scope ->Request scope ->Backing  bean scope
  • Application scope: An application scope object is available for the duration of the application and is shared among users. This scope may be used to hold static objects that are the same for all users.
  • Session scope: The object is available for the duration of the session, which is user instance-specific. A use case for a session scope bean is a user info bean that stores information about a user, which is read from the database or an LDAP server, to avoid unnecessary queries.
  • Page flow scope (Task flow scope): A pageFlow scope exists for each task flow instance and has a lifespan between request and session scope. The lifetime of the scope spans across all pages in a bounded task flow.
  • Request scope: The object is available from the time an HTTP request is made until a response is sent back to the client. From another perspective, a request scope starts with a request to be issued from one view to another for navigation cases that don't perform a redirect but a default server-side forward. The scope spans across all non-view activities that follow the view of interest to the next view activity.
  • Backing bean scope: The backing bean scope is comparable to the request scope, with the difference in that it exists for a specific client component. In general, all managed beans used in reusable components should be configured to backingBean scope. For example, bounded task flows that are designed to be regions on a page should use the backingBean scope if more than one instance of the task flow is expected to be on a single page.
  • View scope (Page Scope): The object is available until the view ID for the current view activity changes. This becomes handy when you use partial page rendering. If you have a dependent list box, you might send a server request to refresh the list box. When a response is returned, the request scope will be gone but the view scope will be still there. Therefore, view scope can be used to store data when partial rendering request comes back. The view scope exists not only for views that are rendered by JSPX pages, but also for views rendered by page fragments, as is the case in task flows that are built to execute in a region. The view scope of the parent page is not accessible from components added to a page fragement in a region, and the view scope of a view in a region is not accessible for the parent page.
  • None:  When you create objects (such as a managed bean) that require you to define a scope, you can set the scope to none, meaning that it will not live within any particular scope, but will instead be instantiated each time it is referenced. You should set a bean's scope to none when it is referenced by another bean.
Out of these View scope, Backing bean scope and page flow scope are ADF specific. Rest comes with JSF. This is the reason you must define ADF specific scoped backing beans ether in "adf-config.xml" or task flow. You access objects in those scopes via expression language with scope qualification. For instance, to reference the aaBean managed bean from viewScope scope, your expression would be
#{viewScope .aaBean }.
When working in ADF its always recommended to define backing beans in  ether "adf-config.xml" or task flow files.

References

  1. Oracle Fusion Developer Guide by Frank Nimphius and Lynn Munsinger
  2. Creating and Using Managed Beans (if you use ADF Faces components in a standard JSF application)
  3. Using a Managed Bean in a Fusion Web Application (if you use Oracle ADF Model data binding and ADF Controller)
  4. JavaServer Faces (JSF) Tutorial
  5. Backing Bean in JSF Tutorial
  6. Managed Beans in Oracle Fusion Web Applications

Monday, October 14, 2013

How to send an email using Java API & Gmail account


Below blog explains about sending an email using Gmail email address as from email and Java API

Below is the sample code snippet to send email using Java Mail API.

Download the Java Mail Jar and set in class path
Here is the link to download java-mail.jar  http://www.oracle.com/technetwork/java/index-138643.html

       

    /**
   * De limit the toEmail List
   * Authenticate
   * @param msg
   * @param subject
   * @param toEmail
   * @param fromEmail
   * @return
   * @throws Exception
   */
  public static String sendEmail(String msg, String subject, String toEmail, String fromEmail)
    throws Exception
  {
    String toEmails[] = toEmail.split(",");
    System.out.println("TO:::FROM:::SUBJ:::BODY:::" + toEmail + "-" + fromEmail + "-" + subject + "-" + msg);

    Session session = setSessionAuthentication();
    InternetAddress from = new InternetAddress(fromEmail);
    InternetAddress to[] = new InternetAddress[toEmails.length];
    for (int c = 0; c < toEmails.length; c++)
    {
      to[c] = new InternetAddress(toEmails[c]);
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.addRecipients(Message.RecipientType.TO, to);
    message.setSubject(subject);
    message.setText(msg);
    Transport.send(message);
    // msg="OK Msg Posted Successfully";
    return "EMail Sent Successfully";
  }

  /**
   *
   * @return
   * @throws Exception
   */
  public static Session setSessionAuthentication()
    throws Exception
  {
    final String username = "FM@gmail.com";
    final String password = "GMAIL PASSWORD";
    //Using SSL
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    // USING TLS
    //        Properties props = new Properties();
    //        props.put("mail.smtp.auth", "true");
    //        props.put("mail.smtp.starttls.enable", "true");
    //        props.put("mail.smtp.host", "smtp.gmail.com");
    //        props.put("mail.smtp.port", "587");
    props.put("mail.debug", "true");
    MailSSLSocketFactory sf = null;
    try
    {
      sf = new MailSSLSocketFactory();
    }
    catch (GeneralSecurityException e1)
    {
      e1.printStackTrace();
    }
    sf.setTrustAllHosts(true);
    props.put("mail.smtp.ssl.socketFactory", sf);
    Session session = Session.getInstance(props, new javax.mail.Authenticator()
      {
        protected PasswordAuthentication getPasswordAuthentication()
        {
          return new PasswordAuthentication(username, password);
        }
      });
    return session;
  }
       
 

Tuesday, October 8, 2013

Oracle ADF Cheat Sheet

// print the roles of the current user
for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {
System.out.println(”role “+role);
}
// get the ADF security context and test if the user has the role users
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
if ( sec.isUserInRole(”users”) ) {
}
// is the user valid
public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated();
}
// return the user
public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName();
}
// get the binding container
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
// get an ADF attributevalue from the ADF page definitions
AttributeBinding attr = (AttributeBinding)bindings.getControlBinding(”test”);
attr.setInputValue(”test”);
// get an Action or MethodAction
OperationBinding method = bindings.getOperationBinding(”methodAction”);
method.execute();
List errors = method.getErrors();
method = bindings.getOperationBinding(”methodAction”);
Map paramsMap = method.getParamsMap();
paramsMap.put(”param”,”value”)  ;
method.execute();
// Get the data from an ADF tree or table
DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
FacesCtrlHierBinding treeData = (FacesCtrlHierBinding)bc.getControlBinding(”tree”);
Row[] rows = treeData.getAllRowsInRange();
// Get a attribute value of the current row of iterator
DCIteratorBinding iterBind= (DCIteratorBinding)dcBindings.get(”testIterator”);
String attribute = (String)iterBind.getCurrentRow().getAttribute(”field1″);
// Get the error
String error = iterBind.getError().getMessage();
// refresh the iterator
bindings.refreshControl();
iterBind.executeQuery();
iterBind.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);
// Get all the rows of a iterator
Row[] rows = iterBind.getAllRowsInRange();
TestData dataRow = null;
for (Row row : rows) {
dataRow = (TestData)((DCDataRow)row).getDataProvider();
}
// Get the current row of a iterator , a different way
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), “#{bindings.testIter.currentRow.dataProvider}”, TestHead.class);
TestHead test = (TestHead)ve.getValue(ctx.getELContext());
// Get a session bean
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), “#{testSessionBean}”, TestSession.class);
TestSession test = (TestSession)ve.getValue(ctx.getELContext());
// main jsf page
DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
// taskflow binding
DCTaskFlowBinding tf = (DCTaskFlowBinding)dc.findExecutableBinding(”dynamicRegion1″);
// pagedef of a page fragment
JUFormBinding form = (JUFormBinding) tf.findExecutableBinding(”regions_employee_regionPageDef”);
// handle to  binding container of the region.
DCBindingContainer dcRegion   = form;
// return a methodexpression like a control flow case action or ADF pagedef action
private MethodExpression getMethodExpression(String name) {
Class [] argtypes = new Class[1];
argtypes[0] = ActionEvent.class;
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createMethodExpression(elContext,name,null,argtypes);
}
//
RichCommandMenuItem menuPage1 = new RichCommandMenuItem();
menuPage1.setId(”page1″);
menuPage1.setText(”Page 1″);
menuPage1.setActionExpression(getMethodExpression(”page1″));
RichCommandButton button = new RichCommandButton();
button.setValueExpression(”disabled”,getValueExpression(”#{!bindings.”+item+”.enabled}”));
button.setId(item);
button.setText(item);
MethodExpression me = getMethodExpression(”#{bindings.”+item+”.execute}”);
button.addActionListener(new MethodExpressionActionListener(me));
footer.getChildren().add(button);
// get a value
private ValueExpression getValueExpression(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return  elFactory.createValueExpression(elContext, name, Object.class);
}
// an example how to use this
RichInputText input = new RichInputText();
input.setValueExpression(”value”,getValueExpression(”#{bindings.”+item+”.inputValue}”));
input.setValueExpression(”label”,getValueExpression(”#{bindings.”+item+”.hints.label}”));
input.setId(item);
panelForm.getChildren().add(input);
// catch an exception and show it in the jsf page
catch(Exception e) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), “”);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, msgHead , msgDetail);
facesContext.addMessage(uiComponent.getClientId(facesContext), msg);
// reset all the child uicomponents
private void resetValueInputItems(AdfFacesContext adfFacesContext,
UIComponent component){
List<UIComponent> items = component.getChildren();
for ( UIComponent item : items ) {
resetValueInputItems(adfFacesContext,item);
if ( item instanceof RichInputText  ) {
RichInputText input = (RichInputText)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
} else if ( item instanceof RichInputDate ) {
RichInputDate input = (RichInputDate)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
}
}
}
// redirect to a other url
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse)ectx.getResponse();
String url = ectx.getRequestContextPath()+”/adfAuthentication?logout=true&end_url=/faces/start.jspx”;
try {
response.sendRedirect(url);
} catch (Exception ex) {
ex.printStackTrace();
}
// PPR refresh a jsf component
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);
// find a jsf component
private UIComponent getUIComponent(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
return facesCtx.getViewRoot().findComponent(name) ;
}
// get the adf bc application module
private OEServiceImpl getAm(){
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, “#{data.OEServiceDataControl.dataProvider}”,
Object.class);
return   (OEServiceImpl)valueExp.getValue(elContext);
}
// change the locale
Locale newLocale = new Locale(this.language);
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(newLocale);
// get the stacktrace of a not handled exception
private ControllerContext cc = ControllerContext.getInstance();
public String getStacktrace() {
if ( cc.getCurrentViewPort().getExceptionData()!=null ) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cc.getCurrentViewPort().getExceptionData().printStackTrace(pw);
return sw.toString();
}
return null;
}
// get the selected rows from a table component
RowKeySet selection = resultTable.getSelectedRowKeys();
Object[] keys = selection.toArray();
List<Long> receivers = new ArrayList<Long>(keys.length);
for ( Object key : keys ) {
User user = modelFriends.get((Integer)key);
}
// get  selected Rows of a table 2
for (Object facesRowKey : table.getSelectedRowKeys()) {
table.setRowKey(facesRowKey);
Object o = table.getRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
Row row = rowData.getRow();
Test testRow = (Test)((DCDataRow)row).getDataProvider() ;
}

Oracle ADF – Best Practices

  1. Do not use invokeAction in pageDef because will be executed several times. Use instead a task flow with a method call in front. Also, using this approach, we can reuse the page in other task flows.
  2. Do not create view criterias containing the name of the view since the name of the view could be changed and then also, the criteria name should be changed.
  3. Use unbounded tasks only for pages or bounded task flows available as bookmarks.
  4. Do not use unbounded task flows for the following operations: create, update and delete. Should be used only for read operations.
  5. Do not add service methods in the application model that are dependent of the view iterators (default iterators). Use instead standard operations like: CreateWithParams, ExecuteWithParams,  etc.
  6. Create secondary iterators for views in the service methods. Do not use default iterators because are the same used in the view layer.
  7. Do not add HTML in JSF. Use instead styles and/or CSS for available ADF components.
  8. Try to not use the view’s attributes in the WHERE clause for filtering. Use instead default criterias for each view instance from the application model.
  9. Do not use two services layers separately with different database connections to the same database if is not needed. Use instead nested application models.
  10. Always use the scope prefix for any accessed memory variables (requestScope, backingBeanScope, viewScope, pageFlowScope, sessionScope, applicationScope, backingBeanScope).
  11. Put the Cancel operation in af:subform and with immediate=true, in order to ignore the validations of other input fields which have immediate=true.
  12. In the context of fragment based task flows, use viewScope in preference to request scope for a more predictable behavior within the context of the sub-flow that contains the fragments
  13. Task flows should always contain an activity marked as an exception handler. This activity does not have to be a view activity it can be a method or router (our preferred approach) with control flow rules to subsequent activities.
  14. Use SetPropertyListener instead of SetActionListener (was deprecated in 11g).
  15. Do not combine view accessors with data model master-detail because accessor attributes create distinct row sets based on an internal view object other than that from detail.
  16. When a view criteria is applied programmatically in a business method from the application model later the view criteria must be removed.
  17. Try to use data model master-detail only for composite relations.
  18. For performance increase you can tune the view instance from the application model in order to get from DB more than one row once. By default is 1.