Friday, February 1, 2013

Oracle ADF Read Images From Database Dynamically

Following is one of the way of displaying images from database dynamically and show on ADF page without using HTTP Servlet. The advantage of this method is that we don't require to create DB connection, create and execute query, which are required if we use servlet for displaying the images.

Following are the steps:

1) Create View Object : First create a view object based on table having images as blob column. The below viewObject is based on entityObject but should be created as read only without entity object.


2) Create Managed/Backing Bean: Create a bean file and write following code to read the blob content of image as byte array and convert that to encoded string. This string content will be used to display the image on page.

    public String getImageArray() {
            BlobDomain attribute = (BlobDomain)ADFUtils.evaluateEL("#{row.bindings.Image.inputValue}");
            try {
                byte[]   bytesEncoded = Base64.encode(attribute .getBytes(1L,(int)attribute.getLength()));
                imageArray= new String(bytesEncoded);
            } catch (Exception e) {
                e.printStackTrace();
            }
        return imageArray;
    }


The above code is using EL as #{row.bindings.Image.inputValue} since the data is shown under table.

3) Create Image Component: Drop the image attribute from datacontrol onto jspx page as outputText component just to create the binding of the image attribute. Alternatively we can go to binding tab of the page and add image attribute binding. Now add image component as follow:

           <af:image  source="data:image/png;base64,#{bean.imageArray}"
                          shortDesc="#{row.bindings.ImageName.inputValue}"
                          id="it1">
            </af:image>

4) Final Page: The above method will display the images as follow



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

Thursday, October 18, 2012

WebCenter Portal Deployment Error


Error::

[October 18, 2012 12:31:34 PM MVT] java.lang.InstantiationError: ServiceContext resource configuration file "META-INF/context.provider" found, but the class defined "class oracle.webcenter.framework.internal.service.DefaultServiceContext" is not an instance of oracle.webcenter.framework.service.ServiceContext.
[October 18, 2012 12:31:34 PM MVT] ServiceContext resource configuration file "META-INF/context.provider" found, but the class defined "class oracle.webcenter.framework.internal.service.DefaultServiceContext" is not an instance of oracle.webcenter.framework.service.ServiceContext.
[October 18, 2012 12:31:34 PM MVT] Deploy operation failed.

Solution::

1) Ensure that there is no space in the domain path or working directory (if deploying through JDev itself).

2) If there is no space and still getting the issue, then clear the tmp folder for the manged server where application is being deployed. Stop the managed server and  delete content of following folder

MIDDLEWARE_HOME/user_projects/domains/DOMAIN_NAME/servers/WC_Spaces1/tmp

Now deploy the application again. This time it should work.

Thursday, September 27, 2012

Call Managed bean method without using DC

To call a managed bean method without exposing the managed bean as data control, we can do following;

For a method like this:

public class MyBean {
    public MyBean() {
        super();
    }
  public void myMethod(String arg1) {
    System.out.println(arg1);
  }
}


Add following method invocation code in page definition file:


<methodAction  id="CallMyMethodOnMyBean"              
                InstanceName="${MyBean}"
                MethodName="myMethod" DataControl="AppModuleDataControl">
       <NamedData NDName="arg1" NDType="java.lang.String" NDValue="Foo"/>
</methodAction>

Sample:: http://java.net/projects/smuenchadf/sources/samples/content/MethodActionThatCallsManagedBeanWithoutDataControlInvolved.zip

Wednesday, September 26, 2012

Combine Security Providers in Weblogic

By default, WebCenter services only use first security provider configured in the list. In order to fetch the user details from second or any further provider, we just need to add "virtualize = true" under the domain -> Security Provider Configuration -> Configure -> add new property

For details, please check:

http://andrejusb.blogspot.in/2011/06/webcenter-11g-ps3ps4-aggregating.html



Tuesday, August 21, 2012

A day on Python - Basics

Why Python: Provide better inegration with other language.

How to start Python: login to command promp and type python

Basic Syntax: Require tabs or equal number of spaces to make block.
No Declaration required.

a=10
a =>10
print a => 10

a="Hello\n how are u"
a => "Hello\n how are u"
print a => Hello
                how r u
print type(a) => 'str'

a=2+3j
print a.real and print a.imag
operators: ==,!=,<>, bitwise operators, += ,...

a=10
a is 10 => true
a is not 10 => false

a='hello'
'h' in a => true
'H' in a => false

which python => path and name of interpreter.

Create Script:
vi Script.py
#! /user/bin/

import Script.py => This will execute all the command defined outsids the functions
To import function use: from script import function/variable/*

Using modules::
help()
modules =>List of all modules

To write command in multiple lines:
a='''line1
line2
line3'''
print a => line1
                line2
                line3

Type Casting:
a='458'
b = int(a)

a="Part1"
b="and Part2"
a+' '+b => Part1 and Part2
s= a*2
print s => Part1Part1

If Statement
if a>10:
(tab) print "true"
(tab) print "If done"
else:
(tab) print "Else Part"
(press ctrl+D) to terminate the command if using on prompt

a=[1,2,3]
for var in a
(tab/space) print var
for i in range(1,10)
(tab/space) print var


Using else with while
i=2
a=10
while i<a:
  if  a%i ==0
    print "Not Prime"
    break
 i+=1
else:
   print "Prime" => This else will only be executed when the condition of while is false, not when break is called.

Taking inputs:
1) Integer inputs:
a = input("Enter Value")
Enter Value 10
a => 10
2) String/Char input:
a=raw_input("Enter")
Enter 10
a => '10'

List of Char/String to String
a=['a','b']
s= ''.join(a)
print s =>'ab'
Split again to list
list(s) => ['a','b']
a="hello"
list(a) => ['h','e','l','l','o']
a="Hello how r u"
a.split(' ') => ['Hello', 'how', 'r', 'u']

Concatinate:
a=[1,2,3,4]
a+[10,20] => [1,2,3,4,10,20]

Sorting
a=[1,2,5,4,3]
a.sotr() => [1,2,3,4,5]
a.reverse()
a.pop() => Delete last element and return that element
a.pop(index) => Delete element at index
a.remove(3) => Will remove elemement 3 itself (not at index 3)
a.append([1,2,3]) =>will append [1,2,3] as list at last position
a.insert(0,10) => insert at 0th index

Call be Value and Reference
a=[1,2,3]
b=a => by reference
c=a[:] => by value

Dictionary::
dict={key1:'Value', key2:Value}
dict.has_key(key1) => True
dick.get(key1) => Value
del dick[Key1] => Will delete Key1
d.keys() => Return all Keys
d.values()
d.items()
d.iterkeys() => To iterate over keys

Tuple: Unmodifiable list
a= 1,2,3 or a=(1,2,3)

Using Functions
def functionName(n):
(tab/space) function body

Exception Handling
try:
     body
except ExceptionType,msg
     print msg

Using Modules:
Math: This module provides map, reduce and filter

Saturday, August 18, 2012

Create Row as last row in table


Source: https://blogs.oracle.com/jdevotnharvest/entry/how_to_add_new_adf

public String onRowCreate() {
 BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
 //access the name of the iterator the table is bound to. Its "allDepartmentsIterator"
 //in this sample
 DCIteratorBinding dciter = (DCIteratorBinding) bindings.get("allDepartmentsIterator");
 //access the underlying RowSetIterator
 RowSetIterator rsi = dciter.getRowSetIterator();
 //get handle to the last row
 Row lastRow = rsi.last();
 //obtain the index of the last row
 int lastRowIndex = rsi.getRangeIndexOf(lastRow);
 //create a new row
 Row newRow = rsi.createRow();
 //initialize the row
 newRow.setNewRowState(Row.STATUS_INITIALIZED);
 //add row to last index + 1 so it becomes last in the range set
 rsi.insertRowAtRangeIndex(lastRowIndex +1, newRow); 
 //make row the current row so it is displayed correctly
 rsi.setCurrentRow(newRow);                          
 return null;
}  
For the table to show the newly created row after this ensure:

1. The table is configured to always show the current selected row by setting 
 its displayRow property to selected
2. The table is PPR'ed after the row is created, which can be done declarative 
using the PartialTriggers property of the table pointing to the ID of the command creating the new row