Pages

Thursday, May 20, 2010

Flex Http Service



Flex was one of the best framework for developing RIA [ Rich Internet Applications ]. it provides many inbuilt capabilites for connecting to various back end systems including Http and SOAP based web-services.

in this article , we will see how we can connect to a java servlet using flex HttpService.this service does not require any changes to any configuration files.

HttpService - Using Flex Http Service we can send request for getting external data either using post or get methods. we can use HttpSerivce with any kind of backend technology like Java Server pages ,ColdFusion , Microsoft Asp.net e.t.c.

Creating A Flex User Interface - we will make our example very simple .we will create a Text Field which accepts a String and a Button which shows the length of the text entered by making a call to server .



here is the Mxml Code for creating the Layout

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  
<mx:HTTPService id="serverCall" method="POST"  
    url="http://localhost:8080/HttpServiceInFlex/SampleHttpServlet"
    result="on_Result(event)" fault="on_Fault(event)"/>

<mx:TextInput x="47" y="17" text="Enter Your Name Here" id="textInput"/>
<mx:Button x="47" y="47" label="Call Servlet" id="callToServer" click="send_data(event)"/>    
  
    <mx:Script>
        <![CDATA[
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;
             import mx.controls.Alert;
          
            private function send_data(event:MouseEvent):void {
                var param:Object = {};
                param["name"] = textInput.text;
                serverCall.send(param);
            }
          
            private function on_Result(event:ResultEvent):void {
                Alert.show(event.message.body.toString());
            }
          
            private function on_Fault(event:FaultEvent):void {
                Alert.show(event.toString(), event.type);            
            }
          
        ]]>
    </mx:Script>
      
</mx:Application>

lets see the main parts in the code , a HttpService can be created by Using <mx:HTTPService> element like

<mx:HTTPService id="serverCall" method="POST"  
    url="http://localhost:8080/HttpServiceInFlex/SampleHttpServlet"
    result="on_Result(event)" fault="on_Fault(event)"/>

HttpService takes a few properties lik id="serverCall" which we will be using when making a call to java servlet and to send some parameters to server side.
method="get" - the method we are requesting
url=Url is the page we are trying to access
we will also define result and fault event handlers which are invoked when a call to server succeds or fails.

and  now coming to the actionScript code ,
we have written a send_data() method which gets invoked when we click the button under the text Field. so we define the send_data() method as


private function send_data(event:MouseEvent):void {
                var param:Object = {};
                param["name"] = textInput.text;
                serverCall.send(param);
      }

here we are using
var param:Object = {};

param["name"] = textInput.text; to get the value from textField and assign to the variable "name" and keep that in the request .

serverCall.send(param);  , in this we are invoking the call to the server by passing the values that are collected from the textField.

the other 2 methods ,

private function on_Result(event:ResultEvent):void {
                Alert.show(event.message.body.toString());
}
          
private function on_Fault(event:FaultEvent):void {
                Alert.show(event.toString(), event.type);            
}

which are nothing but the event handlers for handling the status returned by the HttpService .if there is a success then the on_Result method is invoked which alerts the response obtained  and fault does the thing that is defined for handling fault events.

here comes the SampleServlet that i Used

package com.HttpService;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SampleHttpServlet
 */
public class SampleHttpServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SampleHttpServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sentvalue=request.getParameter("name");
        response.getWriter().append("Your Name Contains Total "+sentvalue.length()+" characters");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sentvalue=request.getParameter("name");
        response.getWriter().append("Your Name Contains Total "+sentvalue.length()+" characters");
    }

}

Just takes the String and counts the number of characters in the String.

and finally we are done with code ,  lets see how it works




We will see some more ways of connecting to back ends using Flex in the next articles

Happy Coding
…………
Read More

Thursday, May 6, 2010

BlazeDS


Adobe Flex, one of the most used tool for developing RIA [Rich Internet Applications]. Flex is not only a User interface provider but a robust framework that handles enterprise integration and communication. BlazeDS is a open source software that provides effective integration for flex and java.
What is BlazeDS?
BlazeDS is open source software that helps in integrating Flex with java.BlazeDs enables message interchange and remote procedure calls thus providing a strong integration between 2 technologies.
What exactly is BlazeDS?
We gave a brief introduction for BlazeDS, but let’s see in detail

BlazeDS is a
  • Java web application that leverages servlet specification.
  • Web application that runs in a servlet container.
  • Set of services that can be managed by jmx agents.
  • A program that intercepts all interaction between a flex application and java.
BlazeDS allows us to
  • Allows to access remote java methods from flex application.
  • Translation of java objects returned from server to action script objects read by flex.
  • Translation of flex action script objects to java objects needed by java server to process.
  • Management of communication channels, connection types between java and flex.
  • Message passing between flex application and java server.
  • Pushing data to the client on server’s initiative and not as a response to a request.
Installing BlazeDS
BlazeDS can be downloaded from http://opensource.adobe.com/wiki/display/blazeds/download+blazeds+3
BlazeDS works on all open sources and commercial servlet containers. BlazeDS includes a turnkey version which contains a internal tomcat server configured which is a best choice for beginners.

What does BlazeDS contains?
BlazeDS contains 3 key services,
  • Remoting Service allows your flex applications to invoke java method deployed on servers
  • Message Service provides us a publish/subscribe infrastructure which allows the flex application to publish messages and subscribe to a message destination. This allows us to develop data push technology.
  • Proxy service allows the flex application to access data available in other domains
Configuring BlazeDS
The heart of blazeDS contains a Servlet which intercepts all calls between flex application and java. The servlet is called MessageBrokerSerlvet which uses channels, endpoints and adapters to enable proxy, remote and message services. An xml file called “services-config.xml” which lies in WEB-INF/flex defines the relationship for the services.
Channels and end point are the important things in allowing a connection between java and flex. A flex client can communicate with channels. These channels will communicate with end point that resides with the BlazeDS.
These BlazeDS end point are servlet based end point and each end point defines a type and format for communication. The type of communication varies from simple AMF data exchange, polling data exchange and streaming data exchange.
The channels and endpoints are paired when a communication is done from flex to BlazeDS.The binding of channels and endpoint is done in “services-config.xml” file.
In addition to channels and endpoints, BlazeDS contains adapters which allow the BlazeDS to send messages from the end point to here where from here they can connect to a back end system or a jms server.

Explaining Channels and Service Points
To send a message the client application uses channels .channels use different formats of message, translate them into a network specific format and send them to the end point which is on server side.
Channels maintain an order of the messages being sent and the same order is applied in receiving the responses. This helps for a proper communication between both parties.
The endpoint takes the messages, translates them from the network specific manner to the form in which java can understand and sends them to messsageBrokerServlet. The servlet then determines where to send the message.
Architecture 

BlazeDS application contains 2 sides
Client - The client side uses a messaging framework provided by the blazeDS in interacting with the server. Channels are used on client side to make this connectivity. Channels are grouped together as channel sets .the main functionality of channel set is to provide connectivity between flex and server. The flex application tried to connect to the first channel in case if it is not success it goes to next channel in the channel set. Channels are the low level ends of client application. They are mainly responsible for connecting flex application to the end point of blazeDS on server side.
Selection of channels in channel set depends on various factors like type of application we are constructing. If we are working with a non-binary data, we will go for Http Channel or if we construct binary data we go for AMFChannel [Action Message Format].
Server - The BlazeDS server is contained in a web application. a flex client makes a request to the channels from where the request goes to end point on the BlazeDS side. From BlazeDS it moves to MessageBorker. From MessageBroker to Service Object [ Remote Service,Http Service] and from service Object to Destination [ Remoting Destination .. ] and then finally to adapters where the adapter objects may connect to Database or perform any operations locally and send back the data to client.
We will have a move over the server side objects
End Point – BlazeDS end points are inside the servlet container.these end points are bootstrapped by the MessageBrokerServlet which is defined the web.xml.in addition to this declaration , we also have a HttpSessionListener is configured so that the blazeDs has a session listener attribute and a binding listener.
Client applications use channels to communicate with endpoints. It is very important that message format should be identical in communication. If a client uses AMF Message, then he connects to AMFChannel which connect AM Endpoint on server side.
MessageBorkerServlet- MessageBrokerServlet extracts the message from the request once the request is processed at end point and identifies the service it is requesting and sends the message to the service.
Services and Destinations – services are the targets for the client applications where as destinations are services configured in some way. Consider when we work on a remoting application , we use a RemoteObject to communicate with the Remoting Service.we need to provide some more details like destinationID that refers to the remoting destination that refers a destination in which we need to perform some actions like destination would be a java object to access methods.
The mapping between client-side Flex components and BlazeDS services is as follows:
·         HTTPService and WebService communicate with HTTPProxyService/HTTPProxyDestination
·         RemoteObject communicates with RemotingService/RemotingDestination
·         Producer and Consumer communicate with MessageService/MessageDestination
You can configure services and their destinations in the services-config.xml file, but it is best practice to put them in separate files as follows:
·         RemotingService configured in the remoting-config.xml file
·         HTTPProxyService configured in the proxy-config.xml file
·         MessageService configured in the messaging-config.xml file
Adapters – the last one in the chain are adapters. When a message arrives at the correct destination, it is passed to an adapter that fulfills the request either locally or by contacting a backend system or a remote server such as a JMS server

Messages
All communication between flex and java are done using messages of different types.flex components use several messages to communicate with blazeDS.there are both action Script version and java version classes in both client side and server side , since messages are serialized and de-serialized on both sides.
In other situations, you do not write code for constructing and sending messages. For example, you simply use a RemoteObject component to call the remote method from the Flex application. The RemoteObject component creates a RemotingMessage to encapsulate the RemoteObject call. In response it receives an AcknowledgeMessage from the server. The AcknowledgeMessage is encapsulated in a ResultEvent in the Flex application.
Sometimes you must create a message to send to the server. For example, you could send a message by creating an AsyncMessage and passing it to a Producer.
Message Patterns: BlazeDS uses 2 types of patterns Request/Reply and Publisher/Subscriber. HTTPService, and WebService components use the request/reply message pattern, in which the Flex component makes a request and receives a reply to that request. Producer and Consumer components use the publish/subscribe message pattern. In this pattern, the Producer publishes a message to a destination defined on the BlazeDS server. All Consumers subscribed to that destination receive the message.


Configuration Files
The services-config.xml file initially references three other configuration files
o    remoting-config.xml along with services-config.xml files are used when we work with remoting.
o    messaging-config.xml along with services-config.xml files are used when we work with messaging.
o    proxy-config.xml along with services-config.xml files are used when we work with proxied HTTP Service or proxied Web Service.

Set up BlazeDS in Tomcat
Step 1 - Download latest release of BlazeDS Turnkey.
Step 2 – Download Tomcat and install
Step 3 - Extract the content in blazeds.war file into a folder called blazeds. Now we have downloaded and have the required files extracted to setup BlazeDS for a web application. Let’s create a web application.
Step 4 -  In your Tomcat installation directory, you will find a folder named webapps. Usually it is at this location on Windows Operating System “C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps”
Create a web application named samplewebapp. You do this by just creating folder named samplewebapp under webapps folder.
Step 5 - Copy all .jar files from blazeds/WEB-INF/lib to samplewebapp/WEB-INF/lib
Step 6 - Copy blazeds/WEB-INF/flex folder to samplewebapp/WEB-INF
This folder (blazeds/WEB-INF/flex) contains BlazeDS configuration files. Use these files to configure Remoting/Messaging/Proxy services.
Step 7- Now we will add Servlet mapping for BlazeDS Servlet named MessageBrokerServlet, so that BlazeDS is invoked when you send request for a Remoting/Messaging/Proxy destination using any of the channels supported.
Copy blazeds/WEB-INF/web.xml to samplewebapp/WEB-INF
If you already have a web.xml configured, then you can just copy the Servlet mapping for MessageBrokerServlet and the session listener. You can either copy the content below or copy it from the blazeds/WEB-INF/web.xml

<!-- Http Flex Session attribute and binding listener support -->
<listener>
<listener-class>flex.messaging.HttpFlexSession</listener-class>
</listener>
<!-- MessageBroker Servlet -->
<servlet>
<servlet-name>MessageBrokerServlet</servlet-name>
<display-name>MessageBrokerServlet</display-name>
<servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
<init-param>
<param-name>services.configuration.file</param-name>
<param-value>/WEB-INF/flex/services-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MessageBrokerServlet</servlet-name>
<url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>

That’s it you have BlazeDS setup for your web application.
We will see some of the examples of integrating flex and java using BlazeDS in the next article.
Read More

Monday, May 3, 2010

Working With Weblogic Startup & Shutdown classes

There is many times where an application needs to get global data to perform some sort of functionality. They may use the global data which may contain many parameters like jms , jdbc , connection pool information which will be used while serving to the client requests. These sorts of global data, frequently used data should be kept in somewhere easily accessed by application. The Best place is to place them in JNDI [Java Naming And Directory Interface].if it to be placed in the JNDI, How can it be done in Weblogic . the answer to this questions is by using a StartUp class.

A startup class in weblogic is nothing but a class which gets executed when the server is starting up. Similarly the Shutdown works the wasy the name says.

In this article we will see how we can create a startup class and deploy it to a target to get executed when the target is starting up.

Create A Start Up Class: in order to create a start up class in weblogic we need to implement the weblogic related interface T3StartupDef . If you're wondering about the 'T3', the unofficial word is that it stands for Tengah 3, which I believe was the old name for the product before the WebLogic Company was purchased by BEA.this interface provides 2 methods to implement


public void setServices(T3ServicesDef arg0) {

}

public String startup(String arg0, Hashtable arg1) throws Exception {
return null;
}


The first method takes an argumernt T3ServicesDef which is an object which gives you access to the weblogic internal like connection pools ,logging and workspaces and more .

The second method takes 2 arguments String, Hashtable where the first argument is the name that we specified during the creation of startup class. If we specify the name of the startup class in weblogic console as “startUp-0”, then the first argument holds this name. The second argument is a hashtable which takes all the arguments that we send through the start up to be kept in jndi.these can by any string values.


Here is the same code

public class sampleClass implements T3StartupDef {

public void setServices(T3ServicesDef arg0) {

}

public String startup(String arg0, Hashtable arg1) throws Exception {
System.out.println("Startup class invoked - " + arg0);
return "Invoked Class Is Here And Successfully";
}


public static void main(String[] args) {

}

}

Creating a Startup Class In Weblogic Console :
Click “startup and Shutdown class” in left hand tree
Select “startup Class” -> Next
Keep the Name and enter the class Name [ Class name for above example : com.jagadesh.sampleClass ] -> Next
Select the Target and Finnish

Now the important part, we need to make sure the class is in the server class path , for this we need to edit setDomainEnv.cmd [ windows ] to add the class to the server class path.

If we need to add a jar to all domains, we can copy the jar file to WL_HOME/server/lib . the CommEnv.cmd will include the jar when the server is starting up. We will edit the CommEnv.cmd and prepend the jar file to WEBLOGIC_CLASSPATH

If we need to add to a specific domain, we will edit the setDomainEnv.cmd file available in that domain bin directory and add the jar entry to PRE_CLASSPATH

I created the jar file by the name Sam and added it to the setDomainEnv.cmd as below

@REM Clear the pre_classpath here in case an application template wants to set it before the larger pre_classpath id below

set PRE_CLASSPATH=C:/software/Sam.jar;

just search for the PRE_CLASSPATH and on the right hand side give your jar location.

Now we can restart the server and in the log file after the server restarted we can see the contents which we defined in the startup method like


<1270705581990> <BEA-000287> <Invoking startup class: com.jagadesh.sampleClass.startup(null)>
####<Apr 8, 2010 12:46:21 AM CDT> <Info> <WebLogicServer> <PKMI-DS00C2B17> <desktop_server> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1270705581990> <BEA-000288> <com.jagadesh.sampleClass reports: Invoked Class Is Here And Successfully>


See weblogic docs for writing advanced start up and shutdown scripts
Read More

Weblogic Deployment Plan


A deployment plan Is a plain xml document that defines a application deployment configurations that are specific for a weblogic server environment such as Production, Test and Development. The deployment plan exists outside of the application archive and will override the configurations specified by the application descriptors. We can use the deployment plan to easily change the configurations from production to test and development.

The deployment plan lets an admin define specific features for a deployment in an xml file and re-use them for different deployments. For example, a web application in a production environment has a context root as /example and in test or development we need to specify the context root as /examples for the same web application, then we can create a deployment plan from the production environment. We can edit it, change the context root and deploy the same in the test and development environments [but we have a different context roots]

We will use the SimpleSample application in our Demo. this is a simple application with a servlet which prints a message on the screen.

First we will deploy the application into the weblogic server , just follow the steps below for deploying the application ..

Click On Deployments [on the Left Hand Tree]
On the right hand side, you will see a “Summary of deployments” -> select “install”
Now select the path where your war file is available -> Next
Select “install the deployment as an application” -> Next
Select the target -> Next
Next -> Next - > Finish

You can the test the application by going to
Deployments -> Application Name ->Testing

Once the application is deployed and working , we will see how to create a deployment plan for the simpleSample application.

Go to Deployments -> select the application “SimpleSample”
Go to Configuration Tab -> make some changes [I changed the Session Timeout (in seconds): to 3601 from 3600 ]
Save [ you will asked for saving the deployment plan as plain.xml ] .save it

Now lets edit the deployment plan . open the deployment plan.xml file in a text editor.

An excerpt from the deployment plan.xml file generated on my desktop

<?xml version='1.0' encoding='UTF-8'?>
<deployment-plan xmlns="http://www.bea.com/ns/weblogic/deployment-plan" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/deployment-plan http://www.bea.com/ns/weblogic/deployment-plan/1.0/deployment-plan.xsd" global-variables="false">
<application-name>deploy_plan</application-name>
<variable-definition>
<variable>
<name>SessionDescriptor_invalidationIntervalSecs_12706221845760</name>
<value>50</value>
</variable>
</variable-definition>
<module-override>
<module-name>SimpleSample.war</module-name>
<module-type>war</module-type>
<module-descriptor external="true">
<root-element>weblogic-web-app</root-element>
<uri>WEB-INF/weblogic.xml</uri>
<variable-assignment>
<name>SessionDescriptor_invalidationIntervalSecs_12706221845760</name>
<xpath>/weblogic-web-app/session-descriptor/invalidation-interval-secs</xpath>
</variable-assignment>
<hash-code>1270622184576</hash-code>
</module-descriptor>
<module-descriptor external="false">
<root-element>web-app</root-element>
<uri>WEB-INF/web.xml</uri>
</module-descriptor>
<module-descriptor external="true">
<root-element>wldf-resource</root-element>
<uri>META-INF/weblogic-diagnostics.xml</uri>
</module-descriptor>
</module-override>
<config-root>C:\Documents and Settings\xprk477\Desktop\deploy_plan\plan</config-root>
</deployment-plan>

The mechanism works as follows first we need to define a variable in brown section and then assigning it to the application [purple section] . the xpath element in the variable-assignment is just a link to the element in the weblogic.xml descriptor. We have changed the session invalidation interval seconds, so now this value will reflect the value in weblogic.xml‘s session invalidation interval second .

Coming to our Demo , we will add a “WeblogicWebApp_ContextRoots” element to the deployment plan.xml file since we need to change the context root element from “SimpleSample” to some other .now my modified deployment plan.xml looks like this ,

<?xml version='1.0' encoding='UTF-8'?>
<deployment-plan xmlns="http://www.bea.com/ns/weblogic/deployment-plan" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/deployment-plan http://www.bea.com/ns/weblogic/deployment-plan/1.0/deployment-plan.xsd" global-variables="false">
<application-name>deploy_plan</application-name>
<variable-definition>
<variable>
<name>WeblogicWebApp_ContextRoots_12706221845760</name>
<value>"/songissong"</value>
</variable>
<variable>
<name>SessionDescriptor_invalidationIntervalSecs_12706221845760</name>
<value>50</value>
</variable>
</variable-definition>
<module-override>
<module-name>SimpleSample.war</module-name>
<module-type>war</module-type>
<module-descriptor external="true">
<root-element>weblogic-web-app</root-element>
<uri>WEB-INF/weblogic.xml</uri>
<variable-assignment>
<name>WeblogicWebApp_ContextRoots_12706221845760</name>
<xpath>/weblogic-web- app/context-root</xpath>
<operation>replace</operation>
</variable-assignment>
<variable-assignment>
<name>SessionDescriptor_invalidationIntervalSecs_12706221845760</name>
<xpath>/weblogic-web-app/session-descriptor/invalidation-interval-secs</xpath>
</variable-assignment>
<hash-code>1270622184576</hash-code>
</module-descriptor>
<module-descriptor external="false">
<root-element>web-app</root-element>
<uri>WEB-INF/web.xml</uri>
</module-descriptor>
<module-descriptor external="true">
<root-element>wldf-resource</root-element>
<uri>META-INF/weblogic-diagnostics.xml</uri>
</module-descriptor>
</module-override>
<config-root>C:\Documents and Settings\xprk477\Desktop\deploy_plan\plan</config-root>
</deployment-plan>

I just modified the web-context from “simpleSample” to “songissong” . In order to override the context root we need to do a replace operation in the variable assignment since the element already exists in the archive.

Now we need to update the current application with the changes we made to the plan ,

Go to Deployments -> select the Application “SimpleSample” -> click Update
In the next window we will see “Deployment plan path:” , select “Change Path” and select the updated the deployment plan.xml file and click Next. Select Finish

Now test your application and we will see that the context element is changed.


Happy learning , More to Come
Read More