5 Ekim 2012 Cuma

Some useful ADF and JSF code for managed beans


In the following, you will find some handy code which can be used in managed beans.
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();
}

4 Ekim 2012 Perşembe

ADF Task Flow Oluşturmak

Örnek: Firma - Personel


  1. İlk olarak Configure checkbutton unchecked yapılarak custom paketler ile bir portal projesi oluşturulur.
  2. Bounded Task Flow->Company.xml
  3. Bu T.K. (Task Flow) içine CompanyDetails View, CompanyEdit View ve CompanyDetails'ten CompanyEdit'e "edit" flowu
  4. CompanyDetails View->CompanyDetails.jsff fragment dosyası oluşturulur.
  5. CompanyDetails.jsff içinde Düzenle butonu (action = edit) konur (Bu buton ile CompanyEdit view'a gidilir). Alt tarafa Personel, Mali Bilgiler, Projeler ve diğer bilgiler tab olarak gelir. Her tab bir veya birden fazla T.K.'da oluşur.
  6. CompanyDetails.jsff içinde firma bilgileri SQL ile getirilir. O kullanıcıya ait firmayı getirecek query için gerekli parametreyi alma: http://biravejava.blogspot.com/2012/10/adf-task-flowda-pagescope-variable-view.html linkinde belirtilmiştir.
  7. Personel tabı altında EmployeeList T.F. region olarak eklenir.
  8. EmployeeList T.F. -> EmployeeList View -> EmployeeList.jsff
  9. 2 yöntem: 1. si, EmployeeList.jsff içinde buton ile yeni bir popup açılır, bu popup içinde EmployeeEdit T.F. nun region ı olur. 2. si EmployeeList T.F. içinde EmployeeList View ve EmployeeEdit View olur, flow ile ulaşılır.
  10. Task Flow parametreleri ayarlanır.
  11. Task Flow'ların Security'de rolleri verilir!
  12. T.F. ardından dependent A.M. ile deploy edilip istediğimiz başka bir projede kullanılır.
  13. Deploy edilen jar, başka projede filesystem kaynağından, deploy PATH verilerek ulaşılır (jar'ın kendi değil, bulunduğu klasör!)

ADF Task Flow'da PageScope variable'ı View Object Query Classına atamak


You can make a JDeveloper model View Object (VO) use a data query that has a custom variable accessor in Java.  This is useful for cases where you want your where clause to select based on the current user name from the ADF Security context.
Go to the “Query” tab of your view object:

Add a new Bind Variable and make sure to specify “Expression” and give the value the Groovy expression “adf.object.viewObject.yourPropertyName”.  The “adf.object.viewObject” portion is essentially like saying “this object” and then it will call getYourPropertyName() to fetch the value:

Back in your query expression, refer to this new bind variable by its name but prepend “:” to indicate that it is a bind variable as shown above.
Select the “Java” tab of your view object and then click the pencil icon to edit the settings:

Select the “Generate View Object Class” and “Include bind variable accessors” options:

This will generate a new “.java” entry under your view object in the JDeveloper application navigator:

Finally, open that Java file and change the implementation of your get accessor as you wish.  In my case, I am simply returning the user name property from the ADF security context.  I also changed my set accessor to do nothing:

Example:
When you press the button on the screen it will count and display how many times you have pressed the button and counter will be different for each browser window or tab
//Method on the button
 public void doCounting(ActionEvent actionEvent) {
    
     Number value = (Number)getPageFlowScopeValue("myCounter");
     if (value.intValue() >= 0) {
         setPageFlowScopeValue("myCounter", value.intValue() + 1);
     }
      
     setManagedBeanValue("pageFlowScope.pFlowBean.counter",getPageFlowScopeValue("myCounter"));
 
 }
 //Method to set the value of page flow scope created on runtime
 public void setPageFlowScopeValue(String name, Number value) {
     ADFContext adfCtx = ADFContext.getCurrent();
     Map pageFlowScope = adfCtx.getPageFlowScope();
     pageFlowScope.put(name, value);
 }
 
//method to get the value of page flow scope created on runtime
 public Object getPageFlowScopeValue(String name) {
     ADFContext adfCtx = ADFContext.getCurrent();
     Map pageFlowScope = adfCtx.getPageFlowScope();
     Object val = pageFlowScope.get(name);
  
     if (val == null)
         return 0;
     else
         return val;
 }
 
//Methods used to get and set the values in a Managed bean
 public Object getManagedBeanValue(String beanName) {
     StringBuffer buff = new StringBuffer("#{");
     buff.append(beanName);
     buff.append("}");
     return resolveExpression(buff.toString());
 }
 
 public Object resolveExpression(String expression) {
     FacesContext facesContext = FacesContext.getCurrentInstance();
     Application app = facesContext.getApplication();
     ExpressionFactory elFactory = app.getExpressionFactory();
     ELContext elContext = facesContext.getELContext();
     ValueExpression valueExp = elFactory.createValueExpression(elContext, expression, Object.class);
     return valueExp.getValue(elContext);
 }
 
 
 public void setManagedBeanValue(String beanName, Object newValue) {
     StringBuffer buff = new StringBuffer("#{");
     buff.append(beanName);
     buff.append("}");
     setExpressionValue(buff.toString(), newValue);
 }
 
 public static void setExpressionValue(String expression, Object newValue) {
     FacesContext facesContext = FacesContext.getCurrentInstance();
     Application app = facesContext.getApplication();
     ExpressionFactory elFactory = app.getExpressionFactory();
     ELContext elContext = facesContext.getELContext();
     ValueExpression valueExp = elFactory.createValueExpression(elContext, expression, Object.class);
   
     Class bindClass = valueExp.getType(elContext);
     if (bindClass.isPrimitive() || bindClass.isInstance(newValue)) {
         valueExp.setValue(elContext, newValue);
     }
 }