Wednesday, December 18, 2013

Force another EO to execute before an EO

Today, I experienced an interesting problem, I want to post another EO while executing an EO.

Example Problem is,

Consider a table Employee & EmployeeRel

Here while creating the an EmployeeRel record, I may choose an existing employee or create a new employee and set the s_empId., But If we do so, we will get the Integrity constraint exception, because the EmployeeRel record insert query is executed before the new Employee insert query.(We are not using association here for the new Employee)

So, We need to execute the new Employee insert query before EmployeeRel record. ADF framework allows us to use the life cycle method PostChanges() to forece the new Employee insert query execution. 

So override the postChanges() in the EmployeeRelImpl as follows,

    public void postChanges(TransactionEvent e) {
      if ((getPostState() == STATUS_NEW) || (getPostState() == STATUS_MODIFIED)) {
        EmployeeImpl secondEmp = getSecondEmployee(this.getSEmpId());
        if (secondEmp != null) {
          if (secondEmp .getPostState() == STATUS_NEW) {
            secondEmp .postChanges(e);
          }
        }
      }
      super.postChanges(e);
    }
    
    private PartyImpl getSecondEmployee(Number secondEmpId){
        Key key=EmployeeImpl .createPrimaryKey(secondEmpId);
        return (EmployeeImpl )EmployeeImpl .getDefinitionObject().findByPrimaryKey(getDBTransaction(), key);            
    }


Here is the sample DB script, I've used for my sample.

create table Emp(name varchar(20),emp_id number(10) primary key);
create table Emp_rel(rel_id number(10),f_empid number(10) REFERENCES Emp(emp_id),s_empid number(10) references Emp(emp_id));



  

Monday, December 9, 2013

ADF Association composition behaviors


If we select Implement cascade delete operation,
  • First it will generate delete query on the child entities and invoke the delete query.
  • Next it will generate delete query on the parent entity and invoke the delete query.
  • Then it will issue commit.

If we select optimize for Database cascade delete operation and in the foreign key ON DELETE CASCADE
  •  First it will generate delete query on the parent entity and invoke the delete query
  •  While deleting the parent record, it will delete child the child records at the DB level as we have implemented ON DELETE CASCADE.
  • It will issue commit.
  • It will clear the child entities from the cache for that parent record.

If we select optimize for Database cascade delete operation and in the foreign key we don’t set ON DELETE CASCADE
  • First It will generate delete query on the parent entity and invoke the delete query.
  • While deleting the parent record, it will throw Database constraint exception as we have not implemented ON DELETE CASCADE and SQL Exception will be thrown.

If we select Cascade update key attributes,
·         When updating the parent key attributes, it will update the child record’s foreign key attributes.

If we don’t select Cascade update key attributes, it will throw exceptions while trying to update the parent records primary key.

If we select update Top level history columns, it will update the parent records history columns when we are trying to add/update child records.

If we select Lock level to Lock Container, While updating the child record it will lock the immediate parent record.

If we select Lock level to Lock Container, While updating the child record it will lock the all the parent records in the hierarchy.

Sunday, December 1, 2013

Refactoring DataBindings.cpx file and Having Multiple cpx files

I found some interesting facts while I was playing with DataBindings.cpx file this weekend and I'm blogging them now after a long time.
  • Renaming the default DataBindings.cpx file.
  • Having more than one DataBindings file in a project.
       As you know the DataBindings.cpx file plays a vital role in the ADF Model layer, which is used to create the BindingContext for the Web Application by ADFBindingFilter and this stores the meta info about page defintions mappings to create the Binding Container for ADF data bound pages and DataControl usages to find the appropriate AppModules and ErrorHanler config,etc.

       JDeveloper does not provide declarative facility to rename or move the DataBindings.cpx file. To rename or move the DataBindings.cpx file, just create the new one and delete the existing one. While doing this don't forgot to update the adfm.xml file which is the registry of registries and always have the id property is same as the DataBindings cpx file name otherwise you will get error message  "DataControl is not found".

For example if you are renaming the cpx file from DataBindings.cpx to MyDataBindings.cpx, update the id as follows.

DataBindings.cpx file

<?xml version="1.0" encoding="UTF-8" ?>

<Application xmlns="http://xmlns.oracle.com/adfm/application"
             version="11.1.1.61.92" id="DataBindings" SeparateXMLFiles="false"
             Package="view" ClientType="Generic">
.........................
.........................
</Application>

MyDataBindings.cpx

<?xml version="1.0" encoding="UTF-8" ?>
<Application xmlns="http://xmlns.oracle.com/adfm/application"
             version="11.1.1.61.92" id="MyDataBindings" SeparateXMLFiles="false"
             Package="view" ClientType="Generic">
.........................
.........................
</Application>

         If you want to have more than one DataBindings.cpx file in a project, then  add the entries in the adfm.xml file, because ADFBindingFilter looks for the cpx files in the adfm.xml file. Cpx file names should be unique within the project.

Sample adfm.xml for multiple cpx files.

<?xml version="1.0" encoding="UTF-8" ?>

<MetadataDirectory xmlns="http://xmlns.oracle.com/adfm/metainf"                                      
                                                             version="11.1.1.0.0">
  <DataBindingRegistry path="view/DataBind1.cpx"/>
  <DataBindingRegistry path="view/DataBind1.cpx"/>
  <DataBindingRegistry path="view1/DataBind2.cpx"/>
</MetadataDirectory>



Note:  It is best practice to have cpx file name as DataBindings.cpx and having only one cpx file if we don't have special use cases.



Wednesday, March 28, 2012

ADF client side validations with inbuilt validation tags


Validate maximum length;
<af:inputText id="id0" value="12A" label="Maximum length validator">
<af:validateLength maximum="5"/>
</af:inputText>
Validate minimum length;
<af:inputText id="id00" value="12A" label="Minimum length validator">
<af:validateLength minimum="3"/>
</af:inputText>
Validate length range;
<af:inputText id="id01" value="12A" label="Length Range Validator">
<af:validateLength minimum="1" maximum="5"/>
</af:inputText>
Validate long range;
<af:inputText id="id2" value="10" label="Long Range Validator">
<af:validateLongRange minimum="5" maximum="50"/>
</af:inputText>
Validate double range;
<af:inputText id="id3" value="8.6" label="Double Range Validator">
<af:validateDoubleRange minimum="4.1" maximum="8.9"/>
</af:inputText>
Validate regular expression;
<af:inputText id="id4" value="9999" label="Regular Expression validation">
<af:validateRegExp pattern="[9]*"/ >
</af:inputText>
Date validation with filter condition;
<af:inputDate id="id5" value="2011-05-21"
label="Select a date, but not a Friday">
<af:convertDateTime pattern="yyyy-MM-dd"/>
<af:validateDateRestriction invalidDaysOfWeek="Fri"/>
</af:inputDate>
Validate date range;
<af:inputDate id="mdf3ee" value="2011-11-25" label="Submission period">
<af:convertDateTime pattern="yyyy-MM-dd"/>
<!-- Supports ISO date format strings of the form "yyyy-MM-dd" -->
<af:validateDateTimeRange minimum="2011-11-16" maximum="2011-12-16"/>
</af:inputDate>

Saturday, January 21, 2012

Set and get object into/from session

/**
* Method for setting an object in session
* @param name
* @param value
* @return null
*/
public static void setSessionValue(String name, Object value) {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request =
(HttpServletRequest)context.getExternalContext().getRequest();
HttpSession httpSession = request.getSession(false);
httpSession.setAttribute(name, value);
}
/**
* Method for getting an object from session
* @param null
* @return Object
*/
public static Object getSessionValue(String attName) {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request =
(HttpServletRequest)context.getExternalContext().getRequest();
HttpSession httpSession = request.getSession(false);
return httpSession.getAttribute(attName);
}

Friday, January 20, 2012

Some more usefull methods in ViewObjectImpl

1.getFilteredRows(java.lang.String attrName, java.lang.Object attrValue)
          Returns all rows in this collection whose attribute value matches the value being passed in attrValue.

 2.getRow(Key key)
          Returns the first row matching a given key.

 3.setCurrentRow(Row row)
          Designates a given row as the current row.
 getCurrentRow()
          Returns the current row of the iterator.

for more info
ViewObjectImpl API

Sunday, January 8, 2012

jdevloper not taking the latest changes – what to do?

Sometime when you do the changes and run the application the latest changes are not updated while running the application.
The culprit is the system folder.
{user_home}\system11.1.1.4.37.57.75\o.j2ee\drs\
has the exploded war file which will have the classes that is old. deleting the classes from the exploded directory would definitely fix the issue.

Enable FastSwap in Weblogic deployment to load java classes at runtime without relaoding the classloader

 Fast Swap
Specifies whether FastSwap deployment is used to minimize redeployment since Java classes are redefined in place without reloading the ClassLoader. For more information, see "Using FastSwap Deployment to Minimize Redeployment" in Deploying Applications to Oracle WebLogic Server.

Enable Class Redefinition
Select to enable FastSwap.

Refresh Interval
FastSwap checks for changes in application classes when an incoming HTTP request is received. Subsequent HTTP requests arriving within the number of seconds specified here will not trigger a check for changes. The first HTTP request arriving after the number of seconds specified here have passed, will cause FastSwap to perform a class-change check again.

Redefinition Task Limit
Specifies the number of redefinition tasks that will be retained by the FastSwap system. If the number of tasks exceeds this limit, older tasks are automatically removed.


The following types of changes are supported with FastSwap:
  • Addition of static methods
  • Removal of static methods
  • Addition of instance methods
  • Removal of instance methods
  • Changes to static method bodies
  • Changes to instance method bodies
  • Addition of static fields
  • Removal of static fields
  • Addition of instance fields
  • Removal of instance fields

Wednesday, December 8, 2010

JavaScipt Code to close a popup

var popup = AdfPage.PAGE.findComponent("popupId"); 
          if (popup.isPopupVisible() == true){
              popup.hide();
          }

How to invoke a JavaScript method from the managed bean

Jspx part
---------------
<f:view>
    <af:document id="d1">
     <![CDATA[
   <script>
      function greeter() {
         alert("Hello..");
         }
   }             
</script> ]]>
      <af:form id="f1">
        <af:commandButton text="commandButton 1" id="cb2"
                              partialSubmit="true"
                              action="#{ScriptCallerBean.cb2_action}"/>
      </af:form>
    </af:document>
</f:view>


managed bean coding
------------------------
import javax.faces.context.FacesContext;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;

public void caller(){
ExtendedRenderKitService extRenderKitSrvc = Service.getRenderKitService(FacesContext.getCurrentInstance(),ExtendedRenderKitService.class);
extRenderKitSrvc.addScript(FacesContext.getCurrentInstance(),"window.greeter()");
}

Friday, November 26, 2010

How to export commandLink in the table into excel

Hi Friends,
        Some of you may have this problem,The problem is While you are exporting collumn in the commandLink,in the excel sheet the commandLink collumn field will be empty.The reason is the export is only for components of type ValueHolder, which a command ink is not.
      So I solve this problem by using an output text inside the commandLink,and in the outputText field property I use the value property,but in the text property of the commandLink is empty.

sample coding,
   <af:commandLink actionListener="#{bindings.setCurrentRowWithKey.execute}"
          text=""  id="cl4" action="edit">
           <af:outputText value="#{row.DocumentName}" id="ot2"/>
    </af:commandLink>

Hi this will work in all versions of the JDeveloper,This is one of solution,I dont know whether  this is a correct solution or not.If any alternative solution,please post your comments             

Clearing Filter criteria in ADF Rich Table

Hi Friends,this is one of my use-case for removing the filter text in the table when clicking a command button.
I think you all like this scenario.

Logic is,
           ADF table filter uses SearchRegion binding, which genearly uses a All Queriable Attributes Criteria. It will apply the criteria on the View object. So we need to clear the criteria on the view object.

The Solution is,
        1.Bind a table in the Jspx to a managed bean,say summaryTable.
        2.In the Jspx page,use a commandButton and in its Action property call a method in the managed bean for eg: clearFilters()

        3.Type the following code in the method,
  public String clearFilters(){
      if (summaryTable != null){
      FilterableQueryDescriptor queryDescriptor =
                                        (FilterableQueryDescriptor)summaryTable.getFilterModel();
      if (queryDescriptor != null && queryDescriptor.getFilterCriteria() != null){
      queryDescriptor.getFilterCriteria().clear();
      summaryTable.queueEvent(new QueryEvent(summaryTable,queryDescriptor));
      }
      else{
          String message = "Have some problem in Clearing Filters. please try later";
          FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(message));
      }
      }
      return null;
  }


Now you run your application,type some filter text and click in the Button which will clear the filter text.
This example I tried in JDeveloper 11.1.1.2.0 . I hope it will work in all the versions of JDeveloper.If any problem post your comments or mail to felixandrew3@gmail.com

Thursday, November 25, 2010

How to invoke popup component programmatically in ADF

Hi All,
     Here is a sample solution for invoking the popup component from a method in the managed bean.

Solution.
     1.Create a button in the Jspx page.
     2.Create a popup componet inside the af|form (for eg:popup id=p1)   and bind the popup to a managed bean with name popup
     3.In the Action property of button,invoke a method in the managed bean( for eg.the method caller() )

In the backing bean code,

  public String caller(){
      showPopup(popup, null);
      return null;
 }
 public static void showPopup(RichPopup popup, UIComponent component) {
      FacesContext context = FacesContext.getCurrentInstance();
      String alignId = (component==null) ? null : component.getClientId(context);
      StringBuilder script = new StringBuilder();
      script.append("var popup = AdfPage.PAGE.findComponent('").append("p1").append("'); ")
              .append("if (!popup.isPopupVisible()) { ")
              .append("var hints = {}; ");
       if (alignId!=null) {
         script.append("hints[AdfRichPopup.HINT_ALIGN_ID] = '").append(alignId).append("'; ")
           .append("hints[AdfRichPopup.HINT_ALIGN] = AdfRichPopup.ALIGN_AFTER_START; ");
       }
        script.append("popup.show(hints);}");
        ExtendedRenderKitService erks =
          Service.getService(context.getRenderKit(), ExtendedRenderKitService.class);
        erks.addScript(context, script.toString());
       }
    
Hi, Onething note this works in JDeveloper 11.1.1.2.0  But I dont know how about in other version.I hope it will work in all versions,

         If it dosn't works post your comment or mail to : felixandrew3@gmail.com . I will send you the sample code.

Thursday, October 21, 2010

How to hide the spin bar in the carousel componet

thanks to Frank,
Use Skining to hide this spin bar in the carousel component,


In the css file,
af|carousel::spin-bar{    
     visibility: hidden;     
}
af|carousel::spin-h-previous-icon-style{
     visibility: hidden;
}
af|carousel::spin-h-next-icon-style{
   visibility: hidden;
}
af|carousel::spin-info{
     visibility: hidden;
}

How to use the Carousel component in 2 seconds

1.Craete a .jspx file
2.Create a View Object DataControl
3.Drag and Drop the view object from the DataControl to the jspx page
Now Choose carousel from  the following,
4.Choose carouselItem in the structure panel,and in the property inspecter of the carouselItem,for text attribute  type #{item.employeeName}  // give any attribute of the view object in the place of employeeName
5.Now run the application
       
       

Wednesday, October 6, 2010

ADF 11g: contextInfo Implementation

     All component that we can add the contextInfo component to (column, commandLink,inputComboboxListOfValues, inputText, outputFormatted, outputText, selectOneChoice), have a facet called context.
    for example,let us use a ContextInfo component for a InputTextBox that displays some info about that.

Steps,
    1.Drag and drop a InputText component from the component palete
    2.Inside the InputTextBox right-click and choose Insert-Inside InputBox--->Jsf-Core--->Facet and choose context from the dropdown list
    3.Inside the Facet right-click and choose Insert-Inside Facet--->ContextInfo
    4.Inside the ContextInfo right-click and choose Insert-Inside-ContextInfo--->Adf Faces--->show Popup behaviour
    5.Drag and drop a Popup component in the AF:document in the structure panel,
    6.In the show popup behaviour give the popup id for the popup component.

Tuesday, September 28, 2010

AutoSuggestBehaviour in ADF

1.Create a text Box
2.Inside the text box drag and drop a autoSuggestBehaviour component
3.In the SuggestedItems create a managed bean for countrySuggester.getCountries
4.Now your Jsf will look like this,
<af:inputText label="Country" value="#{item.country}"
                                        columns="20" id="it5">
                <af:autoSuggestBehavior suggestedItems="#{countrySuggester.getCountries}"/>
        </af:inputText>

5.In the countrySuggester class make it as this,

import java.util.ArrayList;
import java.util.List;

import javax.faces.model.SelectItem;

public class CountrySuggester {

  private List<SelectItem> countries = new ArrayList<SelectItem>();

  public CountrySuggester() {
    super();
    countries.add(new SelectItem("Belgium"));
    countries.add(new SelectItem("Hungary"));
    countries.add(new SelectItem("Bulgaria"));
    countries.add(new SelectItem("India"));
    countries.add(new SelectItem("Indonesia"));
    countries.add(new SelectItem("United Kingdom"));
    countries.add(new SelectItem("United States of America"));
    countries.add(new SelectItem("Netherlands"));
    countries.add(new SelectItem("Nepal"));
    countries.add(new SelectItem("Namibia"));

  }
 
  public List<SelectItem> getCountries(String country) {
    List<SelectItem> items = new ArrayList<SelectItem>();
    for(SelectItem item:countries){
      if (item.getLabel().startsWith(country)) {
        items.add(item);
      }
    }
    return items;
  }
}

Guidelines for ADF Beginners

See the following links which demonstrates the Step by Step procedure for using ADF11g components

1.http://st-curriculum.oracle.com/obe/jdev/obe11jdev/ps1/ria_application/developriaapplication_long.htm
2.http://st-curriculum.oracle.com/obe/jdev/obe11jdev/ps1/boundedtaskflow/bounded_task_flow.html
3.http://st-curriculum.oracle.com/obe/jdev/obe11jdev/ps1/adf_richclient/adfrichclient.htm

Example for ADF FacesMessage

1.Create a Button component
2.In the Button Action proerty  bind it to the managed bean
3.In the  method type the following code.

        FacesContext fc = FacesContext.getCurrentInstance();
        FacesMessage message = new FacesMessage("Hi this is your message");
         fc.addMessage(null, message);