Wednesday, June 27, 2018

ADF UI - Resetting or clearing form fields in ADF popup on clicking 'Cancel'


Sample UseCase: Suppose the popup has input form fields to enter data with say OK and Cancel buttons, and when the user enters data and clicks on 'Cancel' button, we need to close the popup and reset all values entered in the popup's fields. If you don't reset the values, if you invoke the same popup again, it'll show the same previously entered values in the form which is unwanted. So, how to show the popup without the previous values?

Solution:
1. Set popup's 'contentDelivery' property to 'lazyUncached'. Setting this property won't cache the data entered and won't restore the previously entered values. This is highly recommended to set contentDelivery="lazyUncached" for better performance as the popup will be loaded only on invocation but not at the time of page loading.

1 <af:popup id="popup1" 2 binding="#{pageFlowScope.ClassSectionCreateBean.cancelWarningPopup}" 3 contentDelivery="lazyUncached">

2. If the step1 doesn't work, drop af:resetActionListener as a sub-element to 'Cancel' button in the popup. ResetActionListener will reset the form fields in the popup. We can also call ResetActionListener programmatically in an actionlistener method as follows using Oracle's internal API.

1 public void saveSections(ActionEvent ae) { 2 //Your logic here 3 ResetActionListener ral = new ResetActionListener(); 4 ral.processAction(ae); 5 }

But, using internal API in the code is not encouraged. There is public API to achieve the same using the below code.

1 UIComponent comp = actionEvent.getComponent(); 2 oracle.adf.view.rich.util.ResetUtils.reset(comp);

But, this Public API is not yet available in the latest publicly available Jdeveloper available and it'll be available in the upcoming versions. Until then, we need to go ahead using internal API only as shown in step2.

Above solutions might not work....
3. solution works for me
We need to write below code at cancel button before hide the popup. 
        Row r1 = hdrVo.getCurrentRow();
        //r1.refresh(oracle.jbo.Row.REFRESH_UNDO_CHANGES |  Row.REFRESH_FORGET_NEW_ROWS);  
        r1.refresh(r1.REFRESH_UNDO_CHANGES | r1.REFRESH_WITH_DB_FORGET_CHANGES);

Tuesday, June 26, 2018

Casting String Timestamp into JBO Timestamp

 
        // setting acknowledgement date
        java.util.Date date;
        Calendar cal = Calendar.getInstance();
        date =cal.getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        String strDate = dateFormat.format(date);
        this.setAckDt(castToJBODate(strDate));


====================== ======================
 public oracle.jbo.domain.Timestamp castToJBODate(String aDate) {
        DateFormat formatter;
        SimpleDateFormat  dateFormat ;
        java.util.Date date;
       
        if (aDate != null) {

            try {

                //formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss ");
               dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                //date = formatter.parse(aDate);
                date = (Date)dateFormat.parse(aDate);
                System.out.println("Sql Date:"+date.getTime()+" : "+date);
                java.sql.Date sqlDate = new java.sql.Date(date.getTime());
                java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
                System.out.println("Date after :"+sqlDate);
                //oracle.jbo.domain.Timestamp jboDate = new oracle.jbo.domain.Timestamp(sqlDate);
                oracle.jbo.domain.Timestamp jboDate = new oracle.jbo.domain.Timestamp(timestamp);
                System.out.println("Jbo Date:"+jboDate);
                return jboDate;
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

        return null;
    }

Sunday, June 24, 2018

Converting ADF Pages to Reusable Page Fragments

https://blogs.oracle.com/shay/converting-adf-pages-to-reusable-page-fragments


So you finished building a great ADF Faces JSF page, and now you realize that you actually need the same functionality in 30 other places in your application. Well wouldn't it have been great to know about it before you started? What am I suppose to do now? How can I include one JSF page inside another JSF page?
Don't worry - JDeveloper and ADF come to the rescue.
ADF has some great reusability features for JSF pages in the form of TaskFlows, Page Fragments and Regions. And even if you didn't plan ahead of time to use those, you can still get your page to become a pagefragment and be included in other pages quite easily with the JDeveloper convert options for taskflows.
 Here is a small demo that shows how to take a regular ADF Faces page, and convert it to be a resuable page that you can include in multiple other pages.

Tuesday, June 12, 2018

Oracle ADF bean memory scopes thefollowing diagram shows an overview of the managed bean memory scopes, and the corresponding expression language references, supported by Oracle ADF. See "What You May Need to Know About Memory Scope for Task Flows" at Creating a Task Flow for additional information.

Oracle ADF bean memory scopes

The following diagram shows an overview of the managed bean memory scopes, and the corresponding expression language references, supported by Oracle ADF. See "What You May Need to Know About Memory Scope for Task Flows" at Creating a Task Flow for additional information.



A best practice for managed beans that is often (and I admit easily) overlooked is to implement the Java Serializable interface for beans in session, pageFlow and view scope. 

You wont recognize the absence of Serializable before running your application in a fail over environment. 

As it fits into this context: Note that managed beans can inherit from a parent. So you may want to design a base managed bean class that contains helper functions you often need and that also implements Serializable. Then, with a little change to your coding guidelines, that managed beans must extend the base bean, you ensure your application's managed beans are always serializable.

Note that under the Tools | Preferences | Audit | Profiles entry, Oracle JDeveloper has an audit rule to find managed beans that are not serializable



Monday, June 11, 2018

Display selected table row number and total rows

Display selected table row number and total rows

A question on OTN was how to display the current row number
and the number of totally available rows in a formatted output string. In the
example used below, the format is
row no. [<row index>] of max rows [<total numbers of rows>]
For this example, I used an af:outputText component to
display the information on the page. The value of the af:outputText component is calculated from expression language (EL)
accessing the ADF binding layer as shown below. Note that for better readability the EL includes line breaks, which in your application you should not add.
 row no. [
#{(bindings.allDepartmentsIterator.rangeStart
< 0 ?

1 : bindings.allDepartmentsIterator.rangeStart+1) +

(
bindings.allDepartmentsIterator.currentRowIndexInRange == -1 ?

0 :
bindings.allDepartmentsIterator.currentRowIndexInRange)}
]
of max rows[
#{bindings.allDepartmentsIterator.estimatedRowCount}]
Note
how the expression uses the iterator binding in the ADF binding layer to determine
the maximum number of table rows. It then uses the same iterator to determine
the current row. Because iterators are zero based, the EL uses additional logic
to compensate this.
The af:outputText component needs to have its PartialTriggers property pointing the the af:table component ID to ensure the displayed information is refreshed when the table row currency changes.
 <af:outputText value="row no. [#{(bindings.allDepartmentsIterator.rangeStart &lt; 0 ? 1  :  bindings.allDepartmentsIterator.rangeStart+1) +( bindings.allDepartmentsIterator.currentRowIndexInRange ==  -1 ? 0 : bindings.allDepartmentsIterator.currentRowIndexInRange)}] of max rows [#{bindings.allDepartmentsIterator.estimatedRowCount}]"
                id="ot1" partialTriggers="pc1:t1"/>

Thursday, June 7, 2018

Difference in RowCount Vs EstimatedRowCount Vs FetchedRowCount in ADF

Being an ADF developer,there are few method which is very confusing .So lets discuss method which fetch row count of VO>
Sometimes in ADF applications, we need to count the number of rows, as shown in the table .If we don’t understand these method , it will create a big performance problem.
getRowCount() -> getRowCount() retrives all the records from View Object by executing ViewObject Query.The count is calculated by traversing the Viewobject using next() method until the
last record is retrived. This method hinders the performance of application in case of VO with large number of rows.
getEstimatedRowCount() -> When you need to get quick count of row.Use this method. Method getEstimatedRowCount() actually retrives the count by hitting getQueryHitCount() which runs the select count(*) on the VO query.
getFetchedRowCount() -> Method getFetchedRowCount() counts the number of rows from the Result Set.Returns the number of rows fetched at that point of time.
In Short –
-> When you need to iterate all row to get or check some attribute value use getRowCount().It can create problem issue.
-> When you just need an count of table use getEstimatedRowCount().
If the application, we need to traverse the rowset all records, such as some of the above every line to get attribute values, you can choose to use getRowCount () method;
And if we only need to know the number of rows set the time, then use getEstimatedRowCount () method,

Wednesday, June 6, 2018

vo.getAllRowsInRange() vs vo.createRowSetIterator

   

public List selectedUnits(){
    /* DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
    DCIteratorBinding itr = bindings.findIteratorBinding("CmUserUnitAccessVu1VO1Iterator");
    ViewObject vo = itr.getViewObject();
      //  String unit=new String;
      //String unit[];
      List <String> unit = new ArrayList<String>();
    if(vo!=null){
        Row r[] = vo.getAllRowsInRange();  // here we get only 25 records
        for (int i = 0; i < r.length; i++) {
            String check = (String)r[i].getAttribute("Tyorn");
            if(check.equals("Y")){
                String temp  = (String)r[i].getAttribute("UnitCode");
                unit.add(temp);
               }
        }
    } */
    DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
    DCIteratorBinding itr = bindings.findIteratorBinding("CmUserUnitAccessVu1VO1Iterator");
    ViewObject vo = itr.getViewObject();
    //  String unit=new String;
    //String unit[];
    List<String> unit = new ArrayList<String>();
    if (vo != null) {
        //AdfFacesContext.getCurrentInstance().addPartialTarget(this.getT2());
        RowSetIterator r = vo.createRowSetIterator("new");
        //Row r[] = vo.get
        if (r != null) {
            r.reset();
            while (r.hasNext()) {
                Row currow = r.next();
                // currow.setAttribute("Tyorn", "N");
                String check = (String)currow.getAttribute("Tyorn");
                if (check.equals("Y")) {
                    String temp = (String)currow.getAttribute("UnitCode");
                    unit.add(temp);
                }
            }
            r.closeRowSetIterator();

        }
    }

Monday, June 4, 2018

ADF: Update model in value change listener

refer below lik
http://www.rsantrod.com/2016/08/adf-update-model-in-value-change.html

-- this is the example

    public void popNewProducts(ValueChangeEvent vce) {
//       
     vce.getComponent().processUpdates(FacesContext.getCurrentInstance());

        if (this.getSor2().getValue().equals("N")) {
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            //String catCode = (String)this.getCatCodeId().getValue();
            String catCode = (String)vce.getNewValue();
            HashMap<String, String> hm = new HashMap<String, String>();
            hm = (HashMap<String, String>)resolveExpression("#{pageFlowScope.ParamsBean.parm_obj}");
            System.out.println("hm==" + hm);
            String vcomp_mode = hm.get("COMP_CODE");
            BindingContext bindingContext = BindingContext.getCurrent();
            DCDataControl dc = bindingContext.findDataControl("AppModuleAMDataControl");
            AppModuleAMImpl appM = (AppModuleAMImpl)dc.getDataProvider();
            String query = "select distinct a.prod_code\n" +
                "from pi_product_mst a,pi_prod_price_defn b\n" +
                "where a.prod_code = b.prod_code\n" +
                "and a.prod_id = b.prod_id\n" +
                "and a.comp_code = ?\n" +
                "and a.cat_code = ?\n" +
                "and b.prod_price is not null\n" +
                "and nvl(a.active_yn,'Y') = 'Y'";

            DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
            DCIteratorBinding dcItteratorBindings1 = bindings.findIteratorBinding("PiProdPriceDefnVO2Iterator");
            ViewObject voDtl = dcItteratorBindings1.getViewObject();
            //System.out.println("before create");
            voDtl.createRow();
            System.out.println("after create");
            pstmt = appM.getDBTransaction().createPreparedStatement(query, 1);
            try {
                pstmt.setString(1, vcomp_mode);
                pstmt.setString(2, catCode);
                rs = pstmt.executeQuery();

                int x = 1;
                if (voDtl.getRowCount() > 0) {
                    System.out.println("greter than zero");
                    while (voDtl.hasNext()) {
                        System.out.println("Inside while");
                        voDtl.removeCurrentRow();
                        System.out.println(x);
                        x++;
                    }

                    voDtl.first();
                    voDtl.removeCurrentRow();

                }
                while (rs.next()) {
                    System.out.println("voDtl " + voDtl);
                    //Row r = appM.getPiProdPriceDefnVO2().createRow();
                    Row r = voDtl.createRow();
                    String vprodCode = rs.getString(1);
                    System.out.println(r + "  r " + vprodCode);
                    r.setAttribute("ProdCode", vprodCode);

                }
                AdfFacesContext.getCurrentInstance().addPartialTarget(t1);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

Implementing Conditional Insert, Update, and Delete Allows for View Objects

Implementing Conditional Insert, Update, and Delete Allows for View Objects
User's of Oracle Forms are familiar with the declarative "data block" settings for:
  • Insert Allowed? [Y|N]
  • Update Allowed? [Y|N]
  • Delete Allowed? [Y|N]
The BC4J framework does not (yet) have declarative view object settings for these, however we provide the framework methods that you can override to conditionally decide whether you want to allow insert, update, or delete on a view object. In a nutshell...
  • To disallow insert, throw a JboException (or any subclass of it) from an overridden create() method in the ViewRowImpl class
  • To disallow update, throw a JboException from an overridden setAttributeInternal() method in the ViewRowImpl class
  • To disallow delete, throw a JboException from an overridden remove() method in the ViewRowImpl class
  • To give clients (like JClient, JSP, UIX, etc.) feedback on the updateability of individual attributes in a conditional/custom way, override the isAttributeUpdateable() method and return true/false as appropriate.
Since BC4J is a framework, one of the most powerful things you can do is extend the framework to do that it doesn't already. BC4J gives you powerful building-blocks to do this. One of the key ones is the framework support for custom name/value-pair metadata properties that can be associated with Entity Objects, EO Attributes, View Objects, VO Attributes, or Application Modules.
The class below illustrates a custom subclass of oracle.jbo.server.ViewObjectImpl that checks whether the user has set custom metadata properties on their view objects named InsertAllowed, UpdateAllowed, and DeleteAllowed, and then exposes getter/setter methods to allow the programmer to get the status of these settings.
package otn.howto.fwkext;
import oracle.jbo.server.ViewObjectImpl;
import oracle.jbo.Row;
import oracle.jbo.*;
public class CustomViewObjectImpl extends ViewObjectImpl  {
  private static final String YES = "y";
  boolean insertAllowed;
  boolean updateAllowed;
  boolean deleteAllowed;
  public boolean isInsertAllowed() { return insertAllowed; }
  public boolean isUpdateAllowed() { return updateAllowed; }
  public boolean isDeleteAllowed() { return deleteAllowed; }
  public void setInsertAllowed( boolean value ) { insertAllowed = value; }
  public void setUpdateAllowed( boolean value ) { updateAllowed = value; }
  public void setDeleteAllowed( boolean value ) { deleteAllowed = value; }
  protected void create() {
    super.create();
    String insProp = (String)getProperty("InsertAllowed");
    String updProp = (String)getProperty("UpdateAllowed");
    String delProp = (String)getProperty("DeleteAllowed");
    // If property not specified, default allowability to true.
    setInsertAllowed(insProp == null || insProp.equalsIgnoreCase(YES));
    setUpdateAllowed(updProp == null || updProp.equalsIgnoreCase(YES));
    setDeleteAllowed(delProp == null || delProp.equalsIgnoreCase(YES));
  }
}
The following custom subclass of the base oracle.jbo.server.ViewRowImpl class overrides the methods mentioned above, and generically enforces the insert-allowed, update-allowed, and delete-allowed behaviors for any view object that subclasses from this custom framework subclass, instead of extending from the default oracle.jbo.server.ViewRowImpl:
package otn.howto.fwkext;
import oracle.jbo.server.*;
import oracle.jbo.AttributeList;
import oracle.jbo.*;
/*
 * Requires use of CustomViewObjectImpl
 */
public class CustomViewRowImpl extends ViewRowImpl  {
  protected boolean hasEntities() {
    return getEntity(0) != null;
  }
  /*
   * By convention, we'll say that the state of this VO row
   * is the state of its first entity object.
   * 
   * Only makes sense to call this if VO row has entities
   */
  protected byte getViewRowStatus() {
    return getEntity(0).getPostState();
  }

  public boolean isAttributeUpdateable(int index) {
    if (hasEntities()) {
      byte status = getViewRowStatus();
      switch (status) {
        case Entity.STATUS_NEW:
        case Entity.STATUS_INITIALIZED: {
          if (!getVO().isInsertAllowed()) return false;
          else break;
        }
        case Entity.STATUS_UNMODIFIED:
        case Entity.STATUS_MODIFIED: {
          if (!getVO().isUpdateAllowed()) return false;
          else break;
        }
      }
    }
    return super.isAttributeUpdateable(index);
  }
  protected void setAttributeInternal(int index, Object val) {
    if (hasEntities()) {
      byte status = getViewRowStatus();
      switch (status) {
        case Entity.STATUS_NEW:
        case Entity.STATUS_INITIALIZED: {
          if (!getVO().isInsertAllowed()) 
            throw new JboException("no inserts");
          else break;
        }
        case Entity.STATUS_UNMODIFIED:
        case Entity.STATUS_MODIFIED: {
          if (!getVO().isUpdateAllowed())
            throw new JboException("no updates");
          else break;
        }
      }
    }
    super.setAttributeInternal(index, val);
  }
  public void remove() {
    if (!hasEntities() || getVO().isDeleteAllowed()) {
      super.remove();
    }
    else {
      byte status = getViewRowStatus();
      if (status == Entity.STATUS_NEW || status == Entity.STATUS_INITIALIZED) {
        super.remove();
      }
      else {
        throw new JboException("Delete not allowed in this view");
      }
    }
  }
  protected void create(AttributeList nvp) {
    if (getVO().isInsertAllowed()) {
      super.create(nvp);
    }
    else {
      throw new JboException("Insert not allowed in this view");
    }
  }
  private CustomViewObjectImpl getVO() {
    return (CustomViewObjectImpl)getViewObject();    
  }
}
With these two classes in place, these are the steps to take advantage of them:
  1. On the "Java" tab of your view object, click the (Extends) button and set the View Object Class to otn.howto.fwkext.CustomViewObjectImpl and the View Row Class to otn.howto.fwkext.CustomViewRowImpl
  2. On the "Properties" tab, add custom properties like InsertAllowed with a value of N, for example, to disallow inserts for this view object
To make these custom framework subclasses your global defaults, you can visit the Tools | Preferences... dialog and visit the "Business Components" / "Base Classes" category to set the IDE-wide defaults. In the JDeveloper 9.0.4 release, these defaults can also now be set at the project level by clicking "Edit..." from the right-mouse menu on your *.jpx file in the project.

Not to update in query mode then override isAttributeUpdateable at VORowImpl class

ex:2

    public void setNewRowState(byte b) {
        //super.setNewRowState(b);
        if (b != Row.STATUS_INITIALIZED || getNewRowState() != Row.STATUS_NEW) {
         super.setNewRowState(b);
         }
    }
   
    protected boolean hasEntities() {
        return getEntity(0) != null;
      }
      /*
       * By convention, we'll say that the state of this VO row
       * is the state of its first entity object.
       *
       * Only makes sense to call this if VO row has entities
       */
      protected byte getViewRowStatus() {
        return getEntity(0).getPostState();
      }

    public boolean isAttributeUpdateable(int i) {
        Boolean update = super.isAttributeUpdateable(i);
       // System.out.println(" hasentiies "+hasEntities());
           
        if (hasEntities()) {
            byte status = getViewRowStatus();
            //System.out.println("status "+ status);
            //System.out.println(Entity.STATUS_NEW +" Entity.STATUS_MODIFIED "+Entity.STATUS_MODIFIED+" "+Entity.STATUS_UNMODIFIED);
            switch (status) {
             case Entity.STATUS_UNMODIFIED:
             case Entity.STATUS_MODIFIED:
                {
                    //System.out.println("inside status modified");
                    if (this.getTransApproved() != null || this.getTransApproved().equals("Y")) {
                        if (i == this.findAttrAndGetIndex("ValidToDt")) {
                            // System.out.println(i+" this.findAttrAndGetIndex(\"ValidToDt\") "+this.findAttrAndGetIndex("ValidToDt"));
                            return update;
                        }
                        return false;

                    }else break;
                }
             // 
                // return super.isAttributeUpdateable(i);
            }
        }
        return update;
    }

==================
ex:1
    public boolean isAttributeUpdateable(int i) {
        Boolean update = super.isAttributeUpdateable(i);
       // System.out.println(" hasentiies "+hasEntities());
         
        if (hasEntities()) {
            byte status = getViewRowStatus();
            //System.out.println("status "+ status);
            //System.out.println(Entity.STATUS_NEW +" Entity.STATUS_MODIFIED "+Entity.STATUS_MODIFIED+" "+Entity.STATUS_UNMODIFIED);
            switch (status) {
             case Entity.STATUS_UNMODIFIED:
             case Entity.STATUS_MODIFIED:
                {
                    //System.out.println("inside status modified");
                    if (this.getTransApproved() != null || this.getTransApproved().equals("Y")) {
                        if (i == this.findAttrAndGetIndex("ValidToDt")) {
                            // System.out.println(i+" this.findAttrAndGetIndex(\"ValidToDt\") "+this.findAttrAndGetIndex("ValidToDt"));
                            return update;
                        }
                        return false;

                    }else break;
                }
             // 
                // return super.isAttributeUpdateable(i);
            }
        }
        return update;
    }
==============



ex:2
public boolean isAttributeUpdateable(int i) {
        Boolean update = super.isAttributeUpdateable(i);
        if (this.getTransApproved()!=null || this.getTransApproved().equals("Y")){
            if ( i==this.findAttrAndGetIndex("ValidToDt")){
               // System.out.println(i+" this.findAttrAndGetIndex(\"ValidToDt\") "+this.findAttrAndGetIndex("ValidToDt"));
                        return update;
            }
            return false;
         
        }
       return update;
       // return super.isAttributeUpdateable(i);
    }