Thursday, December 6, 2012

Oracle ADF Ready To Use Sample Codes

*********Add Faces Message*********
FacesContext facesContext = FacesContext.getCurrentInstance();

facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, rb.getString("reqEmail"),null));

*********To Show Rich Popup*********
private RichPopup richPopup;
UIComponent source = (UIComponent)actionEvent.getSource();
String alignId = source.getClientId(facesContext);
RichPopup.PopupHints hints = new RichPopup.PopupHints();
hints.add(RichPopup.PopupHints.HintTypes.HINT_ALIGN_ID, source).add(RichPopup.PopupHints.HintTypes.HINT_LAUNCH_ID,
source).add(RichPopup.PopupHints.HintTypes.HINT_ALIGN,RichPopup.PopupHints.AlignTypes.
ALIGN_START_AFTER);
richPopup.show(hints);

*********To get Application Module Connection Object*********
ELContext elContext = null;
ValueExpression valueExp = null;
try {
            FacesContext fc = FacesContext.getCurrentInstance();
            Application app = fc.getApplication();
            ExpressionFactory elFactory = app.getExpressionFactory();
            elContext = fc.getELContext();
            valueExp = elFactory.createValueExpression(elContext, "#{data.idWorkshopAppModuleDataControl.dataProvider}",Object.class);
} catch (Exception e) {
            logger.error("getAm():" + e);
}
 return (idWorkshopAppModuleImpl)valueExp.getValue(elContext);

*********To access attribute using Key value*******
//Inside any method in App module
Key key= new Key( new Object[]{empID});
Row row=this.getEmployeeView1().getRow(key);
Row.setAttribute(“AttribName”, AttribValue);
try{
            this.getDBTransaction().commit();
}catch(Exception e) {}

*********Setting the Value of Named Bind Variables Programmatically*********
// changed lines in TestClient class
ViewObject vo = am.findViewObject("UserList");
vo.setNamedWhereClauseParam("TheName","alex%");
vo.setNamedWhereClauseParam("HighUserId", new Number(315));
vo.executeQuery();

*********Defining new Bind variable at Runtime:*********
vo.setWhereClause("user_role = :TheUserRole");
vo.defineNamedWhereClauseParam("TheUserRole", null, null);
vo.setNamedWhereClauseParam("TheUserRole","technician");
// execute the query and process the results, and then later...
vo.setNamedWhereClauseParam("TheUserRole","user");


*********Creating and Setting View Criteria attributes:**********
ApplicationModule am =
Configuration.createRootApplicationModule(amDef, config);
ViewObject vo = am.findViewObject("UserList");
// 1. Create a view criteria rowset for this view object
ViewCriteria vc = vo.createViewCriteria();
// 2. Use the view criteria to create one or more view criteria rows
ViewCriteriaRow vcr1 = vc.createViewCriteriaRow();
ViewCriteriaRow vcr2 = vc.createViewCriteriaRow();
// 3. Set attribute values to filter on in appropriate view criteria rows
vcr1.setAttribute("UserId","> 304");
vcr1.setAttribute("Email","d%");
vcr1.setAttribute("UserRole","technician");
vcr2.setAttribute("UserId","IN (324,326)");
vcr2.setAttribute("LastName","Baer");
// 4. Add the view criteria rows to the view critera rowset
vc.add(vcr1);
vc.add(vcr2);
// 5. Apply the view criteria to the view object
vo.applyViewCriteria(vc);
// 6. Execute the query
vo.executeQuery();

setWhereClause() : uses the column name while the createViewCriteriaRow's setAttribute uses attribute name.
We can also use the setConjuction(ViewCriteria.VIEW_CNJ_AND ) method on VC to set the AND or OR operation that will be used between View Criterias.


**********Using Entity object to get attribute value**********
private EntityImpl retrieveServiceRequestById(long requestId) {
String entityName = "devguide.model.entities.ServiceRequest";
EntityDefImpl svcReqDef = EntityDefImpl.findDefObject(entityName);
Key svcReqKey = new Key(new Object[]{requestId});
return svcReqDef.findByPrimaryKey(getDBTransaction(),svcReqKey);
}


*********Using association to get the attribute value for the related Entity object*********
public String findServiceRequestTechnician(long requestId) {
// 1. Find the service request entity
EntityImpl svcReq = retrieveServiceRequestById(requestId);
if (svcReq != null) {
// 2. Access the User entity object using the association accessor attribute
EntityImpl tech = (EntityImpl)svcReq.getAttribute("TechnicianAssigned");
if (tech != null) {
// 3. Return some of the User entity object's attributes to the caller
return tech.getAttribute("FirstName")+" "+tech.getAttribute("LastName");
}
else {
return "Unassigned";
}
}
else {
return null;
}
}


*********Updating Attribute using EO*********
public void updateRequestStatus(long requestId, String newStatus) {
// 1. Find the service request entity
EntityImpl svcReq = retrieveServiceRequestById(requestId);
if (svcReq != null) {
// 2. Set its Status attribute to a new value
svcReq.setAttribute("Status",newStatus);
try {
// 3. Commit the transaction
getDBTransaction().commit();
}
catch (JboException ex) {
getDBTransaction().rollback();
throw ex;
}
}
}


*********Creating new Row in EO*********
public long createProduct(String name, String description) {
String entityName = "devguide.model.entities.Product";
// 1. Find the entity definition for the Product entity
EntityDefImpl productDef = EntityDefImpl.findDefObject(entityName);
// 2. Create a new instance of a Product entity
EntityImpl newProduct = productDef.createInstance2(getDBTransaction(),null);
// 3. Set attribute values
newProduct.setAttribute("Name",name);
newProduct.setAttribute("Description",description);
try {
// 4. Commit the transaction
getDBTransaction().commit();
}
catch (JboException ex) {
getDBTransaction().rollback();
throw ex;
}
// 5. Access the database trigger assigned ProdId value and return it
DBSequence newIdAssigned = (DBSequence)newProduct.getAttribute("ProdId");
return newIdAssigned.getSequenceNumber().longValue();
}


*********Creating new Row using VO*********
import java.sql.Timestamp;
import oracle.jbo.ApplicationModule;
import oracle.jbo.Row;
import oracle.jbo.ViewObject;
import oracle.jbo.client.Configuration;
import oracle.jbo.domain.DBSequence;
import oracle.jbo.domain.Date;
public class TestCreatingServiceRequest {
public static void main(String[] args) throws Throwable {
String amDef = "devguide.model.SRService";
String config = "SRServiceLocal";
ApplicationModule am =
Configuration.createRootApplicationModule(amDef, config);
// 1. Find the ServiceRequests view object instance.
ViewObject svcReqs = am.findViewObject("ServiceRequests");
// 2. Create a new row and insert it into the row set
Row newSvcReq = svcReqs.createRow();
svcReqs.insertRow(newSvcReq);
// 3. Show effect of entity object defaulting for Status attribute
System.out.println("Status defaults to: "+newSvcReq.getAttribute("Status"));
// 4. Set values for some of the required attributes
newSvcReq.setAttribute("CreatedBy",308); // Nancy Greenberg (user)
Date now = new Date(new Timestamp(System.currentTimeMillis()));
newSvcReq.setAttribute("RequestDate",now);
newSvcReq.setAttribute("ProdId",119); // Ice Maker
newSvcReq.setAttribute("ProblemDescription","Cubes melt immediately");
// 5. Commit the transaction
am.getTransaction().commit();
// 6. Retrieve and display the trigger-assigned service request id
DBSequence id = (DBSequence)newSvcReq.getAttribute("SvrId");
System.out.println("Thanks, reference number is "+id.getSequenceNumber());
Configuration.releaseRootApplicationModule(am, true);
}
}


**********Gettning Records from Master and Details table**********
import oracle.jbo.ApplicationModule;
import oracle.jbo.Row;
import oracle.jbo.RowSet;
import oracle.jbo.ViewObject;
import oracle.jbo.client.Configuration;
public class TestClient {
public static void main(String[] args) {
String amDef = "devguide.model.SRService";
String config = "SRServiceLocal";
ApplicationModule am =
Configuration.createRootApplicationModule(amDef,config);
// 1. Find the StaffList view object instance.
ViewObject staffList = am.findViewObject("StaffList");
// 2. Execute the query
staffList.executeQuery();
// 3. Iterate over the resulting rows
while (staffList.hasNext()) {
Row staffMember = staffList.next();
// 4. Print the staff member's full name
System.out.println("Staff Member: "+staffMember.getAttribute("FullName"));
// 5. Get related rowset of ServiceRequests using view link accessor
RowSet reqs = (RowSet)staffMember.getAttribute("ServiceRequests");
// 6. Iterate over the ServiceRequests rows
while (reqs.hasNext()) {
Row svcreq = reqs.next();
// 7. Print out some service request attribute values
System.out.println(" ["+svcreq.getAttribute("Status")+"] "+
svcreq.getAttribute("SvrId")+": "+
svcreq.getAttribute("ProblemDescription"));
if(!svcreq.getAttribute("Status").equals("Closed")) {
// 8. Get related rowset of ServiceHistories
RowSet hists = (RowSet)svcreq.getAttribute("ServiceHistories");
// 9. Iterate over the ServiceHistories rows
while (hists.hasNext()) {
Row hist = hists.next();
// 10. Print out some service request history attributes
System.out.println(" "+hist.getAttribute("LineNo")+": "+
hist.getAttribute("Notes"));
}
}
}
}


*********Finding and Updating a foreign key value**********
import oracle.jbo.ApplicationModule;
import oracle.jbo.JboException;
import oracle.jbo.Key;
import oracle.jbo.Row;
import oracle.jbo.ViewObject;
import oracle.jbo.client.Configuration;
public class TestFindAndUpdate {
public static void main(String[] args) {
String amDef = "devguide.model.SRService";
String config = "SRServiceLocal";
ApplicationModule am =
Configuration.createRootApplicationModule(amDef,config);
// 1. Find the ServiceRequests view object instance
ViewObject vo = am.findViewObject("ServiceRequests");
// 2. Construct a new Key to find ServiceRequest# 101
Key svcReqKey = new Key(new Object[]{101});
// 3. Find the row matching this key
Row[] reqsFound = vo.findByKey(svcReqKey,1); //An entity-based view object delegates the task of finding rows by key to its underlying
if (reqsFound != null && reqsFound.length > 0) { //entity row parts. When you use the findByKey() method to find a view row by key,
Row svcReq = reqsFound[0]; //the view row turns around and uses the entity definition's findByPrimaryKey() to
// 4. Print some service request information //find each entity row contributing attributes to the view row key.
String curStatus = (String)svcReq.getAttribute("Status");
System.out.println("Current status is: "+curStatus);
try {
// 5. Try setting the status to an illegal value
svcReq.setAttribute("Status","Reopened");
}
catch (JboException ex) {
System.out.println("ERROR: "+ex.getMessage());
}
// 6. Set the status to a legal value
svcReq.setAttribute("Status","Open");
// 7. Show the value of the status was updated successfully
System.out.println("Current status is: "+svcReq.getAttribute("Status"));
// 8. Show the current value of the assigned technician
System.out.println("Assigned: "+svcReq.getAttribute("TechnicianEmail"));
// 9. Reassign the service request to technician # 303
svcReq.setAttribute("AssignedTo",303); // Alexander Hunold (technician)
// 10. Show the value of the reference info reflects new technician
System.out.println("Assigned: "+svcReq.getAttribute("TechnicianEmail"));
// 11. Rollback the transaction
am.getTransaction().rollback();
System.out.println("Transaction cancelled");
}
Configuration.releaseRootApplicationModule(am,true);
}
}