Search This Blog

Saturday, November 21, 2009

General Method to get component in a ADF page

public static void findComponent(String componentId, ContextCallback callback) throws FacesException {
// -- Get current instance of the Faces context object
FacesContext facesCtx = FacesContext.getCurrentInstance();
// -- Get view root for current view or page
UIViewRoot root = facesCtx.getViewRoot();
// -- Invoke the CallBack on the component associated with componentId
boolean found = root.invokeOnComponent(facesCtx, componentId, callback);
// -- Throw exception if the target component is not found
if (!found) throw new FacesException(componentId + " not found!");
}

Wednesday, November 4, 2009

Useful ADF Function

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

Friday, October 30, 2009

Calling javascript function from backing bean

ADF Code


FacesContext context = FacesContext.getCurrentInstance();


ExtendedRenderKitService service = (ExtendedRenderKitService)Service.getRenderKitService(context, ExtendedRenderKitService.class);


service.addScript(context, "rowfocus("+ nCount +");");


javascript






Monday, May 25, 2009

Passing Arralist to package

Declaration of Types
-------------------------
create or replace type EMP_REC as object(
employee_id number(6),
last_name varchar2(25),
job_id varchar2(10))
=============================
create or replaceTYPE EMP_TABLE AS TABLE OF EMP_REC
=============================================
PACKAGE
create or replacePACKAGE BODY PK_PROD AS
PROCEDURE INSERT_PROD(p_iorec IN EMP_TABLE)
AS BEGIN
/* TODO implementation required */
FOR i IN 1..p_iorec.count LOOP
--get p_iorec(i).EMP_NAME
insert into productmaster values(p_iorec(i).employee_id, p_iorec(i).last_name, p_iorec (i).job_id);
END LOOP;
END INSERT_PROD;
PROCEDURE INSERT_PROD1 AS dt varchar2(20);
BEGIN /* TODO implementation required */
--select sysdate into dt from dual;
insert into productmaster values(2,'as', 'asd');
END INSERT_PROD1;
END PK_PROD;
==========================================
Java Code
========
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection(connectUrl, "HR", "oracle");
//Statement s = con.createStatement();
//ResultSet rs = s.executeQuery("Select * from employees");
//while (rs.next()){
//System.out.println(rs.getString(2));
//}
oracle.jdbc.OracleCallableStatement ocs = null;
oracle.sql.StructDescriptor structDesc =
StructDescriptor.createDescriptor("EMP_REC", con);
oracle.sql.ArrayDescriptor arrayDesc = ArrayDescriptor.createDescriptor("EMP_TABLE", con);
ArrayList arr = new ArrayList();
String[] objName;
ListIterator LItr = rows.listIterator();
while (LItr.hasNext()) {
// objName=(String[])LItr.next();
// Object [] singleobj = {
// objName[0],objName[1],objName[2]
// };
oracle.sql.STRUCT p1struct = new STRUCT(structDesc, con, (Object[])LItr.next()); //singleobj);
arr.add(p1struct);
}
oracle.sql.ARRAY newArray =new ARRAY(arrayDesc, con, arr.toArray());
ocs =
//(OracleCallableStatement)con.prepareCall("begin PK_PROD.INSERT_PROD1; end;");
(OracleCallableStatement)con.prepareCall("begin PK_PROD.INSERT_PROD(:1); end;"); ocs.setARRAY(1, newArray);
ocs.execute();
con.commit();
con.close();
ocs.close();

Wednesday, April 29, 2009

Two ways to assign detail view

import oracle.jbo.client.Configuration;
import oracle.jbo.*;
import oracle.jbo.domain.Number;
public class Test { public static void main(String[] args) {
String _am = "test.TestModule", _cf = "TestModuleLocal";
ApplicationModule am = Configuration.createRootApplicationModule(_am,_cf);
ViewObject lines = am.findViewObject("TopLevelLineItemView");
/* * You can use createAndInitRow() to supply the needed
* foreign key value to order at line row create time. */
Row newLine = lines.createAndInitRow(new NameValuePairs(new String[]{"Orderid"}, newObject[]{new Number(12345)}));
newLine.setAttribute("Itemid", "CRU-1234");
newLine.setAttribute("Quantity", new Number(1));
lines.insertRow(newLine);
/* * Or else, you can get a row of the parent view */
ViewObject orders = am.findViewObject("OrderView");
/* * Just use the first order in the view as an example */
Row existingOrder = orders.first();
/* * Then get the details iterator via the View Link attribute accessor */
RowIterator linesIter = (RowIterator)existingOrder.getAttribute("LinesItemsForOrder");
/* * Then use this iterator to create the new Line */
newLine = linesIter.createRow();
linesIter.insertRow(newLine);
newLine.setAttribute("Itemid", "XYZ-1234");
newLine.setAttribute("Quantity", new Number(4));
am.getTransaction().postChanges();
/* * Everything worked, so rollback so we don't actually create the new rows */ am.getTransaction().rollback();
Configuration.releaseRootApplicationModule(am,true);
}
}

Monday, April 20, 2009

Message Box In ADF & Validators

FacesMessage fm = new FacesMessage("Format of officel Email is incorrect"); FacesContext Context = FacesContext.getCurrentInstance(); Context.addMessage(null,fm);


public void checkEmail1(FacesContext facesContext, UIComponent uIComponent, Object object) {
// Add event code here...
String email=(String)object;
if(email.indexOf("@")<=0 email.indexOf(".")<=0) {
FacesMessage fm = new FacesMessage("Format of officel Email is incorrect"); FacesContext Context = FacesContext.getCurrentInstance(); Context.addMessage(null,fm);
//checkEmailFormat(facesContext,uIComponent,object,"Invalid office email");
}

Wednesday, April 15, 2009

ADF:Display Selected table row

public void ChangeListener(SelectionEvent selectionEvent) {
// Add event code here...
String amDef = "parameter.AppModule";
String config = "AppModuleLocal";
ApplicationModule am = Configuration.createRootApplicationModule(amDef, config); ViewObject vo = am.findViewObject("ParamMastView1");
ArrayList rows = new ArrayList();
Object[] ss=table1.getSelectedRowKeys().toArray();
RowKeySet rr=table1.getSelectedRowKeys();
Iterator it=rr.iterator
Object ky=it.next();
List kk=(List)ky;
ListIterator LItr = kk.listIterator();
Key kk1=(Key)LItr.next();
System.out.println(kk1);
Row[] selectedRows = vo.findByKey(kk1,1);
Row voRow = selectedRows[0];
System.out.println(" ["+voRow.getAttribute("ParamId")+"] "+ voRow.getAttribute("ParamName")+": "+
voRow.getAttribute("ParamValue"));
Object o = table1.getSelectedRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
Row row = rowData.getRow();
System.out.println(row.getAttribute(0));
RowKeySet rowSet = table1.getSelectedRowKeys();
Iterator rowSetIter = rowSet.iterator();
//DCBindingContainer bindings = this.getBindingContainer();
// DCIteratorBinding iter = bindings.findIteratorBinding("DeptView1Iterator");
DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
DCIteratorBinding iter = dcBindings.findIteratorBinding("MenuView1Iterator");
while (rowSetIter.hasNext()) {
List l = (List)rowSetIter.next();
Key key = (Key)l.get(0);
iter.setCurrentRowWithKey(key.toStringFormat(true));
Row r = iter.getCurrentRow();
System.out.println("selected dept " + r.getAttribute("MenuName"));
}

ADF:Calling PLSQL Package using jdbc connection

ArrayList rows = new ArrayList();
private static String connectUrl = "jdbc:oracle:thin:@10.201.1.32:1521:XE";
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection(connectUrl, "HR", "oracle");
//Statement s = con.createStatement();
//ResultSet rs = s.executeQuery("Select * from employees");
//while (rs.next()){
//System.out.println(rs.getString(2)); //}
oracle.jdbc.OracleCallableStatement ocs = null;
oracle.sql.StructDescriptor structDesc = StructDescriptor.createDescriptor("EMP_REC", con);
oracle.sql.ArrayDescriptor arrayDesc = ArrayDescriptor.createDescriptor("EMP_TABLE", con);
ArrayList arr = new ArrayList();
String[] objName;
ListIterator LItr = rows.listIterator();
while (LItr.hasNext()) {
// objName=(String[])LItr.next();
// Object [] singleobj = {
// objName[0],objName[1],objName[2]
// };
oracle.sql.STRUCT p1struct = new STRUCT(structDesc, con, (Object[])LItr.next()); //singleobj);
arr.add(p1struct);
}
oracle.sql.ARRAY newArray = new ARRAY(arrayDesc, con, arr.toArray());
ocs =
//(OracleCallableStatement)con.prepareCall("begin PK_PROD.INSERT_PROD1; end;");
(OracleCallableStatement)con.prepareCall("begin PK_PROD.INSERT_PROD(:1); end;"); ocs.setARRAY(1, newArray);
ocs.execute();
con.commit();
con.close();
ocs.close();

Changing view Objects & refreshing coresponding controls

FacesContext fctx = FacesContext.getCurrentInstance();
ValueBinding vb1 = fctx.getApplication().createValueBinding("#{bindings.ViewObj1Iterator}");
DCIteratorBinding UserListView = (DCIteratorBinding)vb1.getValue(fctx);
ViewObject vo = UserListView.getViewObject
vo.setNamedWhereClauseParam("PRole_id",1);
vo.executeQuery();

ADF Page Load event & post back

@PostConstruct

protected void OnLoad(){

if(!isPostback()){

System.out.println("test");

} }

private boolean isPostback() {

return Boolean.TRUE.equals(resolveExpression("#{adfFacesContext.postback}"));

}

private Object resolveExpression(String expression) {

FacesContext ctx = FacesContext.getCurrentInstance(); Application app = ctx.getApplication();

ValueBinding bind = app.createValueBinding(expression); return bind.getValue(ctx);

}