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

Friday, 17 June 2016

ADF: Controlling Bounded TaskFlow Progrmatically

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 have to pass 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;  
   }  

ADF: Daily use code

1. How  to make a current row, programmatically

public void onTableSelect(SelectionEvent selectionEvent) { // --- perform optional pre-processing here --- //RichTable _table = (RichTable ) selectionEvent.getSource();

CollectionModel model = (CollectionModel ) _table.getValue(); 
JUCtrlHierBinding_binding = (JUCtrlHierBinding)model.getWrappedData();
DCIteratorBinding iteratorBinding = _binding.getDCIteratorBinding();                   
Object _selectedRowData = _table´.getSelectedRowData(); 
JUCtrlHierNodeBindingnode = (JUCtrlHierNodeBinding) _selectedRowData ;
Key rwKey = node.getRowKey();
iteratorBinding.setCurrentRowWithKey(rwKey.toStringFormat(true));// --- perform optional post-processing here --- //}

2. How  to access memory scopes.


ADFContext.getCurrent().getApplicationScope();

ADFContext.getCurrent().getSessionScope();
AdfFacesContext.getCurrentInstance().getPageFlowScope();
ADFContext.getCurrent().getRequestScope();
ADFContext.getCurrent().getViewScope();
FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("isTrainCompDisabled", "true");


Application module sesion:
getSession().getUserData().put("USER_LOC", locationId);
adf.userSession.
userData.USER_LOC


3. Invoke  popup programaticaaly


public
void someAcion(ActionEvent event){ ...
FacesContext fctx = FacesContext.getCurrentInstance();
UIComponent launcher = (UIComponent) event.getSource();//get the client id of the launching component to//add as a hint argument to the popupString alignId launcher.getClientId(fctx);//Assuming that the popup has a JSF component binding//to the managed bean. Use the "binding" attribute of//the af:popup to build this binding referenceRichPopup popup = getPopup();RichPopup.PopupHints hints =
new
RichPopup.PopupHints();//align the popup with the component launching ithints.add(RichPopup.PopupHints.HintTypes.HINT_ALIGN_ID, launcher)hints.add(RichPopup.PopupHints.HintTypes.HINT_LAUNCH_ID, launcher)hints.add(RichPopup.PopupHints.HintTypes.HINT_ALIGN,RichPopup.PopupHints.AlignTypes.ALIGN_AFTER_END);popup.show(hints);}

 

4. To insert a new row in table at last and scroll the tabble to display the  new row
public


String newRowAction() {
CollectionModel tableModel =(CollectionModel) table1.getValue();
JUCtrlHierBinding adfModel =(JUCtrlHierBinding) tableModel.getWrappedData();
DCIteratorBinding dciter = adfModel.getDCIteratorBinding();//get the last row for the index and create a new row for the//user to editRow
lastRow = dciter.getNavigatableRowIterator().last();
Row newRow = dciter.getNavigatableRowIterator().createRow();
newRow.setNewRowState(Row.STATUS_INITIALIZED);
int
lastRowIndex =dciter.getNavigatableRowIterator().getRangeIndexOf(lastRow);
dciter.getNavigatableRowIterator().insertRowAtRangeIndex(lastRowIndex+1, newRow);// make the new row the current row of the tabledciter.setCurrentRowWithKey(newRow.getKey().toStringFormat(
true
));//table should have its displayRow attribute set to//"selected"AdfFacesContext.getCurrentInstance().addPartialTarget(table1);
return

null
;}

 
5. Binding container


import oracle.adf.model.BindingContext;
import oracle.binding.BindingContainer;...

BindingContext bindingContext = BindingContext.getCurrent();
BindingContainer bindings =bindingContext.getCurrentBindingsEntry();

 

6. Operation binding code
BindingContext bctx = BindingContext.getCurrent();
  BindingContainer bindings = bctx.getCurrentBindingsEntry();
  OperationBinding operationBinding =
       bindings.getOperationBinding("name_of_method_binding");
  //optional
  operationBinding.getParamsMap().put("argumentName1",value1);
  operationBinding.getParamsMap().put("argumentName2",value2);
  //invoke method
  operationBinding.execute();
  if (!operationBinding.getErrors().isEmpty()) {
     //check errors
     List errors = operationBinding.getErrors();
     Iterator<oracle.jbo.JboException> iterator = errors.iterator();
          while (iterator.hasNext()) {
              FacesMessage fm =
                  new FacesMessage(FacesMessage.SEVERITY_ERROR, iterator.next().getMessage(),
                                   null);
              FacesContext fctx = FacesContext.getCurrentInstance();
              fctx.addMessage(null, fm);
          }
  }
  //optional
  Object methodReturnValue = operationBinding.getResult();


7. Exception error in bean
 

public void onToolBarButtonAction(ActionEvent actionEvent) {
   JboException ex = new JboException("Just to tease you !!!!!");
   BindingContext bctx = BindingContext.getCurrent();
   ((DCBindingContainer)bctx.getCurrentBindingsEntry()).reportException(ex);
}

 

8. Redirect to another view programatically
 

public static void redirectToView(String viewId) {
    FacesContext fCtx = FacesContext.getCurrentInstance();
    ExternalContext eCtx = fCtx.getExternalContext();

    String activityUrl = ControllerContext.getInstance().getGlobalViewActivityURL(viewId);
    try {
        eCtx.redirect(activityUrl);
    } catch (IOException e) {
        e.printStackTrace();
        JSFUtils.addFacesErrorMessage("Exception when redirect to " + viewId);
    }
}

 

9.Getting the current row value
 

BindingContext ctx = BindingContext.getCurrent();
DCBindingContainer bc = (DCBindingContainer)ctx.getCurrentBindingsEntry();
DCIteratorBinding iterator = bc.findIteratorBinding("ViewObjectIterator");
Row r = iterator.getCurrentRow();
String empNameValue = (String)r.getAttribute("EmpName");

10.You can use the below code to refresh ADF page programatically

FacesContext context = FacesContext.getCurrentInstance()
String viewId = context.getViewRoot().getViewId()

ViewHandler vh = context.getApplication().getViewHandler()
UIViewRoot page = vh.createView(context, viewId);

context.setViewRoot(page);

Import the following classes

import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;


11. Operation binding code
 

            BindingContext ctx = BindingContext.getCurrent();
            DCBindingContainer bindings =
                (DCBindingContainer)ctx.getCurrentBindingsEntry();

            OperationBinding operation =
                bindings.getOperationBinding("addWhereClauseToOrderTypeVO");

            operation.getParamsMap().put("ou", valueChangeEvent.getNewValue());

            operation.execute();

            if (operation.getResult() != null) {
                Boolean result =
                    (Boolean)operation.getResult(); // cast to the expected result type
            }

 

12. Invoke CreateInsert from bean
 

BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
        OperationBinding operationBinding = bindings.getOperationBinding("CreateInsert");
        Object result = operationBinding.execute();
        if (!operationBinding.getErrors().isEmpty()) {
            return null;
        }
        DCIteratorBinding dciter =(DCIteratorBinding) bindings.get("YourView1Iterator");
        Row row=dciter.getCurrentRow();
        row.setAttribute("Attribute 0", "value0");
        row.setAttribute("Attribute 1", "value1");
        row.setAttribute("Attribute 2", "value2");
        row.setAttribute("Attribute 3", "value3");



13. Click a button frm bean
 

        FacesContext fctx = FacesContext.getCurrentInstance();
                    UIViewRoot uiViewRoot = fctx.getViewRoot();
                    UIComponent comp = getEditBtn();
                    if (comp != null && (comp instanceof UIXCommand)) {
                        String clientId = comp.getClientId(fctx);
                     
                        StringBuffer scriptBuffer = new StringBuffer();
                        scriptBuffer.append("var button = AdfPage.PAGE.findComponentByAbsoluteId('" + clientId + "');");
                        scriptBuffer.append("if (button != null){");
                        scriptBuffer.append("AdfActionEvent.queue(button);}");
                     
                        writeJavaScriptToClient(scriptBuffer.toString());
                    } else {
                        //log.severe("Component not Found !!!");
                    }

    private void writeJavaScriptToClient(String script) {
            FacesContext fctx = FacesContext.getCurrentInstance();
            ExtendedRenderKitService erks = null;
            erks =
              Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
            erks.addScript(fctx, script);

        }

 

Another approach:
FacesContext facesContext = FacesContext.getCurrentInstance();
UIViewRoot root = facesContext.getViewRoot();
//cb1 is the fully qualified name of the button
RichCommandButton button = (RichCommandButton) root.findComponent(“cb1?); // cb1 will be id of invisible button
ActionEvent actionEvent = new ActionEvent(button);
actionEvent.queue();  


3rd Approach:

UIComponent component = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
  UIComponent root = facesContext.getViewRoot();
  component = findComponent(root, "button_id");  // button_id will be id of invisible button
}

RichCommandButton button = (RichCommandButton)component;
ActionEvent actionEvent = new ActionEvent(button);
actionEvent.queue();   // we are queuing the all action programmaticly



14. Sequence EL
 

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


15. Duplicate Check
 

        ViewObjectImpl portalAcc = IwePortalUserVO();
        portalAcc.setApplyViewCriteriaName("CheckActiveUser");
        portalAcc.setNamedWhereClauseParam("email", emailID);
        portalAcc.executeQuery();

        if (portalAcc != null & portalAcc.getRowCount() > 0) {
         
                //record found
Return duplicate
            }
Else {
Return no duplicate.
}


16. Validation and reading from resource bundle

 

    public void it2_validator(FacesContext facesContext,
                              UIComponent uIComponent, Object object) {
        // Add event code here...
    private static final String RESOURCE_BUNDLE_NAME =
    "com.nintendo.moca.view.MocaViewControllerBundle";
        String value = (String)object;
        if ((value == null) || (value.length() == 0)) {
            return;
        }

        DCBindingContainer bc = ADFUtil.getBindingContainer();
        OperationBinding operation =
            bc.getOperationBinding("checkForDuplicateBatchId");
        operation.getParamsMap().put("batchId", value);

        operation.execute();

        if (operation.getResult() != null) {
            Boolean result =
                (Boolean)operation.getResult(); // cast to the expected result type
            if (result) {
                /////Reading from property file////

                ResourceBundle resourceBundle =
                    BundleFactory.getBundle(RESOURCE_BUNDLE_NAME);
                String duplication=null;;
                String duplicationMsg=null;
                if (resourceBundle != null) {

                     duplication =
                        resourceBundle.getString("ERR_DUPLICATION");
                    duplicationMsg =
                       resourceBundle.getString("ERR_DUPLICATION_MSG");

                }

                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                              duplication,
                                                              duplicationMsg));
            }


        }
    }


17.Print the roles of the current user
 

for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {
  System.out.println("role "+role);
}

Retrieving the ADF security context and test if the user has the role 'users'    
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
if ( sec.isUserInRole("users") ) {
}

Verify if the user is authenticated
public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated();
}

Getting the current user
public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName();
}

Getting the binding container
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();

Getting ADF attribute value from an ADF page definition
AttributeBinding attr = (AttributeBinding)bindings.getControlBinding("test");
attr.setInputValue("test");

Executing a  MethodAction
OperationBinding method = bindings.getOperationBinding("methodAction1");
method.execute();
List errors = method.getErrors();
method = bindings.getOperationBinding("methodAction2");
Map paramsMap = method.getParamsMap();
paramsMap.put("param","value")  ;
method.execute();

Getting data from an ADF tree or table
DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
FacesCtrlHierBinding treeData = (FacesCtrlHierBinding) dcBindings  .getControlBinding("tree");
Row[] rows = treeData.getAllRowsInRange();

Getting an attribute value from the current row of an iterator
DCIteratorBinding iterBind= (DCIteratorBinding)dcBindings.get("testIterator");
String attribute = (String)iterBind.getCurrentRow().getAttribute("field1");


Getting the current row of a iterator (another 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());


Getting the errors of an iterator
String error = iterBind.getError().getMessage();

Refresh an iterator
bindings.refreshControl();
iterBind.executeQuery();
iterBind.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);

All the rows of an iterator
Row[] rows = iterBind.getAllRowsInRange();
TestData dataRow = null;
for (Row row : rows) {
 dataRow = (TestData)((DCDataRow)row).getDataProvider();
}

 

Getting 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 binding
DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
Taskflow binding
DCTaskFlowBinding tf = (DCTaskFlowBinding)dc.findExecutableBinding("dynamicRegion1");
Page fragment's pagedef
JUFormBinding form = (JUFormBinding) tf.findExecutableBinding("regions_employee_regionPageDef");

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);
}

Adding Action and Action Listener to a command component
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);

Getting a ValueExpression
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);
}

Adding Groovy expression to a component's attribute
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 children's value of an UIComponent
private void resetValueInputItems(AdfFacesContext adfFacesContext,
                                UIComponent component){
  List 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 an 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 ADFcomponent
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);

Find a jsf component
private UIComponent getUIComponent(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
return facesCtx.getViewRoot().findComponent(name) ;
}

Getting an 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);


Getting stacktrace of an unhandled 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;
}

Getting the selected rows from a table component

RowKeySet rks = table.getSelectedRowKeys();
Iterator it = rks.iterator();
while (it.hasNext()) {
 List selectedRowKeyPath = (List)it.next();        
 Row row = ((JUCtrlHierNodeBinding)table.getRowData(selectedRowKeyPath)).getRow();
}

 

18. Logging
 

    private static final ADFLogger _logger =
                ADFLogger.createADFLogger(Search.class);
-Djbo.debugoutput=adflogger -Djbo.adflogger.level=FINE
LOG.entering(this.getClass().getName(), "uploadArtifact()");
LOG.exiting(this.getClass().getName(), "uploadArtifact()");

 

19. Execute query against ROW
 

//This is done against the rows in the cache(no DB hit)
vo.setQueryMode(ViewObject.QUERY_MODE_SCAN_ENTITY_ROWS);
ViewCriteria vc = vo.createViewCriteria();
ViewCriteriaRow vcr1 = vc.createViewCriteriaRow();
vcr1.setAttribute("LastName", "LIKE 'P%'");
vc.setCriteriaMode(ViewCriteria.CRITERIA_MODE_CACHE);//ViewCriteria.CRITERIA_MODE_QUERY | ViewCriteria.CRITERIA_MODE_
CACHE
vc.add(vcr1);
vo.applyViewCriteria(vc);
vo.executeQuery();
//1. ViewObject.QUERY_MODE_SCAN_DATABASE_TABLES
//2. ViewObject.QUERY_MODE_SCAN_VIEW_ROWS
//3. ViewObject.QUERY_MODE_SCAN_ENTITY_ROWS
ViewObject employeeVO = findViewObject("EmployeeDetails");
//Combine both database mode and entity cache query mode
employeeVO.setQueryMode(
ViewObject.QUERY_MODE_SCAN_DATABASE_TABLES |
ViewObject.QUERY_MODE_SCAN_ENTITY_ROWS);
//Execute query
employeeVO.executeQuery();

 

20. Create and set where clause
 

ViewObject vo = findViewObject("EmployeeDetails");
//Append WHERE cluase
vo.setWhereClause("FirstName = :bindVarFirstName");
//Define the bind variable
vo.defineNamedWhereClauseParam("bindVarFirstName", null,
null);
//Set the bind param value
vo.setNamedWhereClauseParam("bindVarFirstName","Tom");
vo.executeQuery();
//Define WHERE clause with JDB style bind var :NNN
String whereClause = "EmployeeEO.EMPLOYEE_ID = :1";
ViewObject employeeVO =findViewObject("Employees");
employeeVO.setWhereClause(whereClause);
employeeVO.setWhereClauseParam(1,empId);
employeeVO.executeQuery();

/////How to remove VC\\
ViewObjectImpl vo = (ViewObjectImpl)findViewObject
("EmployeeDetails");
vo.removeApplyViewCriteriaName
(viewCriteriaCNameToBeRemoved);



21.Programaticaly setting the filter

 

//For transient
ViewObject vo = findViewObject("EmployeeDetails");
//FullName is a transient attribute
vo.setSortBy("FullName desc");
vo.executeQuery();

//for persistent
ViewObject vo = findViewObject("EmployeeDetails");
vo.setOrderByClause("EmployeeEO.FIRST_NAME ASC");
vo.executeQuery();

 

22. Check for the duplication
 

//Get row to be checked from employee view object
ViewObject vo = findViewObject("EmployeeDetails");
Row row = vo.getCurrentRow();
//Set the condition for in memory filtering
RowMatch rm = new RowMatch("FirstName = 'William'");
// alternatively use rm.setWhereClause( condition );
if (rm.rowQualifies(row)) {
//Row exists with William as first name

ViewObject vo = findViewObject("EmployeeDetails");
RowMatch rm = new RowMatch("LastName = :bvLastName");
vo.getVariableManager().setVariableValue("bvLastName", "Grant");

 

23, Add multiple VC row
 

ViewObject vo = findViewObject("EmployeeDetails");
ViewCriteria vc = vo.createViewCriteria();
ViewCriteriaRow vcRow1 = vc.createViewCriteriaRow();
vcRow1.setAttribute("JobId", "IT_PROG");
vc.addElement(vcRow1);
ViewCriteriaRow vcRow2 = vc.createViewCriteriaRow();
vcRow2.setAttribute("DepartmentId", "= 10");
vcRow2.setConjunction(ViewCriteriaRow.VC_CONJ_AND |
ViewCriteriaRow.VC_CONJ_NOT);
vc.addElement(vcRow2);
vo.applyViewCriteria(vc);
vo.executeQuery();

 

24. Create a new row
 

//Get the view object
ViewObject countries = findViewObject("CountryVO");
// Create a row and fill in the columns.
Row row = countries.createRow();
row.setAttribute("CountryId", "IN");
row.setAttribute("RegionId", 3);
//Insert row in to the default row set
countries.insertRow(row);

 

25. Default time out web.xml
 

<context-param>
<description>Chooses how many tokens should be preserved at any one time.</description>
<param-name>org.apache.myfaces.trinidad.CLIENT_STATE_MAX_TOKENS</param-name>
<param-value>50</param-value>
</context-param>


26.To dump SOAP messages on the client side, use the following system property:
 
-Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true
 

27. Always insert new row at top, irrespective of selection of row.
 

        DCIteratorBinding dcib =
            (DCIteratorBinding)this.getBindings().get("VOIterator");
        RowSetIterator iter = dcib.getRowSetIterator();
        Row newRow = iter.createRow();
        iter.insertRowAtRangeIndex(0, newRow);
        iter.closeRowSetIterator();

 

28.//In managed bean class
public void createInsertAction(ActionEvent actevnt) {
//Call row create routine defined in AM using binding API
BindingContext bc = BindingContext.getCurrent();
DCBindingContainer dcb =
(DCBindingContainer)bc.getCurrentBindingsEntry();
OperationBinding op = dcb.getOperationBinding
("createDeptRow");
Row row = (Row)op.execute();
if (op.getErrors().size() == 0) {
//On success, keep the new row as active
ArrayList lst = new ArrayList(1);
lst.add(row.getKey());
getDataTable().setActiveRowKey(lst);
}
}

 

29. custom query listener
public void queryPerfromed(QueryEvent queryEvent) {
DCBindingContainer bc = (DCBindingContainer)BindingContext.
getCurrent().getCurrentBindingsEntry();
DCBindingContainer searchBinding = (DCBindingContainer)bc.
findExecutableBinding("DeptViewCriteriaQuery");
String criteriaName = JUSearchBindingCustomizer.
getCriteriaName(searchBinding);
ViewCriteria vc = JUSearchBindingCustomizer.
getViewCriteria(searchBinding, criteriaName);
ViewCriteriaRow vcr1 = vc.createViewCriteriaRow();
vcr1.setAttribute("DepartmentId","10");
vc.addRow(vcr1);
invokeQueryEventMethodExpression
("#{bindings.DeptViewCriteriaQuery.processQuery}",
queryEvent);
}
/**
* Invoke Query EL
*/
private void invokeQueryEventMethodExpression(String expression,
QueryEvent queryEvent) {
FacesContext fctx = FacesContext.getCurrentInstance();
ELContext elctx = fctx.getELContext();
ExpressionFactory efactory =
fctx.getApplication().getExpressionFactory();
MethodExpression me =
efactory.createMethodExpression(elctx, expression,
Object.class, new Class[] { QueryEvent.class });
me.invoke(elctx, new Object[] { queryEvent });

 

30. Requirement-How to programmatically navigate to next jsf page in taskflow.
 

Solution-
Following code show the sample code for navigating one jsf to another using code.
FacesContext context = FacesContext.getCurrentInstance();

context.getApplication().getNavigationHandler().handleNavigation(context,null,"controlflowcase");

 

31. Increase the  memory of server
 

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


32. code to apply VC through row
 

        EnrolleeRosterVOImpl vo = getEnrolleeRosterVO1();
        ViewCriteria vc1 =
            vo.getViewCriteriaManager().getViewCriteria("EnrolleeRosterVOCriteria");
        ViewCriteriaRow vcrow4 = vc1.createViewCriteriaRow();

        Calendar cal = Calendar.getInstance();
        cal.setTime((Date)criteriaMap.get("Birthdate"));
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(criteriaMap.get("Birthdate"));
        // Ouput "Wed Sep 26 14:23:28 EST 2012"
        String formatted = format1.format(cal.getTime());
        System.out.println(formatted);
        // Output "2012-09-26"
        // System.out.println(format1.parse(formatted));
        // Output "Wed Sep 26 00:00:00 EST 2012"*/
        ViewCriteriaItem vci4 = vcrow4.ensureCriteriaItem("Birthdate");
        vci4.setOperator(JboCompOper.OPER_CONTAINS);
        vci4.setValue(formatted);
        vcrow4.setConjunction(ViewCriteriaRow.VC_CONJ_AND);

        vc1.add(vcrow4);
        vo.applyViewCriteria(vc1);

 

33. Code to remove row
 

        EnrolleeRosterVOImpl vo = getEnrolleeRosterVO1();
        ViewCriteria v =
            vo.getViewCriteriaManager().getViewCriteria("EnrolleeRosterVOCriteria");
        String criteriaItemName = "Birthdate";
        if (v != null) {
            boolean found = false;
            while (v.hasNext() && !found) {
                ViewCriteriaRow vcr = (ViewCriteriaRow)v.next();
                if (vcr != null) {
                    ViewCriteriaItem[] vcis = vcr.getCriteriaItemArray();
                    if (vcis != null && vcis.length > 0) {
                        for (int j = 0; j < vcis.length && !found; j++) {
                            ViewCriteriaItem vci = vcis[j];
                            if (vci != null && criteriaItemName != null &&
                                criteriaItemName.equals(vci.getName())) {
                                found = true;
                                vci.setRemovable(true);
                                v.removeRow(vcr);
                                //  vci.setProperty( ViewCriteriaItemHints.CRITERIA_RENDERED_MODE_NEVER, true);
                                v.saveState();
                            }
                        }
                    }
                }
            }
        }

 

34. Java script to autopopulate value at specific pos
function filterForDates(evt) {
    var inputField = evt.getCurrentTarget();
    var oldValue = inputField.getSubmittedValue();
    var key = String.fromCharCode(evt.getKeyCode());
    var newValue = null;
    if (oldValue != null)
     newValue = oldValue + key;
    else
     newValue = key;
    if (newValue.length == 2){
     inputField.setValue(newValue + '/');
    }
    if (newValue.length == 5){
         inputField.setValue(newValue + '/');
    }
}
<af:clientListener method="filterForDates" type="keyDown"/>

 

35. Disabling key input in input date
<af:resource>
  function disableEntry(evt){
    evt.cancel();
  }
 </af:resource>

<af:inputDate label="Label 1" id="id1" readOnly="false"
  contentStyle="background-color:lightgray;">
  <af:clientListener method="disableEntry" type="keyDown"/>
</af:inputDate>


36. Exception error in model
    private void reportException(String errorMsg) {
        BindingContext bctx = BindingContext.getCurrent();
        ((DCBindingContainer)bctx.getCurrentBindingsEntry()).reportException(new Exception(errorMsg));
    }


37. Code to get multiple selected values:
JUCtrlListBinding listBindings = (JUCtrlListBinding)getBindings().get("DepartmentsView1");
        Object str[] = listBindings.getSelectedValues();
        StringBuilder saveMsg =
            new StringBuilder("<html><body><b><p style='color:red'>Selected Departments are-</p></b>");

        saveMsg.append("<ul>");
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
            saveMsg.append("<li> <b>" + str[i].toString() + "</b></li>");
        }

        saveMsg.append("</ul><br>");
        saveMsg.append("</body></html>");
        FacesMessage msg = new FacesMessage(saveMsg.toString());
        FacesContext.getCurrentInstance().addMessage(null, msg);


38. Code to rest selcted value in shuttle
BindingContainer bc = this.getBindings();
        JUCtrlListBinding listBindings = (JUCtrlListBinding)bc.get("DepartmentsView1");
        listBindings.clearSelectedIndices();

38. Long running query
function longRunningTask(evt) {
            var popup = AdfPage.PAGE.findComponentByAbsoluteId('longRunningPopup');
            if (popup != null) {
                AdfPage.PAGE.addBusyStateListener(popup, busyStateListener);
                evt.preventUserInput();
            }
        }

<af:popup childCreation="deferred" autoCancel="disabled"
                  id="longRunningPopup" contentDelivery="immediate"
                  binding="#{pageFlowScope.EmaHomeDynamicRegionManagedBean.longRunningPopup}">
          <af:dialog id="dialog1" closeIconVisible="false" type="none"
                     title="Loading Please Wait..."
                     binding="#{pageFlowScope.EmaHomeDynamicRegionManagedBean.dialog1}"
                     inlineStyle="width:200px; text-align:center;">
            <af:image source="wait_animation.gif"
                      id="i1"/>
          </af:dialog>
</af:popup>
 

39. Support for enter key
function onFieldEnterKey(inputEvent){
    if (event.getKeyCode() == AdfKeyStroke.ENTER_KEY) {
      //get the input text component from the event          
      var inputTextField = inputEvent.getSource();
      //the button is relative to the input text field so
      //relative search will do with no worrying about naming
      //containers
      var defaultButton = inputTextField.findComponent('cb1');
      //perform a partial submot
      var partialSubmit = true;
      AdfActionEvent.queue(defaultButton,partialSubmit);
      //Enter key does not need to go to server as we
      //queued a new event
       event.cancel();
   }
}
<af:panelFormLayout id="pfl1">
  <f:facet name="footer">
     <af:commandButton text="Print Field Value" id="cb1" partialSubmit="true"                                          
                       clientComponent="true" action="#{View1Bean.onButtonPressed}"/>
   </f:facet>
   <af:inputText label="Enter Field" id="it1" binding="#{View1Bean.inputTextField}">
      <af:clientListener method="onFieldEnterKey" type="keyUp"/>
   </af:inputText>
</af:panelFormLayout>


40.  How to invoke a servlet using goLink
            String serverNport = JsfUtils.getServerNPort();
            String contextPath = JsfUtils.getContextPath();
            internalUrl = serverNport + contextPath + "/pcpredirectservlet?";
  public static String getServerNPort()
  {
    ExternalContext ectx = getFacesContext().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
    String s = request.getRequestURL().toString();
    String[] s1 = s.split("/");
    String s2 = s1[0] + "//" + s1[2];
    return s2;
  }
  public static String getContextPath()
  {
    ExternalContext ectx = getFacesContext().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
    return request.getContextPath().toString();
  }

 

41. Binding refernce from bean
org.apache.myfaces.trinidad.util.ComponentReference
ComponentReference Usage:

private ComponentReference someUICompReference;

public UIComponent getSomeUIComponent(){
   return someUICompReference == null ?
            null : someUICompReference.getComponent();
}

public void setSomeUIComponent(UIComponent component) {
    someUICompReference =
        ComponentReference.newUIComponentReference(component);
}


42. Action event queue:
public void callAceVCE(ValueChangeEvent vce) {
if (vce.getNewValue() != null) {
//Code to call ActionEvent
FacesContext facesContext = FacesContext.getCurrentInstance();
UIViewRoot root = facesContext.getViewRoot();
/**Pass cb1(buttonId) if page is not in taskflow, else if page is inside region then pass rgionid:buttonId*/
RichCommandButton button = (RichCommandButton)root.findComponent("r1:cb1");
ActionEvent  actionEvent = new ActionEvent (button);
actionEvent.queue();
}
}


43: Set the VO bind variable using view accessor
@Override
    public void prepareRowSetForQuery(ViewRowSetImpl viewRowSetImpl) {
        RowSetIterator[] masterRows = viewRowSetImpl.getMasterRowSetIterators();
        if (masterRows != null && masterRows.length > 0 && masterRows[0].getCurrentRow() != null &&
            masterRows[0].getCurrentRow().getAttribute("ManagerId") != null) {
            Integer managerId = (Integer) masterRows[0].getCurrentRow().getAttribute("ManagerId");
            viewRowSetImpl.ensureVariableManager().setVariableValue("BindManagerId", managerId);
            System.out.println("ManagerID in bind Var-" + managerId);

        }
        super.prepareRowSetForQuery(viewRowSetImpl);
    }


44. Get binding container of different page
/**
     * @param data
     * @return
     */
    public Object resolvEl(String data) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        ValueExpression valueExp = elFactory.createValueExpression(elContext, data, Object.class);
        Object Message = valueExp.getValue(elContext);
        return Message;
    }
 
    /**Method to get BindingContainer of Another page ,pageUsageId is the usageId of page defined in DataBindings.cpx file
     * @param pageUsageId
     * @return
     */
    public BindingContainer getBindingsContOfOtherPage(String pageUsageId) {
        return (BindingContainer) resolvEl("#{data." + pageUsageId + "}");
    }


45. PPR The page using Apache utility class


        //refresh the Dashboard. ComponentUtils is a utility class of Apache MyFaces Trinidad
        //that performs an efficient relative search for components. Naming containers can be
        //navigated by leading colons ":". E.g. "::" means that the search is performed in the
        //parent of the component the search is started from. pd1 is the ID of the parent
        //componen, ae is the actionListner event object
        UIComponent dashBoard = ComponentUtils.findRelativeComponent(ae.getComponent(), "::pd1");
        if (dashBoard != null) {
            //PPR
            AdfFacesContext.getCurrentInstance().addPartialTarget(dashBoard);
        }


Source: Alok Ranjan

Monday, 13 June 2016

How to Change the Splash Screen?

Some times we need to change the splash screen(Loading icon) according to customer requirement. For that we need to add the below properties in .css file.
-------------------------------------------------------------------------------------------------------
af|document::splash-screen-content{
background-color:blue;
}

af|document::splash-screen-icon {

content:url("images/newLoadIcon.png");
}


Tuesday, 15 December 2015

Oracle ADF/Fusion Web Application Scopes

Def: Scope means how much time that object can be available. ie life time of an object
Usage: At run time, you pass data to pages by storing the needed data in an object scope where the page can access it. The object can be accessed from the scope using an EL expression.
Types: We have seven types of scopes. In which 3 are ADF scopes and remaining 4 are standered jsf/jspx scopes

Types of Scopes:
Four types of jsf/jspx scopes:
1. None scope: When you create objects that requires to define a scope. When you set the scope to none, meaning that it will not live in any particular scope, but will instead be instantiated each time it is referenced. You should set beans scope to none when it is referenced by another bean.
2. Request scope: It can be available once the request is raised and response is rendered back, Once the response rendered this scopes getting expired. It is the least scope, 
3.Session scope: The object can be available duration of the session,  whic is user instance specific. This scope can be used to maintain the user name in all pages,  which is read from database/LDAP server to avoid unnecessary queries.
4. Application scope: The object can be available duration of the application ie Whenever our application is running, this scope can be available. It can be used to maintain the static data irrespective of all users. This is the largest scope, Oracle is not recommended to use

Three types ADF scopes:
5. View scope: This scope can be available to particular jspx/jsff page. When the view id changes, this scope can expired.
6. PageFlow scope: In this the object can be available for the particular task flow only, Whenever task flow id changes this scope getting expired. If a task flow having hundred pages, this scope can be available in all hundred pages.
7. Backing bean scope: In most of the cases request scope and backing bean scopes are same. Only difference is that whenever we drag and drop task flow fragments as dynamic regions in that case we use backing bean scope. Because if drag and drop same task flow more than once, when we change the value in taskflow1 it will be reflected in taskflow2 also. So to avoid this type of problems we can use backing bean scope
Note: To be safe side, while drag and drop task flow as regions use backingbean scope.

Order of scopes(Min to max)
1. None Scope
2. requestScope/backingBeanScope
3. viewScope
4. pageFlowScope
5. sessionScope
6. applicationScope

Monday, 14 December 2015

Showing Static images as Carousel mode

Hi,
     Here I am showing how to add static images as Carousel mode to your project (No need to use any VO, EO and AM)

1). Add the required images to your project (Web Content/images(all your images are here)
2). Create the bean to that page, refer the above bean location to get the name of the images
3). Drag and drop Carousel and Carousel Item. In Carousel Item drag and drop Image. From Carousel, refer list of images found at #2
4). From Carousel item refer to the images location (#1) using the image name found from the bean.

Refer bean code from .jspx page

set Carousel properties are:-

 Final result look like this:-

Friday, 25 September 2015

Different types of data controls(DC) in ADF

1. ADFBC (default)
2. POJO DC
3. Webservices DC
4. URL services DC
5. Place holder DC
6. EJB Dc
7. JMX DC

Task flow components

1. Method call
2. parent action
3. router
4. save point restore
5. task flow call
6. task flow return activity
7.url view
8. view 
9. control flow case
10. wild card control flow rule

Friday, 10 July 2015

Welcome to Oracle Fusion Technologies

Hello friends,
 

My Inspiration to start this blog is to share my Oracle ADF and WebCenter experience, learnings from books, blogs. Ask my questions, resolve viewers' questions, present faced problems & their resolutions with you.

I have more than 2 years experience in Java, Oracle ADF and WebCenter Technologies.

Please excuse me if I have copied data from somewhere else, because I'm collecting it for me & all the viewers who needs it.

Thanks!
DevaRaju