Tuesday, September 1, 2009

Creating a WSDL File From XSD File

In this post, lets learn how we can create services interface - WSDL from schema file using Oracle JDeveloper 11g. Here, we attempt to create a service which when provided with an Employee Id returns the Employee Name. Incase no matching records are found for an Id, it simply returns the string value - "Unknown".


# We start with opening the JDeveloper 11g


# Create an application - "MyWSDLApplication" using the Generic Application template.


# Name the project as "MyWSDLProject" and select "Web Services" as the project technologies.


# The Application Navigator view should look like this


# Lets create the schema file first. For this, right click on the project and from the context menu, select New. In the Gallery that opens, select General -> XML -> XML Schema


# Name the schema as Employee.xsd

# The schema editor window opens as shown in the figure below.

# We will be adding two elements - EmpId and EmpName here. Right click on the root schema element and from the context menu, select Insert inside schema -> element

# Once the two elements are specified, we provide them types by right click on the element and from context menu - select Set Type as shown below

# As depicted in the figure below, EmpId type is taken as long while EmpName type is string.

# With the schema defined, we move onto creating the WSDL document. Right click on the project and from context Menu, select New. In the gallery, choose Business Tier -> Web Services -> WSDL Document. Press OK button.
# Name WSDL document as EmployeeWSDL


# Once OK button is presses, the JDeveloper editor view would look like this

# Arrange the schema and WSDL editor windows in a vertical split arrangement like as shown below. This can be achieved by dragging the Employee.xsd tab below.


# Now, we begin creating the WSDL document. Drag and Drop the EmpId element (input for our case) onto the Port Type window. This opens the 'Create Port Type' window. Lets name it as EmployeeDetail.

# After our previous action, the WSDL editor should look like this

# We have a problem here as can be seen from the image. The output is shown as EmpId while we expect it to be EmpName.

# To correct this, we select the output node in the Port Types window. Drag and Drop EmpName element from the schema onto this node. With this, the WSDL document appears like

# Next we change the name of the messages to EmployeeRequestMessage and EmployeeResponseMessage using the property inspector window.
# With the changes in message name, we need to remap these to the operation messages as else these appear with errorneous icon like we have output icon below. To correct this, drag and drop the relevant messages onto the correct nodes. Example : EmployeeRequestMessage is dropped onto the input node of EmpIdOperation and EmployeeResponseMessage is dropped onto the output of EmpIdOperation


# Here, we make the operation name more meaningful using property Inspector - getEmployeeNameOperation.

# The complete WSDL view should appear like this

# Now, we drag and drop the EmployeeDetail node onto the Bindings/Partner Link Types window. In the Create Binding window, we check the SOAP12.


# This should result in the view as shown below :

# Next, drag and drop the root node from the Bindings window onto the Services window. This results in the view as shown below

# At this point, the structure window should look like this. This completes our WSDL document creation process.


# We can validate our WSDL document by doing right click on the EmployeeWSDL (in the Applications Navigator Window) and from context menu, choose Validate WSDL. Confirm the message in the Messages- Log window.


This completes our exercise to create WSDL document using the schema file. Next, we will create Web Service using this WSDL document.

What is a Web Service ?


Before we explore about web services, lets pay attention to the lay man definition for the term - 'Service'. As I look for its definition in my Soft copy of Wordweb, it displays the Noun form of 'Service' as 'Work done by one person or group that benefits another'. Now, in programming terms - I can safely fit this definition as an application or subprogram that executes a unit a work as part of a business process implementation.

To standardise this definition furtherwe say that the service has got some characteristics as

- Loosely coupled. The service provider and consumer are loosely bound with each other. So, in a way - the consumer can easily shift to any other provider without issues.
- Separation of concerns so as to have an encapsulation of implementations. What would this mean > Ah... Well here, it means that as long as the interface (discussed below) remains constant, consumer or provider of service can change their implementation patterns without forcing the other party to make corresponding changes.
- Now, the common question that may strike us at this time is how would a consumer know about how to call this service made available by the provider. For exactly this reason, there is a service contract defined by the interface that the associated service implementation has to honour. WSDL (Web Services Definition Language) provides the standard way to expose the interface definition and the contract (operations performed).

I guess, we are ready to define Web Services now :
A web service is a discrete, reusable software component that is accessed programmatically over the Internet to return a response. Interaction with a Web service is based on a set of standard protocols and technologies called Web services. The term Web Services describes a standardized way of integrating Web-based applications using the open standards.

For Web Services, data and functionality is exchanged in XML format, SOAP [Simple Object Applications Protocol] is used to transfer the data, WSDL is used for describing the services available and UDDI is used for listing what services are available (like a telephone directory listing the names).

More on SOAP, WSDL and UDDI in next post. ;)

Sunday, August 30, 2009

Showing a Confirmation Message


Faces Message can have there severity specified. Inbuilt severity are for fatal,error,warning and information.

To get a confirmation message we can use FacesMessageUtils.getConfirmationMessage which takes a FacesMessage as input.

This is the managed bean code

public void onClick(ActionEvent actionEvent) {
// Add event code here...
String sb = "My Confirmation Message";
FacesContext ctx = FacesContext.getCurrentInstance();
FacesMessage msg =
FacesMessageUtils.getConfirmationMessage(new FacesMessage(sb.toString()));
ctx.addMessage(null, msg);
}

I have bounded the Action listener of command button to above code


Now lets see if you want to format the message, how to do it.


public void onClick(ActionEvent actionEvent) {
// Add event code here...
StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("ADF");
sb.append(" <br> is cool! </br>");
sb.append("<hr> So is <b> Jdevloper</b>");
sb.append("</html>");
FacesContext ctx = FacesContext.getCurrentInstance();
FacesMessage msg =
FacesMessageUtils.getConfirmationMessage(new FacesMessage(sb.toString()));
ctx.addMessage(null, msg);


}

Integrated WLS Server Instance Conflict


If Integrated WLS server in jdeveloper is not shutdown properly, then sometimes you see the following error message.

To resolve the issue , simply end java.exe process from task Manager -> process tab

A List of TODO's

How often in development , do we leave things for future, when we intend to visit back, but alas we forget.

Like I Need to do a NPE checking, Handle the error, Remove SOP, Make it robust etc.

We might write comments for that in the source code, but again if we don't go through the code diligently either we might not find them, or oops! forgot.

Jdev comes with a very good utility called TODO.Have been using this in my current project a lot where requirements are developing/changing by the day.

You can create a TODO , just by typing TODO after // in source file. Later through Task window, you can view all the TODO's in your project/application. TODO's can also be created for entire project or application.


You can view tasks window through View-->Tasks and it would list all the TODO's in your application.

Thursday, August 20, 2009

ADF Table and QBE

Query By Example(QBE) is a powerful feature in ADF, using which user can filter results at runtime.

In this article , we'll see few cases on how to use QBE

An entity, view object and Am based on HR schema, Employee is created.

Create a jsf page, and insert a panel collection inside jsp root tag.

Inside the panel collection drop the View Object from data control as a table.

To turn on QBE, select the check the filter option.

Select the table in structure window, go to properties panel, and from the Appearance section, for the property "Filter visible" , turn it to false.

Run the page. You'll observe a QBE(filter) icon, at the top in toolbar.
Click on it and filterable fields will appear over each column. Key in your filter criteria and hit enter. Table results get filtered.

Explore the table properties, and you'll see FilterModel and QueryListener properties set, which are used internally by the framework to filter results.

Open the pagedef for the above page, and you'll notice a Search Region under the executables which Filter Model and QueryListener points too.

Now say, when user visits the page for the first time, he wants to see only those employee whose salary is greater then 6000.

For this, we need to create a new view criteria in the VO(with Salary > 6000). Mark the auto execute property of the view criteria to true.

Open the above Search Region under the executables in page def, and for the Criteria Attribute, set the value to the name of the view criteria created above.


Now , when you run the page, you'll see all employees with salary greater then 6000 automatically filtered, when you land on the page. You can create any such complex criteria, and filter the table results.

Now lets suppose, you want a choice list at the top, with all departments, and you want to give user a choice to filter using that choice list.

We can use QBE feature to implement this pattern.

First lets create a JobsVO( Read only VO, based on a SQL query).
My query looks like this.


SELECT JOB_ID
FROM
( SELECT NULL AS JOB_ID FROM dual
UNION
SELECT DISTINCT Employees.JOB_ID FROM HR.EMPLOYEES Employees
)
ORDER BY Job_id nulls FIRST


I have a null option, so that i can filter for all departments, when user selects a blank value.

Attach this Vo(JobVO) in AM, and then through data control, drop this view in Panel Collection toolbar facet as a choice list.

For the choicelist, set AutoSubmit to true. Give a proper label,set Required property to false.
Under Adavanced section, you'll find ValueChangeListener. Bind the valuechangeListener to a method in managed bean.

Also bind the table to managed bean.


public void onJobChange(ValueChangeEvent valueChangeEvent) {
// Add event code here...
valueChangeEvent.getComponent().processUpdates(FacesContext.getCurrentInstance());
FacesContext fc = FacesContext.getCurrentInstance();
String job =
(String)fc.getApplication().evaluateExpressionGet(fc, "#{bindings.JobId.inputValue}",
Object.class);
RichTable tbl = this.getMyTable();
FilterableQueryDescriptor filterQD =
(FilterableQueryDescriptor)tbl.getFilterModel();
Map filterCriteria = filterQD.getFilterCriteria();
if (filterCriteria == null) {
filterCriteria = new HashMap<String, Object>();
filterQD.setFilterCriteria(filterCriteria);
}
filterCriteria.put("JobId", job);
QueryEvent queryEvent = new QueryEvent(tbl, filterQD);
MethodBinding queryListener = tbl.getQueryListener();
queryListener.invoke(fc, new Object[] { queryEvent });


}


Choice list returns index, if i directly access, the valueChangeEvent.getNewValue()
However we want the real Job and not index. Therefore the easiest way to get is through attribute binding.

For this first i created a Attribute Binding in page def, for the attribute JobId from JobsVO

Now, since ValueChangeListener is fired before model gets a chance to update its value to the new Job selected, therefore as a first line in method above, we are updating the model, with selected value.

Once this is done, we retrieve the selected job though the EL expression . Now we get hold of Query Descriptor , and in the filter criteria, set the appropriate field and its value. After which we fire the Query event.

Table is filtered and returns the rows with selected job only.

Uploaded project is at
http://groups.google.com/group/adfprojects/web/OBEApplication.zip

Run the untitled1.jspx and experiment.

Sunday, August 16, 2009

Quick Byte Series - Structural Patterns

Continuining with the Quick Byte Series, Lets go through the structural patterns :

Adaptor : converts the existing interface to a new interface that provides compatibility between unrelated classes and can act as wrapper

Bridge : Decouple an abstraction from its implementation so that the two can vary independently.

Composite : Compose objects into tree structures to represent part-whole hierarchies.

Decorator : Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.

Facade : Make a complex system simpler by providing a general interface.

Flyweight : Use sharing to support large numbers of fine-grained objects efficiently.

Proxy : Provide a placeholder for another object to control access to it.