Friday, March 29, 2013

Calling Servlet From Bean


    public String callServlet(){
     
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpServletRequest req = (HttpServletRequest)fc.getExternalContext().getRequest();
        HttpServletResponse resp=(HttpServletResponse)fc.getExternalContext().getResponse();

        try{
            ShowPdfServlet showPdf = new ShowPdfServlet();
            showPdf.doGet(req, resp);
        }catch(Exception e){
            System.out.println("ERROR");
        }
        return "";
    }

Monday, March 18, 2013

Value Change Listener

Value Change Listener on Input Text Field

In Bean:
    public void editInputValueChangeListener(ValueChangeEvent vcl){


        System.out.println(vcl.getOldValue()); //returns old value
        System.out.println(vcl.getNewValue()); //returns new value


       //Calling AM method..
        BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
        OperationBinding opb = bindings.getOperationBinding("setJob");
        opb.execute();

    }

In AMImpl:

    public void setJob(){
        PprVOImpl pVO = getPprVO();
        PprVORowImpl pRow = (PprVORowImpl)pVO.first();
        System.out.println("Selected Vlaue Ename is :"+pRow.getName()); //returns OLD value
    }


Value Change Listener on Message Choice

In jspx:
In Bean:
    public void editMChoiceValueChangeListener(ValueChangeEvent vcl){


        System.out.println(vcl.getOldValue()); // returns rowid of the old value
        System.out.println(vcl.getNewValue()); // returns rowid of the new value
     
        Map p = ((UIComponent)vcl.getSource()).getAttributes();
        System.out.println("Selected Value"+p.get("rowIndexVal")); //returns old value

        vcl.getComponent().processUpdates(FacesContext.getCurrentInstance());
        Map p = ((UIComponent)vcl.getSource()).getAttributes();
        System.out.println("Selected Value"+p.get("rowIndexVal")); //returns new value
             
        //Calling AM method..
        BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
        OperationBinding opb = bindings.getOperationBinding("setJobx");
        opb.execute();
    }

In AMImpl:
    public void setJobx(){

        PprVOImpl pVO = getPprVO();
        PprVORowImpl pRow = (PprVORowImpl)pVO.first();
        System.out.println("Selected Vlaue Ename is :"+pRow.getName()); //returns NEW value
    }




Friday, March 15, 2013

To Aaccess Resource Bundle in Bean


    public String getTextProp(String propKey){
        ResourceBundle resourceBundle =   BundleFactory.getBundle("com.hb.view.ViewControllerBundle");
        String propName =null;
        if(resourceBundle != null)
        {
                   propName = resourceBundle.getString(propKey);
        }
        return propName ;
    }

Source: http://learn-adf.blogspot.in/2012/03/access-resource-bundle-in-bean.html

Monday, March 11, 2013

JavaScript With ADF Faces Samples


In your ADF web application you may want to use javaScript functions to perform some actions in client side. I will list some of the major javaScript functions which I use it in my applications. To use javaScript functions in your ADF Application (In JDeveloper 11.1.1.2.0) you should do the following :

1- Put inside af:document --> af:resource component with type javaScript (prefer to put the af:resource component inside metaContainer facet of af:document).

2- use af:clientListener component to call the function.

some of the JavaScript sample :

- Open popup
function openPopup(evt){
var popup = AdfPage.PAGE.findComponent("popupId");
popup.show();
}

- Hide poup
function aboutOkButton(event) {
var dialog = event.getSource();
var popup = dialog.findComponent("aboutPopup");
popup.hide();
event.cancel();
}

- Change component visibility
function showText()
{
var output1 = AdfUIComponent.findComponent("output1")
var output2 = AdfUIComponent.findComponent("output2")
var input = AdfUIComponent.findComponent("input")

if (input.value == "")
{
output1.setVisible(true);
}
else
{
output2.setVisible(true)
}

}

- Read value from inputText
var input1 = document.getElementById('in1::content');
var input2 = document.getElementById('in2::content');

if (input1.value == input2.value)
{
alert("Equals");
}
else
{
alert("No Equals");
}

- Set Panel Splitter Position
function setSplitterPos(event) {
var source = event.getSource()
source.setSplitterPosition(200);
}

insert inside af:panelSplitter ---> af:clientListener as:
< af:clientListener method="setSplitterPos" type="propertyChange"/ >

- Execute af:commandButton action

var component = AdfPage.PAGE.findComponentByAbsoluteId(commanButtonId);
AdfActionEvent.queue(component, component.getPartialSubmit());

- Execute goButton

function invokeGo(event){
var component = AdfPage.PAGE.findComponentByAbsoluteId("gb1");
var redirectEvent = new AdfRedirectEvent(component, component.getDestination(), true);
redirectEvent.queue(true);
}

Hint :
AdfRedirectEvent is an internal class and the target is not recognized. Note that on the goButton, you need to set the clientComponent property to true.

- Run file.exe
function RunExe()
{
var commandtoRun = "C:\\file.exe";
var objShell = new ActiveXObject("Shell.Application");
objShell.ShellExecute(commandtoRun, "", "", "open", 1);
}

- Accepting only Upper Case characters in input field

/// For IE only

function convertToUpperCase( _event ) {
var currText = null;
currText = String.fromCharCode(window.event.keyCode);
window.event.keyCode = currText.toUpperCase().charCodeAt(0);
}

/// For Mozilla

function convertToUpperCase( _event ) {
var _keycode = _event.getKeyCode();
if( ( _keycode > 64 && _keycode < 90 ) ||

( _keycode > 96 && _keycode < 123 ) ) {

currText = String.fromCharCode(_event.getKeyCode());
currText = currText.toUpperCase();

var _textFieldField = document.getElementById ( _event.getSource().getClientId() );
var _inputFields = _textFieldField.getElementsByTagName('INPUT');
var _firstInputField = _inputFields[0];
_firstInputField.value = String.concat( _firstInputField.value, currText);
_event.cancel();
}
}

- To know which browser you use

function iEOrNot(myEvent) {
var currText = null;
if(!myEvent)
myEvent = window.event;
if(navigator.appName == 'Microsoft Internet Explorer') {
// I am IE
} else if(navigator.appName != 'Microsoft Internet Explorer') {
// I am not IE
}
}

- Get screen width and hight

width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;

hight= java.awt.Toolkit.getDefaultToolkit().getScreenSize().hight;

- Get Mac Address, Ip Address and Computer Name
function call(event) {
var source = event.getSource();
var macAddress = "";
var ipAddress = "";
var computerName = "";
var wmi = GetObject("winmgmts:{impersonationLevel=impersonate}");
e = new Enumerator(wmi.InstancesOf("Win32_NetworkAdapterConfiguration"));
for(; !e.atEnd(); e.moveNext()) {

var s = e.item();
if(s.DNSHostName!=null)
{
macAddress = s.MACAddress;
ipAddress = s.IPAddress(0);
computerName = s.DNSHostName;
}
}
}

- Open inputDate calender

function openDate(event) {
src = event.getSource();
popup = src.findComponent(""+AdfRichUIPeer.CreateSubId(src.getClientId(), AdfDhtmlInputDatePeer._POPUP_ID));
hints = {alignId:src.getClientId(), align:AdfRichPopup.ALIGN_END_AFTER};
popup.show(hints);
}

- Get keyCode of the key
function keyCode(evt) {
var k=evt.getKeyCode();
}

- Set cursor to inputText
function setFocus(evt) {
var t=document.getElementById('t1::content');// t1 is the inputText Id
t.focus();
Source: http://sameh-nassar.blogspot.in/2010/02/javascript-functions-sample.html

Friday, March 8, 2013

Call AM Method in VO Attribute Using Groovy Expression

1.Open AMImpl, write a method as shown in below screen.

2.Open VO Attributes. Create transient attribute and set following expression as Default Value.
Expression: adf.object.applicationModule.getEmpWelcomeMsg(Ename)


3.Test Results.

Groovy Aggregate functions in VO Attributes

Sample Groovy Aggregate functions: sum, count, min, max and avg
Syntax: ViewAccessor.function(attribute)

1.Create VO
2.Create Accessor for VO as shown in below screen.
3.Create Transient attribute and set properties as shown in below screen. Set expression on view accessor we have created on above screen.
Expression: TestGroovy.max("Sal")


Set Sequence Value to EO Attribute Using Expression

1. Open EO Attributes.
2. Select attribute for which you want to add value from database sequence.
3. Click on Details tab.
4. Select Default Value property as Expression. Click on Pencil button to add below expression.
(new oracle.jbo.server.SequenceImpl("TRX_SEQ",adf.object.getDBTransaction())).getSequenceNumber()
5. Click Ok button
6.Select Refresh Expression Value text field. Set value true
7.Save changes and test application.

Tuesday, March 5, 2013

ADF Interview Questions 2

http://adfhowto.blogspot.in/2010/12/possible-adf-interview-questions.html


ADF Interview Questions 1

Q : What is Oracle ADF?
A : Oracle ADF is an commercial java/j2ee framework, which is used to build enterprise applications.
It is one of the most comprehensive and advanced framework in market for J2EE

Q : What are the advantages of using ADF?
A : Following are the advantages of using :
  • It supports Rapid Application Development.
  • It is based on MVC architecture
  • Declarative Approach (XML Driven)
  • Secure
  • Reduces maintenance cost and time
  • SOA Enabled
Q : What are various components in ADF?
A : Oracle ADF has following components
  • ADF Business Components(Model)
  • ADF Faces (View)
  • ADF Taskflows(Controller)
Q : What is the return type of Service Methods?
A : Service Methods can return Scalar or Primitive Data types.

Q : Can Service Methods return type Void?
A : Yes, Service Methods can Return type Void

Q : Can Service Methods return Complex Data types?
A : No, service methods can return only primitive/scalar data types.

Q : Which component in ADF BC manages transaction ?
A : Application Module, manages transaction.

Q : Can an entity object be based on two Database Objects(tables/views) or two Webservices ?
A : No entity objects will always have one to one relationship with a database object or web service.

Q : Where is that we write business rules/validations in ADF and why?
A : We should be writing validations at Entity Object level, because they provide highest degree of reuse.

Q : What is Managed Bean?
A : Managed bean is a java class, which is initialized by JSF framework. It is primarily used to hold view and controller logic. It is also used to execute java code to be executed on a user action like Button Click.

Q : What are Backing Bean?
A : Backing beans are those managed beans which have 1:1 mapping with a page. They have getters and setters for all the "components" in the related page.

Q : What is difference between managed and backing beans?
A : Backing bean has 1:1 relation with page whereas managed beans can be used in multiple pages.
Backing beans scope is limited to the page whereas managed beans can have other scopes too.

Q : What is a Taskflow?
A : Taskflow is the controller of an ADF application, it provides us an declarative approach to define the control flow.  It is used to define the navigation between pages and various taskflow activites.

Q : What are the different types/categories of Taskflows ?
A :  Taskflows are of two categories : Bounded and UnBounded.

Q : What is the difference between Bounded and UnBounded taskflows?
A : Differences between Bounded and UnBounded taskflows :
  • Bounded taskflows can be secured but Unbounded can’t.
  • Bounded taskflows can accept parameter and return values but unbounded taskflows don’t support parameters
  • Bounded taskflows has a single entry point or a default activity but unbounded taskflows have multiple entry points.
  • Bounded taskflows can be called from other bounded/unbounded taskflows but unbounded cannot be called or reused.
  • Bounded taskflows support transactions unbounded don’t
Q : What are the various access scopes supported by ADF?
A : ADF Faces supports the following scopes
  • Application Scope
  • Session Scope
  • PageFlow Scope
  • Request Scope
  • BackingBean Scope.
Q : Describe life cycle of a ADF Page?
A : ADF page is an extension of JSF and has following phases in its lifecycle
  1. Initialize Context: In this phase the adf page initializes the LifecycleContext with information that will be used during the Lifecycle.
  2. Prepare Model:  In this phase ui model is prepared and initialized. In this phase page parameters are set and methods in the executable section of the page definition of the ADF page are executed.
  3. Apply Input Values: This phase handles the request parameters. The values from the HTML are sent to the server  and applied to the page binding in page definitions.
  4. Validate Input Values:  This phase validates the values that were built in the Apply input values phase
  5. Update Model:  Validated values supplied from user are sent to ADF business components data model
  6. Validate Model Updates:  In this phase the business components will validate user supplied values.
  7. Invoke Application:  This phase will process the ui events stack built during the life cycle of page and also fire navigational events
  8. Prepare Render:  This is the final phase where HTML code is generated from the view tree.
Q : What is PPR and how do you enable Partial Page Rendering(PPR)?
A : PPR is a feature supported by ADF Faces, using which we can render a small portion of a HTML Page, without refreshing the complete page.
It is enabled by.
  • Setting AutoSubmit property to true on the triggering element.
  • Setting the PartialTriggers property of target component to refer to component id of the triggering element.
Q : What is Action Listener ?
Ans : An action listener is a class that wants to be notified when a command component fires an action event. An action listener contains an action listener method that processes the action event object passed to it by the command component
Q:What are business Component In ADF.Describe them?
Ans: All of these features can be summarized by saying that using ADF Business Components for your J2EE business service layer makes your life a lot easier. The key ADF Business Components components that cooperate to provide the business service implementation are:
Entity Object
An entity object represents a row in a database table and simplifies modifying its data by handling all DML operations for you. It can encapsulate business logic for the row to ensure your business rules are consistently enforced. You associate an entity object with others to reflect relationships in the underlying database schema to create a layer of business domain objects to reuse in multiple applications.
Application Module
An application module is the transactional component that UI clients use to work with application data. It defines an up datable data model and top-level procedures and functions (called service methods) related to a logical unit of work related to an end-user task.
View Object
A view object represents a SQL query and simplifies working with its results. You use the full power of the familiar SQL language to join, project, filter, sort, and aggregate data into exactly the “shape” required by the end-user task at hand. This includes the ability to link a view object with others to create master/detail hierarchies of any complexity. When end users modify data in the user interface, your view objects collaborate with entity objects to consistently validate and save the changes
Q: What is Top Link?
Ans:
Top Link is an Object-Relational Mapping layer that provides a map between the Java objects that
the model uses and the database that is the source of their data.
By default, a session is created named default. In the following steps, you create a new session
Q:What is Managed Bean?
Ans:JavaBean objects managed by a JSF implementation are called managed beans. A managed bean describes how a bean is created and managed. It has nothing to do with the bean’s functionality.
Managed bean is about how the bean is created and initialized. As you know, jsf uses the lazy initialization model. It means that the bean in the particular scope is created and initialized not at the moment when the scope is started, but on-demand, i.e. when the bean is first time required.
Q :What is Backing Bean?
Ans:Backing beans are JavaBeans components associated with UI components used in a page. Backing-bean management separates the definition of UI component objects from objects that perform application-specific processing and hold data.
Backing bean is about the role a particular managed bean plays. This is a role to be a server-side representation of the components located on the page. Usually, the backing beans have a request scope, but it is not a restriction.
The backing bean defines properties and handling-logics associated with the UI components used on the page. Each backing-bean property is bound to either a component instance or its value. A backing bean also defines a set of methods that perform functions for the component, such as validating the component’s data, handling events that the component fires and performing processing associated with navigation when the component activates.
What is view object?
Ans :A view object is a model object used specifically in the presentation tier. It contains the data that must display in the view layer and the logic to validate user input, handle events, and interact with the business-logic tier. The backing bean is the view object in a JSF-based application. Backing bean and view object are interchangeable terms
Q: Difference between Backing Bean and Managed Bean?
Backing Beans
Managed Beans
A backing bean is any bean that is referenced by a form.
A managed bean is a backing bean that has been registered with JSF (in faces-config.xml) and it automatically created (and optionally initialized) by JSF when it is needed.
The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml,
Backing Beans should be defined only in the request scope
The managed beans that are created by JSF can be stored within the request, session, or application scopes
Q? What do you mean by Bean Scope?
Bean Scope typically holds beans and other objects that need to be available in the different components of a web application.
Q.  What are the different kinds of Bean Scopes in JSF?
JSF supports three Bean Scopes. viz.,
Request Scope: The request scope is short-lived. It starts when an HTTP request is submitted and ends when the response is sent back to the client.
Session Scope: The session scope persists from the time that a session is established until session termination.
Application Scope: The application scope persists for the entire duration of the web application. This scope is shared among all the requests and sessions.
What is the difference between JSP-EL and JSF-EL?
JSP-EL
JSF-EL
In JSP-EL the value expressions are delimited by ${…}.
In JSf-EL the value expressions are delimited by #{…}.
The ${…} delimiter denotes the immediate evaluation of the expressions, at the time that the application server processes the page.
The #{…} delimiter denotes deferred evaluation. With deferred evaluation ,the application server retains the expression and evaluates it whenever a value is needed.

Q:How to declare the page navigation (navigation rules) in faces-config.xml file in ADF 10g
?
Ans: Navigation rules tells JSF implementation which page to send back to the browser after a form has been submitted. We can declare the page navigation as follows:
/index.jsp
login
/welcome.jsp
This declaration states that the login action navigates to /welcome.jsp, if it occurred inside /index.jsp.
Q: Setting the range of table
Ans :
Q : Which component in ADF BC manages transaction ?
A : Application Module, manages transaction.
Q : Can an entity object be based on two Database Objects(tables/views) or two Webservices ?
A : No entity objects will always have one to one relationship with a database object or web service.
Q : Where is that we write business rules/validations in ADF and why?
A : We should ideally be writing validations at Entity Object level, because they provide highest degree of reuse.
Q:What are the JSF life-cycle phases?
Ans:The six phases of the JSF application lifecycle are as follows (note the event processing at each phase):
1. Restore view
2. Apply request values; process events
3. Process validations; process events
4. Update model values; process events
5. Invoke application; process events
6. Render response
Q. Explain briefly the life-cycle phases of JSF?
1. Restore View : A request comes through the FacesServlet controller. The controller examines the request and extracts the view ID, which is determined by the name of the JSP page.
2. Apply request valuesThe purpose of the apply request values phase is for each component to retrieve its current state. The components must first be retrieved or created from the FacesContext object, followed by their values.
3. Process validationsIn this phase, each component will have its values validated against the application’s validation rules.
4. Update model valuesIn this phase JSF updates the actual values of the server-side model ,by updating the properties of your backing beans.
5. Invoke applicationIn this phase the JSF controller invokes the application to handle Form submissions.
6. Render responseIn this phase JSF displays the view with all of its components in their current state.
Q: What is setActionListener?
Ans:SetActionListener – The setActionListener tag is a declarative way to allow an action source ( , , etc.) to set a value before navigation. It is perhaps most useful in conjunction with the “processScope” EL scope provided b ADF Faces, as it makes it possible to pass details from one page to another without writing any Java code. This tag can be used both with ADF Faces commands and JSF standard tags.
Exmaple of this can be as follows. Suppose we have a table “employee”.We want to fetch the salary of an employee of some particular row and want to send this salary in
Next page in process scope or request scope etc.So using this we can do this.
It have two attributes :
From – the source of the value; can be an EL expression or a constant value
To – the target for the value; must be an EL expression
1
 from="#{row.salary}"
2
to="#{processScope.salary1}"/>
This setActionListener will pick value of salary of that row and store this value into salary1 variable.So anyone can use this salary
As processScope.salary1 . It is very simple to use. And very useful.
Related Posts Plugin for WordPress, Blogger...