Showing posts with label UIComponent. Show all posts
Showing posts with label UIComponent. Show all posts

Thursday, April 9, 2009

Some handy code for backing beans ( ADF & JSF )

Here some code which you can use in your backing beans, I use this code all the time. With this you can retrieve the data or actions from the ADF page definition or create new uicomponents with ADF definitions and some JSF methods.

I'll keep this page up to date. Let me know if you have some code.

// print the roles of the current user
for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {
System.out.println("role "+role);
}


// get the ADF security context and test if the user has the role users
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
if ( sec.isUserInRole("users") ) {
}
// is the user valid
public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated();
}
// return the user
public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName();
}


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

// get an ADF attributevalue from the ADF page definitions
AttributeBinding attr = (AttributeBinding)bindings.getControlBinding("test");
attr.setInputValue("test");

// get an Action or MethodAction
OperationBinding method = bindings.getOperationBinding("methodAction");
method.execute();
List errors = method.getErrors();

method = bindings.getOperationBinding("methodAction");
Map paramsMap = method.getParamsMap();
paramsMap.put("param","value") ;
method.execute();


// Get the data from an ADF tree or table
DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();

FacesCtrlHierBinding treeData = (FacesCtrlHierBinding)bc.getControlBinding("tree");
Row[] rows = treeData.getAllRowsInRange();

// Get a attribute value of the current row of iterator
DCIteratorBinding iterBind= (DCIteratorBinding)dcBindings.get("testIterator");
String attribute = (String)iterBind.getCurrentRow().getAttribute("field1");

// Get the error
String error = iterBind.getError().getMessage();


// refresh the iterator
bindings.refreshControl();
iterBind.executeQuery();
iterBind.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);

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

// Get the current row of a iterator , a different way
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), "#{bindings.testIter.currentRow.dataProvider}", TestHead.class);
TestHead test = (TestHead)ve.getValue(ctx.getELContext());

// Get a session bean
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), "#{testSessionBean}", TestSession.class);
TestSession test = (TestSession)ve.getValue(ctx.getELContext());

// main jsf page
DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
// taskflow binding
DCTaskFlowBinding tf = (DCTaskFlowBinding)dc.findExecutableBinding("dynamicRegion1");
// pagedef of a page fragment
JUFormBinding form = (JUFormBinding) tf.findExecutableBinding("regions_employee_regionPageDef");
// handle to binding container of the region.
DCBindingContainer dcRegion = form;



// return a methodexpression like a control flow case action or ADF pagedef action
private MethodExpression getMethodExpression(String name) {
Class [] argtypes = new Class[1];
argtypes[0] = ActionEvent.class;
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createMethodExpression(elContext,name,null,argtypes);
}

//
RichCommandMenuItem menuPage1 = new RichCommandMenuItem();
menuPage1.setId("page1");
menuPage1.setText("Page 1");
menuPage1.setActionExpression(getMethodExpression("page1"));

RichCommandButton button = new RichCommandButton();
button.setValueExpression("disabled",getValueExpression("#{!bindings."+item+".enabled}"));
button.setId(item);
button.setText(item);
MethodExpression me = getMethodExpression("#{bindings."+item+".execute}");
button.addActionListener(new MethodExpressionActionListener(me));
footer.getChildren().add(button);


// get a value
private ValueExpression getValueExpression(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createValueExpression(elContext, name, Object.class);
}
// an example how to use this
RichInputText input = new RichInputText();
input.setValueExpression("value",getValueExpression("#{bindings."+item+".inputValue}"));
input.setValueExpression("label",getValueExpression("#{bindings."+item+".hints.label}"));
input.setId(item);
panelForm.getChildren().add(input);



// catch an exception and show it in the jsf page
catch(Exception e) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}


FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, msgHead , msgDetail);
facesContext.addMessage(uiComponent.getClientId(facesContext), msg);


// reset all the child uicomponents
private void resetValueInputItems(AdfFacesContext adfFacesContext,
UIComponent component){
List items = component.getChildren();
for ( UIComponent item : items ) {

resetValueInputItems(adfFacesContext,item);

if ( item instanceof RichInputText ) {
RichInputText input = (RichInputText)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
} else if ( item instanceof RichInputDate ) {
RichInputDate input = (RichInputDate)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
}
}
}

// redirect to a other url
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse)ectx.getResponse();
String url = ectx.getRequestContextPath()+"/adfAuthentication?logout=true&end_url=/faces/start.jspx";

try {
response.sendRedirect(url);
} catch (Exception ex) {
ex.printStackTrace();
}

// PPR refresh a jsf component
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);


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


// get the adf bc application module
private OEServiceImpl getAm(){
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, "#{data.OEServiceDataControl.dataProvider}",
Object.class);
return (OEServiceImpl)valueExp.getValue(elContext);
}


// change the locale
Locale newLocale = new Locale(this.language);
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(newLocale);


// get the stacktrace of a not handled exception
private ControllerContext cc = ControllerContext.getInstance();

public String getStacktrace() {
if ( cc.getCurrentViewPort().getExceptionData()!=null ) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cc.getCurrentViewPort().getExceptionData().printStackTrace(pw);
return sw.toString();
}
return null;
}


// get the selected rows from a table component
RowKeySet selection = resultTable.getSelectedRowKeys();
Object[] keys = selection.toArray();
List receivers = new ArrayList(keys.length);
for ( Object key : keys ) {
User user = modelFriends.get((Integer)key);
}

// get selected Rows of a table 2
for (Object facesRowKey : table.getSelectedRowKeys()) {
table.setRowKey(facesRowKey);
Object o = table.getRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
Row row = rowData.getRow();
Test testRow = (Test)((DCDataRow)row).getDataProvider() ;
}

Sunday, April 5, 2009

UIComponent has the function getFacetsAndChildren()


public Iterator getFacetsAndChildren() {
Iterator result;
int childCount = this.getChildCount(),
facetCount = this.getFacetCount();
// If there are neither facets nor children
if (0 == childCount && 0 == facetCount) {
result = EMPTY_ITERATOR;
}
// If there are only facets and no children
else if (0 == childCount) {
Collection unmodifiable =
Collections.unmodifiableCollection(getFacets().values());
result = unmodifiable.iterator();
}
// If there are only children and no facets
else if (0 == facetCount) {
List unmodifiable =
Collections.unmodifiableList(getChildren());
result = unmodifiable.iterator();
}
// If there are both children and facets
else {
result = new FacetsAndChildrenIterator(this);
}
return result;
}

March 10, 2009 Posted by careeritdevelopers | Uncategorized | , | No Comments

You can put a button on Template Def and do reset all inputText irrespective of pages, which implemented the same template

You can put a button on Template Def and do reset all inputText irrespective of pages, which implemented the same template.
Here you can design a Template that be applied to your entire project, from the same template you can access the all pages and its controls.
here is the sample code check it out , let me know your feedback.

private void resetValueInputItems(AdfFacesContext adfFacesContext, UIComponent component){
Map m ;

Iterator IC=component.getFacetsAndChildren();
while ( IC.hasNext() ) {
UIComponent item =IC.next();
if ( item instanceof RichInputText ) {
RichInputText input = (RichInputText)item;
if ( !input.isDisabled() ) {
System.out.println(input.getValue());
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
} else if ( item instanceof RichInputDate ) {
RichInputDate input = (RichInputDate)item;
System.out.println(”got Date”);
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
}
resetValueInputItems(adfFacesContext,item);
}

}

public void resetForm(ActionEvent actionEvent) {
AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
//resetValueInputItems(adfFacesContext,vvFormBinding );

}

March 10, 2009 Posted by careeritdevelopers | Uncategorized | , , , , , | No Comments

We can access all Controls page in ADF

Using this function you can do reset all inputtext in a page without knowing them.

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

public void resetForm(ActionEvent actionEvent) {
AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
resetValueInputItems(adfFacesContext,vvFormBinding );
testMap.put(”TEST”, “initial value”);
}

ADF Faces RC: Dynamic Table

Example

I have seen a number of posts in the forums concerning “How to create dynamic tables with RCF?”. As such, here is code example that creates an af:table with commandButtons that allow a user to dynamically add both rows and columns to a table, creating the oh so desired Ajax goodness.
Now, there a couple of things to note about this example. Namely, this example does not dynamically create components in a backing bean. Instead, a “best practices” approach is taken that enforces better separation between data and UI manipulation. Thus, the dynamic nature of the table is driven by updates to the model rather directly manipulating UI components.
JSPX File
Managed Bean: DynaTableBean.java
JAVA:
1.package com.thepeninsulasedge.view.dynatable.managed;
2.
3.import java.util.ArrayList;
4.import java.util.Collection;
5.import java.util.HashMap;
6.import java.util.List;
7.
8.import java.util.Map;
9.
10.import javax.faces.event.ActionEvent;
11.
12.import org.apache.myfaces.trinidad.model.CollectionModel;
13.import org.apache.myfaces.trinidad.model.SortableModel;
14.
15.public class DynaTableBean {
16. private SortableModel model;
17. private List columnNames;
18.
19.public DynaTableBean() {
20. columnNames = new ArrayList();
21. }
22.
23.// Add a new row to the model
24. public void addRow(ActionEvent evt){
25.if(!columnNames.isEmpty()){
26. Map newRow = createNewRowMap();
27.((List)model.getWrappedData()).add(newRow);
28.}
29.}
30.
31.// Get table model
32. public CollectionModel getCollectionModel(){
33. if(model == null){
34. model = new SortableModel(new ArrayList());
35. }
36. return model;
37. }
38.
39.// Get Column Names
40.public Collection getColumnNames(){
41. return columnNames;
42. }
43.
44.// Add column
45.public void addColumn(ActionEvent evt){
46. // Create new column name
47.String colName = (columnNames.size()+1) + “”;
48.// Add column name to list of names
49. columnNames.add(colName);
50. // Create new row
51. Map newRow = createNewRowMap();
52. // Add new column name to new row
53. newRow.put(colName,null);
54.// Update existing model
55.addColumnToCurrentModel(colName);
56.}
57.
58.// Add column to existing rows
59. private void addColumnToCurrentModel(String name){
60. List list = (List)model.getWrappedData();
61. for(Map row:list){
62. row.put(name,null);
63. }
64. }
65.
66. private Map createNewRowMap(){
67.Map newRow = new HashMap();
68. for(String colName:columnNames){
69. newRow.put(colName,null);
70. }
71.return newRow;
72.}
73.
74.}
IN BACKING BEAN
In backing I have set ‘DynamicTable’ to instantiate it manually, if the session bean might not be get right.
public void setDocument1(RichDocument document1) {
this.document1 = document1;
FacesContext ctx = FacesContext.getCurrentInstance();
Application app = ctx.getApplication();
ValueBinding bind = app.createValueBinding(”#{DynamicTable}”);//session bean name which has given in adf-config
Object o = bind.getValue(ctx);
DynaTableBeantemp = (DynaTableBean) o;
// temp.setUserName(”Test “);
// temp.setDateAndTime(Calendar.getInstance().getTime().toString());

}