ADF & JSF: Some handy code for backing beans

Following are the Some code which is very usefull when working in oracle ADF and JSF.Please go through


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



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


Read more-http://tamanmohamed.blogspot.com/2011/08/adf-jsf-some-handy-code-for-backing.html

How HashMap work in Java

“Hash Map is a Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.” … from Java API

After reading this definition, some question comes in my mind:

How hash map store data internally?
What happen when I try to store some new information in map?
How hash map find my data?

And when I tried to explore it, I find it more and more interesting.

HashMap has a static class named Entry which implements Map.Entry interface. The Entry class looks like:

static class Entry implements Map.Entry {
final Object key;
Object value;
final int hash;
Entry next;
Entry(int i, Object obj, Object obj1, Entry entry) {
value = obj1;
next = entry;
key = obj;
hash = i;

}
// Other methods

}

Every time we insert ainto hashmap using .put() method, a new Entry object is created (not true is some cases. if key already exists, then it just replace the value). Map internally used two data structures to manage/store data:

Array
Link List

This image shows how hashmap manage data. Here

Each index of array is a bucket
To identify the bucket for any , Hash map use key.hashCode() and perform some operation:
Bucket (index) =HashMap.indexFor (HashMap.hash(key.hashCode()), entryArray.length)
It means, two keys with different hashCode can fall under same bucket.
If a bucket is empty (table[i] is null) then the Entry object is simply inserted at ith position
table[i] = new Entry(hash, key, value, null)
If a bucket has some values, then the following algo is used:
Entry entry = table[i]

Table[i] = new Entry(hash,key,value,entry)

It means, the latest entry resides on the top of the bucket.

Load Factor- load factor is the ratio of number of keys to the length of an array. You will now have a threshold (the maximum number of elements that can be stored.The load factor is how full the HashMapis allowed to get before the capacity is doubled. The default load factor of 0.75 means that the HashMap is allowed to reach 75% capacity before it calls the rehash() method and doubles in capacity.The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed,so that the hash table has been increased double the number of buckets.

Generally the default load factor of a hashtable=0.75″ is if the hashtable is 75% full, then it will be re-hashed twice of the initial capacity.
Higher values decrease the space overhead but increase the lookup cost. The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

RACE CONDITION ON HASHMAP IN JAVA

Race condition exists while resizing hashmap in Java. If two threads, at the same time, find that Hashmap needs resizing, they both try resizing the hashMap.
In the process of resizing of hashmap, the element in bucket(which is stored in linked list) get reversed in order during the migration to new bucket, because java hashmap doesn’t append the new element at tail, instead it appends the new element at head to avoid tail traversing.
If race condition happens then you will end up with an infinite loop.

WHAT WILL HAPPEN IF TWO DIFFERENT HASHMAP KEY OBJECTS HAVE SAME HASHCODE?
COLLISION OCCURS-Since hashcode() is same, bucket location would be same and collision occurs in hashMap.Since HashMap use a linked list to store in bucket, “Key and Value” object will be stored in next node of linked list.

COLLISION RESOLUTION

We can find the bucket location by calling the hasCode function on the key object.After finding bucket location, we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in HashMap.

 

 

 

Ref- http://mkbansal.wordpress.com/2010/06/24/hashmap-how-it-works/