Wednesday, December 19, 2012

javascript sync callback

js syncronise callback example :

<html>
    <head>
        <title>Haghe ostadi</title>
    </head>
    <body>

        <script language="javascript">
            function before(){
                this.call=function call(){
                    alert('call back!!');
                }
               
                after(this);
                alert('this would have been called first if it was async');
            }
            function after(x){
                for (i=0; i<100000000;i++){
                    var t= 'x2'=='x1';
                }
                x.call();
            }
            document.load=before();
        </script>

    </body>
</html>

Saturday, September 22, 2012

Subflow sample code for spring web flow 2.3.1.RELEASE

 The outer flow's path:
       src/main/webapp/WEB-INF/flows/outer/outer-flow.xml

 The inner flow's path:
       src/main/webapp/WEB-INF/flows/inner/inner-flow.xml


Inside outer flow:


    <subflow-state id="current-step" subflow="inner">
        <input name="actionrequest" value="100" type="java.lang.String"/>
        <transition on="submit" to="next-step"/>
    </subflow-state>


Inside inner flow:

    <input name="actionrequest"/>
    <view-state id="select-customer" >
        <transition on="submit" to="submit"/>
    </view-state>

    <end-state id="submit" commit="true" />

decision-state sample for spring web flow 2.3.1.RELEASE

Flow definition:

    <decision -state="-state" id="customerselectionRequired">
        <if
test="xBean.conditionCheck(flowRequestContext)"                                 then="nextStep1"
                else="nextStep2">
   
     </if>    
    </decision> 

    <view-state id="nextStep1"> 

    <view-state id="nextStep2"> 

      
xBean is a JSF bean and we send "flowRequestContext" to the bean to have access to the flow details, inside "conditionCheck" method.

here is the body of  "conditionCheck":


    public boolean customerSelectionRequired(RequestContext code){
        code.getActiveFlow().getId(); // The name of the flow!

        /*
         * implementation
         */
    }

Monday, June 25, 2012

XML versus JSON - What is Best for Your App?

One of the biggest debates in Ajax development today is JSON versus XML. This is at the heart of the data end of Ajax since you usually receive JSON or XML from the server side (although these are not the only methods of receiving data). Below I will be listing pros and cons of both methods.
If you have been developing Ajax applications for any length of time you will more than likely be familiar with XML data. You also know that XML data is very powerful and that there are quite a few ways to deal with the data. One way to deal with XML data is to simply apply a XSLT style sheet to the data (I won't have time in this post to go over the inconsistent browser support of XSLT, but it is something to look into if you want to do this). This is useful if you just want to display the data. However, if you want to do something programmatically with the data (like in the instance of a web service) you will need to parse the data nodes that are returned to the XMLHTTPRequest object (this is done by going through the object tag by tag and getting the needed data). Of course there are quite a few good pre-written libraries that can make going through the XML data easier and I recommend using a good one (I won't go into depth as to what libraries I prefer here, but perhaps in a future post). One thing to note is that if you want to get XML data from another domain you will have to use a server side proxy as the browser will not allow this type of receiving data across domains.
JSON is designed to be a more programmatic way of dealing with data. JSON (JavaScript Object Notation) is designed to return data as JavaScript objects. In an Ajax application using JSON you would receive text through the XMHTTPRequest object (or by directly getting the data through the script tag which I will touch on later) and then pass that text through an eval statement or use DOM manipulation to pass it into a script tag (if you haven't already read my post on using JSON without using eval click here to read the post). The power of this is that you can use the data in JavaScript without any parsing of the text. The down side would be if you just wanted to display the data there is no easy way to do this with JSON. JSON is great for web services that are coming from different domains since if you load the data through a script tag then you can get the data without a domain constraint.
The type of data that you use for your application will depend on quite a few factors. If you are going to be using the data programmatically then in most cases JSON is the better data method to use. On the other hand if you just want to display the data returned I would recommend XML. Of course there may be other factors such as if you are using a web service, which could dictate the data method. If you are getting data from a different domain and JSON is available this may be the better choice. For Ruby on Rails developers, if you would prefer to use JSON and XML is all that is available the 2.0 release allows you to change XML into JSON. One of the biggest reasons that people use JSON is the size of the data. In most cases JSON uses a lot less data to send to your application (of course this may very depending on the data and how the XML is formed).
I would recommend that you take a good look at the application that you are building and decide based on the above which type of data you should deal with. There may be more factors than the above including corporate rules and developer experience, but the above should have given you a good idea as to when to use either data method.
If you would like to contact me regarding any of the above you can make me your friend on Social Ajaxonomy and send a message to me through the service (Click here to go to my profile on Social Ajaxonomy).

By David Hurth
Source : http://www.ajaxonomy.com/2007/xslt/xml-versus-json-what-best-your-app

WSDL and WADL

Defining the Contract
An important part of any web service is the contract (or interface) which it defines between the service and any clients that might use it. This is important for a number of reasons: visualization with tools, interaction with other specifications (e.g., web service choreography), code generation, and enforcing a high-level agreement between the client and service provided (that still gives the service freedom to change the underlying implementation). Taken together, they give pretty compelling use cases for having web services contracts, although advocates of minimalism may disagree.
When IBM, Microsoft, and Ariba submitted WSDL 1.1 to the W3C in 2001 as a language for describing web services in conjunction with SOAP 1.1, HTTP POST and GET, and MIME, it quickly became a standard used by every SOAP toolkit. This happened in spite of the fact that it never progressed beyond being a W3C Note (which, according to W3C, is a document available for "discussion" and not officially endorsed by the W3C). In fact, though there is both a WSDL 1.1 and 1.2, WSDL 2.0 is the only version of the specification officially endorsed by the W3C.
With the rise in popularity of RESTful web services, there also became a need to describe contracts for these types of web services as well. Although WSDL 2.0 attempts to fill the gap by providing support for HTTP binding, another specification fills this need in an arguably better way: WADL, a specification developed at Sun by Marc Hadley. Though it has not been submitted to any official standards body (OASIS, W3C, etc.), WADL is promising because of its more comprehensive support for REST-style services.

Contract-First Development
In general there are two different approaches to development of web services in the real world: code-first or contract-first. Code-first is where existing code (generally methods/functions) is turned into a web service using tooling, e.g. the java2wsdl script in Apache Axis. Contract-first is where the actual web services contract is developed first (usually in WSDL), then this is then associated with the appropriate implementation--often using code generation with a tool such as the wsdl2java script in Apache Axis.
Though code-first is a highly popular approach, contract-first is generally considered to be best practice in order to shield the consumers of a service from changes in the underlying code base. By providing an XML-based contract, you are also protecting the client from the vagaries of how different Web Service toolkits generate contracts from code, differences in the way that language types are translated to XML types, etc. Though writing WSDL or WADL rather than code may involve some additional learning curve at the beginning, it pays off in the long run with more robustly designed services.

WSDL 1.1
An official W3C standard, the Web Services Description Language (WSDL) is an XML language for describing web services. WSDL 1.1 (which is still in wide use) has five major elements-
 types, message, portType, binding, and service
-in that order (figure 1 below); all these major elements may be defined 0 or more times in a WSDL document, except for <types>, which may be 0 or 1 time. Here's a short description of each:
  • <types>: This is where XML types to be used in the WSDL document are defined. Traditionally, this has meant using XML Schema, but newer versions of WSDL also support Relax NG.
  • <message>: This is the section where the input or output parts of an operation are defined, i.e. the "parameters" or "return types". It may have multiple child <part> elements, though WS-I forbids the use of more than one part per message in a document literal style service. The <part> itself may have an element (referring to a qualified XML element) or a type (referring to an XML Schema type) attribute; the later is use in RPC/encoded style services, the former in RPC/literal or Document/literal style services (see WSDL Styles).
  • <portType>: Here is where the operations that a web service offers are defined in terms of messages (input and output, with faults). Faults (referring to SOAP faults here) are the web service equivalent of the exception in languages like C++ or Java; most SOAP toolkits will translate SOAP faults into exceptions at runtime.
  • <binding>: This is the "how" of a service, specifying the binding of the operations defined in the portType(s) to specific protocols, such as SOAP.
  • <service>: This is the "where" of the service, specifying the address where a bound operation may be found.
These sections do not necessarily have to reside in the same XML document. In fact, it is common for there to be at least two different WSDL files, where one imports the other (see Abstract and Concrete WSDLs).
<definitions>
     <types>?
        <!-- Defines the XML types used in the WSDL -->
     </types>
     <message>*
        <part element="..." or type="..."/>*
     </message>
     <portType>*
       <!-- Defines the web service "methods" -->
       <operation>*
            <input message="..."/>?
            <output message="..."/>?
            <fault message="..."/>*
       </operation>
     </portType>
     <binding>*
        <operation>
           <!-- Binding of the operation to a protocol, e.g. SOAP -->
        </operation>
     </binding>
     <service>*
        <port name="..." binding="...">
            <!-- Specifies the address of a service,
            e.g., with soap:address -->
        </port>
     </service>
</definitions>
Figure 1: Major elements of WSDL 1.1. (1)
At first blush, having all these different parts of WSDL seems a bit overly complex--after all, do you really need to define both a part (message) for an operation as well as an operation separately (this was my first reaction...)? Well, WSDL 1.1 was created to be highly decoupled, and to maximize reuse of every possible piece; for example, one can define a message that can be used both as an input or an output, or can be used by multiple port type operations. The end result of this structure, however, was a bit unnecessary and hard to read, so the authors of the WSDL 2.0 improved this by removing the <message> section, and using defined elements instead.

WSDL 2.0
WSDL underwent a major renovation in version 2.0, changing the root tag to <description>, and ushering in many other changes and additions. I've already covered much of the structure in WSDL 1.1, so here I will describe mainly the differences:
  • <interface>: As the name implies, this section tends to resemble interfaces in Java, which makes sense since they serve very similar purposes. Like interfaces, they can define multiple operation "signatures" and can be extended for reusability. The <interface> replaces the <portType> of WSDL 1.1, and adds explicit input faults and output faults. The child <operation> elements here can also explicitly define message-exchange patterns in their pattern attribute (see below).
  • <binding>: This element has children that are identical to those of the interface, so that a binding can be specified for each. The major difference over version 1.1 is that bindings are re-usable. To be re-usable the binding simply omits the interface attribute; it may be specified later in the service declaration.
  • <service>: Child <port> are replaced by similar <endpoint> elements.
WSDL 2.0 also defines an explicit HTTP binding to all the methods: GET, POST, PUT, and DELETE. This becomes important for RESTful style web services. In essence, though, WSDL is service rather than resource oriented, so the fit with RESTful services is not as natural as it is in WADL.
<description>
     <types>?
        <!-- Defines the XML types used in the WSDL, as in 1.1 -->
     </types>
     <interface name="..." extends="...">*
          <fault element="..."/>*
          <operation pattern="..message pattern uri..">*
             <input element="..."/>*
             <output element="..."/>*
             <infault ref="..some fault..."/>*
             <outfault ref="..some fault"/>*
          </operation>
     </interface>
     <binding interface="..."?>
        <!-- The binding of a protocol to an interface, same structure
             as the interface element -->
     </binding>
     <service interface="...">
        <!-- Defines the actual addresses of the bindings, as in 1.1,
             but now "ports" are called "endpoints" -->
        <endpoint binding="..." address="..."/>*
     </service>
</description>
Figure 2: Major elements of WSDL 2.0. (1)

WSDL Styles
This developerWorks articledoes a great job of explaining the different styles of WSDL, so I will only summarize briefly here.
In general, an RPC (or "remote procedure call") style service will define the references in its message parts as XML Schema types; a Document style service will define element references on its message parts (the soap:binding will use the appropriate style attribute). An Encoded style will encode the types of the children of the soap:body in the SOAP message; a literal style will not encode them, but leave them as literal XML elements (the binding of input and output messages will have the appropriate use attribute).
RPC vs. Document (where "ns:myElement" is a reference to a defined element) WSDL definitions
<!-- RPC request message -->
<message name="input">
     <part name="param" type="xsd:int"/>
</message>

<!-- Document request message -->
<message name="input">
     <part name="param" element="ns:myElement"/>
</message>

Encoded Vs. Literal SOAP Messages

<!-- Encoded SOAP request -->
<soap:body>
   <param xsi:type="xsd:int">1</param>
<soap:body>

<!-- Literal SOAP request -->
<soap:body>
   <param>1<param>
<soap:body>
e, generally speaking, four distinct styles of WSDL: RPC/Encoded, RPC/Literal, Document/Literal, and Document/Literal Wrapped. As explained in Part 1, RPC/Encoded, once ubiquitous, is now pretty much dead: unless you have to interact with a legacy web service, use something else. Of the remaining styles, RPC/Literal has the drawback that you cannot really validate the types in the SOAP message. With Document/Literal, you can validate the types but you lose the name of the operation in the SOAP. This is where the Document/Literal Wrapped style comes in handy: it "wraps" the body of the document payload in an element that represents the operation name (it also has the additional benefit of enforcing only one child of soap:body as mandated by WS-I). The only real drawback of Document/Literal Wrapped is that you cannot "overload" web service operation names, but this is a minor quibble. Generally speaking, using this style of WSDL is your best bet, unless your SOAP toolkit is unable to work with it.

Message Exchange Patterns
Message exchange patterns are the "handshake protocol" of web services. They let a client know what type (in/out) of messages or faults must be exchanged, and in what order.
WSDL 1.1 defined 4 basic message exchange patterns:
  • One-way: An operation only receives an <input>.
  • Request-response: An operation receives a request, then issues a response. Here the <input> child of <operation> is defined before the <output>
  • Solicit-response: An operation sends a request, then waits for a response. Here the <output> would be defined before the <input>.
  • Notification: An operation sends a message only.
Using the document ordering of elements to establish the message exchange pattern was obviously a little too subtle, so WSDL 2.0 uses an explicit pattern attribute to define it. WSDL 2.0 also expands the number to 8 message exchange patterns, which can be categorized as inbound MEP (if the service receives the first message) or outbound MEP (if the service sends the first message):
  • In-only: Here a service operation only receives an inbound message, but does not reply. This MEP cannot use a fault. When referred to by an operation's pattern attribute, it has the value "http://www.w3.org/ns/wsdl/in-only".
  • Robust In-only: Identical to In-only, except that this type of MEP can trigger a fault. When referred to by an operation's pattern attribute, it has the value "http://www.w3.org/ns/wsdl/robust-in-only".
  • In-Out: Identical to the request-response of WSDL 1.1. A fault here replaces the out message. When referred to by an operation's pattern attribute, it has the value "http://www.w3.org/ns/wsdl/in-out".
  • In-Optional Out: Similar to In-Out, except that the out message is optional. When referred to by an operation's pattern attribute, it has the value "http://www.w3.org/ns/wsdl/in-opt-out".
  • Out-Only: The service operation produces an out-only message, and cannot trigger a fault. When referred to by an operation's pattern attribute, it has the value "http://www.w3.org/ns/wsdl/out-only".
  • Robust Out-Only: Similar to Out-Only, except that this type of MEP can trigger a fault. When referred to by an operation's pattern attribute, it has the value "http://www.w3.org/ns/wsdl/robust-out-only".
  • Out-Optional In: The service produces an out message first, which may optionally be followed by an inbound response. When referred to by an operation's pattern attribute, it has the value "http://www.w3.org/ns/wsdl/out-opt-in".
Abstract and Concrete WSDLs
A WSDL document can be divided into "abstract" and "concrete" portions that by convention often are defined in two or more files (where the concrete file imports the abstract one). The abstract elements are <types>, <message>, and <portType> (or <interface> in 2.0); the concrete ones are <binding> and <service>. Separating these two sections allows for maximal reuse and flexibility in defining services.
A great illustration of this principle is with WS-RP (Web Services for Remote Portlets), a specification essentially for exchanging portlet content between different servers (e.g., a Java application server and, say, Microsoft Sharepoint). WS-RP defines in its specifications all of the types and operations that will be used in the web service of the "producer". The producer server only has to specify the actual concrete WSDL.

WADL
WADL, or Web Application Description Language, is a specification developed to be an alternative to WSDL with specific support for RESTful web services. Whether or not WADL will be widely adopted is still an open question-- certainly it would help if it were submitted to a standards body--but it is interesting nevertheless to present it in contrast with WSDL. Here, instead of providing a more comprehensive overview (the 11/09/2006 specification is very easy to read), I'll provide an example to give a flavor of how it works in the form of the ever-popular stock quote example (Figure 3 below). Notice how it defines both resources and representations, as well as the methods that can be used to manipulate the resources.
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://research.sun.com/wadl/2006/10 wadl.xsd"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns:ex="http://www.example.org/types"
     xmlns="http://research.sun.com/wadl/2006/10">

     <grammars>
        <include href="ticker.xsd"/>
     </grammars>

     <resources base="http://www.example.org/services/">
        <resource path="getStockQuote">
           <method name="GET">
                <request>
                   <param name="symbol" style="query" type="xsd:string"/>
                </request>
                <response>
                   <representation mediaType="application/xml"
                       element="ex:quoteResponse"/>
                   <fault status="400" mediaType="application/xml"
                       element="ex:error"/>
                </response>
           </method>
        </resource>
     </resources>

</application>
Figure 3: A WADL example.
WADL does a nice job of capturing the style of REST. As with any other technology, though, most will wait to use it until it sees some significant adoption.

Conclusion
This has certainly been a whirlwind tour of WSDL and WADL. We've covered some of the most important points here in a fairly concise fashion, but there is quite a lot which can be said about the subject. I encourage anyone who wants to dive deeper to look at the References below (You can find References at the bottom of the original version of the article on the web).

By Brennan Spies
Source : http://www.ajaxonomy.com/2008/xml/web-services-part-2-wsdl-and-wadl

SOAP vs. REST

Developers new to web services are often intimidated by parade of technologies and concepts required to understand it: REST, SOAP, WSDL, XML Schema, Relax NG, UDDI, MTOM, XOP, WS-I, WS-Security, WS-Addressing, WS-Policy, and a host of other WS-* specifications that seem to multiply like rabbits. Add to that the Java specifications, such as JAX-WS, JAX-RPC, SAAJ, etc. and the conceptual weight begins to become heavy indeed. In this series of articles I hope to shed some light on the dark corners of web services and help navigate the sea of alphabet soup (1). Along the way I'll also cover some tools for developing web services, and create a simple Web Service as an example. In this article I will give a high-level overview of both SOAP and REST.

Introduction
There are currently two schools of thought in developing web services: the traditional, standards-based approach (SOAP) and conceptually simpler and the trendier new kid on the block (REST). The decision between the two will be your first choice in designing a web service, so it is important to understand the pros and cons of the two. It is also important, in the sometimes heated debate between the two philosophies, to separate reality from rhetoric.

SOAP
In the beginning there was...SOAP. Developed at Microsoft in 1998, the inappropriately-named "Simple Object Access Protocol" was designed to be a platform and language-neutral alternative to previous middleware techologies like CORBA and DCOM. Its first public appearance was an Internet public draft (submitted to the IETF) in 1999; shortly thereafter, in December of 1999, SOAP 1.0 was released. In May of 2000 the 1.1 version was submitted to the W3C where it formed the heart of the emerging Web Services technologies. The current version is 1.2, finalized in 2005. The examples given in this article will all be SOAP 1.2.
Together with WSDL and XML Schema, SOAP has become the standard for exchanging XML-based messages. SOAP was also designed from the ground up to be extensible, so that other standards could be integrated into it and there have been many, often collectively referred to as WS-*: WS-Addressing, WS-Policy, WS-Security, WS-Federation, WS-ReliableMessaging, WS-Coordination, WS-AtomicTransaction, WS-RemotePortlets, and the list goes on. Hence much of the perceived complexity of SOAP, as in Java, comes from the multitude of standards which have evolved around it. This should not be reason to be too concerned: as with other things, you only have to use what you actually need.The basic structure of SOAP is like any other message format (including HTML itself): header and body. In SOAP 1.2 this would look something like :

<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Header>
<!- Header information here ->
</env:Header>
<env:Body>
<!- Body or "Payload" here, a Fault if error happened ->
</env:Body>
</env:Envelope> 

Note that the <Header> element is optional here, but the <Body> is mandatory.

The SOAP <Header>
SOAP uses special attributes in the standard "soap-envelope" namespace to handle the extensibility elements that can be defined in the header. The most important of these is the mustUnderstand attribute. By default, any element in the header can be safely ignored by the SOAP message recipient unless the the mustUnderstand attribute on the element is set to "true" (or "1", which is the only value recognized in SOAP 1.1). A good example of this would be a security token element that authenticates the sender/requestor of the message. If for some reason the recipient is not able to process these elements, a fault should be delivered back to the sender with a fault code of MustUnderstand.
Because SOAP is designed to be used in a network environment with multiple intermediaries (SOAP "nodes" as identified by the <Node> element), it also defines the special XML attributes role to manage which intermediary should process a given header element and relay, which is used to indicate that this element should be passed to the next node if not processed in the current one.
The SOAP <Body>
The SOAP body contains the "payload" of the message, which is defined by the WSDL's <Message> part. If there is an error that needs to be transmitted back to the sender, a single <Fault> element is used as a child of the <Body>.
The SOAP <Fault>The <Fault> is the standard element for error handling. When present, it is the only child element of the SOAP<Body>. The structure of a fault looks like :

<env:Fault xmlns:m="http://www.example.org/timeouts">
<env:Code>
<env:Value>env:Sender</env:Value>
<env:Subcode>
<env:Value>m:MessageTimeout</env:Value>
</env:Subcode>
</env:Code>
<env:Reason>
<env:Text xml:lang="en">Sender Timeout</env:Text>
</env:Reason>
<env:Detail>
<m:MaxTime>P5M</m:MaxTime>
</env:Detail>
</env:Fault>
 
Here, only the <Code> and <Reason> child elements are required, and the <Subcode> child of <Code> is also optional. The body of the Code/Value element is a fixed enumeration with the values:
  • VersionMismatch: this indicates that the node that "threw" the fault found an invalid element in the SOAP envelope, either an incorrect namespace, incorrect local name, or both.
  • MustUnderstand: as discussed above, this code indicates that a header element with the attribute mustUnderstand="true" could not be processed by the node throwing the fault. A NotUnderstood header block should be provided to detail all of the elements in the original message which were not understood.
  • DataEncodingUnknown: the data encoding specified in the envelope's encodingSytle attribute is not supported by the node throwing the fault.
  • Sender: This is a "catch-all" code indicating that the message sent was not correctly formed or did not have the appropriate information to succeed.
  • Receiver: Another "catch-all" code indicating that the message could not be processed for reasons attributable to the processing of the message rather than to the contents of the message itself.
Subcodes, however, are not restricted and are application-defined; these will commonly be defined when the fault code is Sender or Receiver. The <Reason> element is there to provide a human-readable explanation of the fault. The optional <Detail> element is there to provide additional information about the fault, such as (in the example above) the timeout value. <Fault> also has optional children <Node> and <Role>, indicating which node threw the fault and the role that the node was operating in (see role attribute above) respectively.
SOAP Encoding
Section 5 of the SOAP 1.1 specification describes SOAP encoding, which was originally developed as a convenience for serializing and de-serializing data types to and from other sources, such as databases and programming languages. Problems, however, soon arose with complications in reconciling SOAP encoding and XML Schema, as well as with performance. The WS-I organization finally put the nail in the coffin of SOAP encoding in 2004 when it released the first version of the WS-I Basic Profile, declaring that only literal XML messages should be used (R2706). With the wide acceptance of WS-I, some of the more recent web service toolkits do not provide any support for (the previously ubiquitous) SOAP encoding at all.
A Simple SOAP Example
Putting it all together, below is an example of a simple request-response in SOAP for a stock quote. Here the transport binding is HTTP.

The request:GET /StockPrice HTTP/1.1
Host: example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"
xmlns:s="http://www.example.org/stock-service">
<env:Body>
<s:GetStockQuote>
<s:TickerSymbol>IBM</s:TickerSymbol>
</s:GetStockQuote>
</env:Body>
</env:Envelope>
The response:HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"
xmlns:s="http://www.example.org/stock-service">
<env:Body>
<s:GetStockQuoteResponse>
<s:StockPrice>45.25</s:StockPrice>
</s:GetStockQuoteResponse>
</env:Body>
</env:Envelope>
 
If you play your cards right, you may never have to actually see a SOAP message in action; every SOAP engine out there will do its best to hide it from you unless you really want to see it. If something goes wrong in your web service, however, it may be useful to know what one looks like for debugging purposes.

REST
Much in the way that Ruby on Rails was a reaction to more complex web application architectures, the emergence of the RESTful style of web services was a reaction to the more heavy-weight SOAP-based standards. In RESTful web services, the emphasis is on simple point-to-point communication over HTTP using plain old XML (POX).
The origin of the term "REST" comes from the famous thesis from Roy Fielding describing the concept of Representative State Transfer (REST). REST is an architectural style that can be summed up as four verbs (GET, POST, PUT, and DELETE from HTTP 1.1) and the nouns, which are the resources available on the network (referenced in the URI). The verbs have the following operational equivalents:HTTP CRUD Equivalent
==============================
GET read
POST create,update,delete
PUT create,update
DELETE delete
A service to get the details of a user called 'dsmith', for example, would be handled using an HTTP GET to http://example.org/users/dsmith. Deleting the user would use an HTTP DELETE, and creating a new one would mostly likely be done with a POST. The need to reference other resources would be handled using hyperlinks (the XML equivalent of HTTP's href, which is XLinks' xlink:href) and separate HTTP request-responses.
A Simple RESTful Service
Re-writing the stock quote service above as a RESTful web service provides a nice illustration of the differences between SOAP and REST web services.

The request:GET /StockPrice/IBM HTTP/1.1
Host: example.org
Accept: text/xml
Accept-Charset: utf-8
The response:HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: nnn
<?xml version="1.0"?>
<s:Quote xmlns:s="http://example.org/stock-service">
<s:TickerSymbol>IBM</s:TickerSymbol>
<s:StockPrice>45.25</s:StockPrice>
</s:Quote>
 
Though slightly modified (to include the ticker symbol in the response), the RESTful version is still simpler and more concise than the RPC-style SOAP version. In a sense, as well, RESTful web services are much closer in design and philosophy to the Web itself.

Defining the Contract
Traditionally, the big drawback of REST vis-a-vis SOAP was the lack of any way of specifying a description/contract for the web service. This, however, has changed since WSDL 2.0 defines a full compliment of non-SOAP bindings (all the HTTP methods, not just GET and POST) and the emergence of WADL as an alternative to WSDL. This will be discussed in more detail in coming articles.

Summary and Pros/Cons
SOAP and RESTful web services have a very different philosophy from each other. SOAP is really a protocol for XML-based distributed computing, whereas REST adheres much more closely to a bare metal, web-based design. SOAP by itself is not that complex; it can get complex, however, when it is used with its numerous extensions (guilt by association).
To summarize their strengths and weaknesses:

** SOAP **
Pros:
  • Langauge, platform, and transport agnostic
  • Designed to handle distributed computing environments
  • Is the prevailing standard for web services, and hence has better support from other standards (WSDL, WS-*) and tooling from vendors
  • Built-in error handling (faults)
  • Extensibility
Cons:
  • Conceptually more difficult, more "heavy-weight" than REST
  • More verbose
  • Harder to develop, requires tools
** REST **
Pros:
  • Language and platform agnostic
  • Much simpler to develop than SOAP
  • Small learning curve, less reliance on tools
  • Concise, no need for additional messaging layer
  • Closer in design and philosophy to the Web
Cons:
  • Assumes a point-to-point communication model--not usable for distributed computing environment where message may go through one or more intermediaries
  • Lack of standards support for security, policy, reliable messaging, etc., so services that have more sophisticated requirements are harder to develop ("roll your own")
  • Tied to the HTTP transport model
By Brennan Spies
Source : http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest

Monday, June 11, 2012

jquery datepicker localization persian , fa

<script type="text/javascript">

jQuery(function ($) {
    $.datepicker.regional['fa'] = {
        closeText:'بستن',
        prevText:'&#x3c;قبلي',
        nextText:'بعدي&#x3e;',
        currentText:'امروز',
        monthNames:['فروردين', 'ارديبهشت', 'خرداد', 'تير', 'مرداد', 'شهريور', 'مهر', 'آبان', 'آذر', 'دي', 'بهمن', 'اسفند'],
        monthNamesShort:['فروردين', 'ارديبهشت', 'خرداد', 'تير', 'مرداد', 'شهريور', 'مهر', 'آبان', 'آذر', 'دي', 'بهمن', 'اسفند'],
        dayNames:['يکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'],
        dayNamesShort:['يك', 'دو', 'سه', 'چه', 'پن', 'جم', 'شن'],
        dayNamesMin: ['ي', 'د', 'س', 'چ ', 'پ', 'ج ', 'ش'],
        weekHeader:'هف',
        dateFormat:'yy/mm/dd',
        firstDay:6,
        isRTL:true,
        showMonthAfterYear:false,
        yearSuffix:'',
        timeOnlyTitle: 'افقط زمان' ,
        timeText: 'زمان',
        hourText: 'ساعت',
        minuteText: 'دقيقه',
        secondText: 'ثانيه',
        ampm: false,
        month: 'ماه',
        week: 'هفته',
        day: 'روز',
        allDayText: 'همه روزها'
    };
    $.datepicker.setDefaults($.datepicker.regional['fa']);
});
</script>

Primefaces calendar localization persian , fa

<script type="text/javascript">

PrimeFaces.locales ['fa'] = {
    closeText:'بستن',
    prevText:'&#x3c;قبلي',
    nextText:'بعدي&#x3e;',
    currentText:'امروز',
    monthNames:['فروردين', 'ارديبهشت', 'خرداد', 'تير', 'مرداد', 'شهريور', 'مهر', 'آبان', 'آذر', 'دي', 'بهمن', 'اسفند'],
    monthNamesShort:['فروردين', 'ارديبهشت', 'خرداد', 'تير', 'مرداد', 'شهريور', 'مهر', 'آبان', 'آذر', 'دي', 'بهمن', 'اسفند'],
    dayNames:['يکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'],
    dayNamesShort:['يك', 'دو', 'سه', 'چه', 'پن', 'جم', 'شن'],
    dayNamesMin: ['ي', 'د', 'س', 'چ ', 'پ', 'ج ', 'ش'],
    weekHeader:'هف',
    dateFormat:'yy/mm/dd',
    firstDay:6,
    isRTL:true,
    showMonthAfterYear:false,
    yearSuffix:'',
    timeOnlyTitle: 'افقط زمان' ,
    timeText: 'زمان',
    hourText: 'ساعت',
    minuteText: 'دقيقه',
    secondText: 'ثانيه',
    ampm: false,
    month: 'ماه',
    week: 'هفته',
    day: 'روز',
    allDayText: 'همه روزها'
};

</script>

Sunday, May 27, 2012

Spring ACL based permission management

Key Concepts
Spring Security's domain object instance security capabilities center on the concept of an access control  list  (ACL). Every domain object instance in your system has its own ACL, and the ACL records details of  ho can and can't work with that domain object. With this in mind, Spring Security delivers three main  CL-related  capabilities to your application :
  • A way of efficiently retrieving ACL entries for all of your domain objects (and modifying those  CLs)
  •  A way of ensuring a given principal is permitted to work with your objects, before methods  re called
  •  A way of ensuring a given principal is permitted to work with your objects (or something they  return), after methods are called.
The tables are presented below in order of size in a typical Spring Security ACL deployment, with the table with the most rows listed last :
  • ACL_SID allows us to uniquely identify any principal or authority in the system ("SID" stands for "security identity"). The only columns are the ID, a textual representation of the SID, and a flag to indicate whether the textual representation refers to a principal name or a GrantedAuthority. Thus, there is a single row for each unique principal or GrantedAuthority. When used in the context of receiving a permission, a SID is generally called a "recipient".
  •  ACL_CLASS allows us to uniquely identify any domain object class in the system. The only columns are the ID and the Java class name. Thus, there is a single row for each unique Class we wish to store ACL permissions for.
  •  ACL_OBJECT_IDENTITY stores information for each unique domain object instance in the system. Columns include the ID, a foreign key to the ACL_CLASS table, a unique identifier so we know which ACL_CLASS instance we're providing information for, the parent, a foreign key to the ACL_SID table to represent the owner of the domain object instance, and whether we allow ACL entries to inherit from any parent ACL. We have a single row for every domain object instance we're storing ACL permissions for.
  •  Finally, ACL_ENTRY stores the individual permissions assigned to each recipient. Columns include a foreign key to the ACL_OBJECT_IDENTITY, the recipient (ie a foreign key to ACL_SID), whether we'll be auditing or not, and the integer bit mask that represents the actual permission being granted or denied. We have a single row for every recipient that receives a permission to work with a domain object.
Now that we've provided a basic overview of what the ACL system does, and what it looks like at a table structure, let's explore the key interfaces. The key interfaces are:
  • Acl: Every domain object has one and only one  Acl object, which internally holds the AccessControlEntrys as well as knows the owner of the Acl. An Acl does not refer directly to the domain object, but instead to an ObjectIdentity. The Acl is stored in the ACL_OBJECT_IDENTITY table.
  •  AccessControlEntry: An  Acl holds multiple  AccessControlEntrys, which are often abbreviated as ACEs in the framework. Each ACE refers to a specific tuple of Permission, Sid and Acl. An ACE an also be granting or non-granting and contain audit settings. The ACE is stored in the ACL_ENTRY table.
  •  Permission: A permission represents a particular immutable bit mask, and offers convenience functions for bit masking and outputting information. The basic permissions presented above (bits 0 through 4) are contained in the BasePermission class.
  •  Sid: The ACL module needs to refer to principals and  GrantedAuthority[]s. A level of indirection is provided by the Sid interface, which is an abbreviation of "security identity". Common classes include PrincipalSid (to represent the principal inside an Authentication object) and GrantedAuthoritySid. The security identity information is stored in the ACL_SID table.
  •  ObjectIdentity: Each domain object is represented internally within the ACL module by an ObjectIdentity. The default implementation is called ObjectIdentityImpl.
  •  AclService: Retrieves the  Acl applicable for a given  ObjectIdentity. In the included implementation (JdbcAclService), retrieval operations are delegated to a LookupStrategy. The LookupStrategy provides a highly optimized strategy for retrieving ACL information, using  atched retrievals (BasicLookupStrategy) and supporting custom implementations that leverage  aterialized views, hierarchical queries and similar performance-centric, non-ANSI SQL  apabilities.
  •  MutableAclService: Allows a modified Acl to be presented for persistence. It is not essential to  se this interface if you do not wish.
Getting Started :
To get starting using Spring Security's ACL capability, you will need to store your ACL information somewhere. This necessitates the instantiation of a DataSource using Spring. The DataSource is then injected into a JdbcMutableAclService and BasicLookupStrategy instance. The latter provides high-performance ACL retrieval capabilities, and the former provides mutator capabilities. Refer to one of the samples that ship with Spring Security for an example configuration. You'll also need to populate the database with the four ACL-specific tables listed in the last section (refer to the ACL samples for the appropriate SQL statements).
Once you've created the required schema and instantiated JdbcMutableAclService, you'll next need to ensure your domain model supports interoperability with the Spring Security ACL package. Hopefully ObjectIdentityImpl will prove sufficient, as it provides a large number of ways in which it can be used. Most people will have domain objects that contain a public Serializable getId() method. If the return type is long, or compatible with long (eg an int), you will find you  need not give further consideration to ObjectIdentity issues. Many parts of the ACL module rely on long identifiers. If you're not using long (or an int, byte etc), there is a very good chance you'll need to reimplement a number of classes. We do not intend to support non-long identifiers in Spring Security's ACL module, as longs are already compatible with all database sequences, the most common identifier data type, and are of sufficient length to accommodate all common usage scenarios.
The following fragment of code shows how to create an Acl, or modify an existing Acl:

 // Prepare the information we'd like in our access control entry (ACE)
ObjectIdentity oi = new ObjectIdentityImpl(Foo.class, new Long(44));
Sid sid = new PrincipalSid("Samantha");
Permission p = BasePermission.ADMINISTRATION;
// Create or update the relevant ACL
MutableAcl acl = null;
try {
  acl = (MutableAcl) aclService.readAclById(oi);
} catch (NotFoundException nfe) {
  acl = aclService.createAcl(oi);
}
// Now grant some permissions via an access control entry (ACE)
acl.insertAce(acl.getEntries().length, p, sid, true);
aclService.updateAcl(acl);
 
In the example above, we're retrieving the ACL associated with the "Foo" domain object with identifier number 44. We're then adding an ACE so that a principal named "Samantha" can "administer" the object. The code fragment is  relatively self-explanatory, except the insertAce method. The first argument to the insertAce method is determining at what position in the Acl the new entry will be inserted. In the example above, we're just putting the new ACE at the end of the existing ACEs. The final argument is a boolean indicating whether the ACE is granting or denying. Most of the time it will be granting (true), but if it is denying (false), the permissions are effectively being blocked.
Spring Security does not provide any special integration to automatically create, update or delete ACLs as part of your DAO or repository operations. Instead, you will need to write code like shown above for your individual domain objects. It's worth considering using AOP on your services layer to automatically integrate the ACL information with your services layer operations. We've found this quite an effective approach in the past.
Once you've used the above techniques to store some ACL information in the database, the next step is to actually use the ACL information as part of authorization decision logic. You have a number of choices here. You could write your  own AccessDecisionVoter or AfterInvocationProvider that respectively fires before or after a method invocation. Such classes would use  AclService to retrieve the relevant ACL and then call  Acl.isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode) to decide whether permission is granted or denied. Alternately, you could use our  AclEntryVoter,  AclEntryAfterInvocationProvider or  AclEntryAfterInvocationCollectionFilteringProvider classes. All of  these classes provide a declarative-based approach to evaluating ACL information at runtime, freeing you from needing to write any code. Please refer to the sample applications to learn how to use these classes.

Exctracted from : Spring Security: Reference Documentation v3.1.0

MyBatis Insert

The Mapper interface method accepts the Object :

void insertAccount(Account account);

The Mapper xml uses the properties :

<insert id="insertAccount" parameterType="x.y.z.Account">

               INSERT INTO ACCOUNT (EMAIL, FIRSTNAME, LASTNAME, STATUS, ADDR1, ADDR2, CITY,
               STATE, ZIP, COUNTRY, PHONE, USERID)

VALUES

              (#{email}, #{firstName}, #{lastName}, #{status}, #{address1},  #{address2,jdbcType=VARCHAR}, 
              #{city}, #{state}, #{zip}, #{country}, #{phone}, #{username})

</insert>

Monday, May 14, 2012

I can't live, If living is without you !!!

Don't hesitate to download Ubuntu 12.4LTS

Http://www.ubuntu.com

Spring - Websphere - JNDI - JMS configuration

Define a JNDI template that other beans will be using for retrieving JNDI objects.
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.provider.url">smqp://localhost:4001/timeout=10000</prop>
<prop key="java.naming.factory.initial">com.swiftmq.jndi.InitialContextFactoryImpl</prop>
</props>
</property>
</bean>

Create a connection factory. I used Topic instead of Queue for my experiment.
<bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref ="jndiTemplate"/>
<property name="jndiName" value="TopicConnectionFactory"/>
</bean>
Create a Spring specific JMS template that will be used for sending JMS messages. Note that we are providing connection factory and a destination to the template. Destination is the message destination which is in our case named ‘testtopic’.
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="defaultDestination" ref="destination"/>
<property name="pubSubDomain" value="true"/>
<property name="deliveryPersistent" value="true"/>
<property name="deliveryMode" value="2"/>
</bean>
<bean id="destination" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplate"/>
<property name="jndiName" value="testtopic"/>
</bean>
I create a MsgSender class and inject jmsTemplate and destination to it. This class simply sends a number of JMS messages to the provided destination using the template.
<bean id="sender" class="myexp.spring.MsgSender">
<property name="destination" ref="destination"/>
<property name="jmsTemplate" ref="jmsTemplate"/>
</bean>
After sending the messages, we need to receive it right? :) So here we are defining a Spring specific message listener container and providing a message listener to the container. For each message received, the onMessage method of the message listener will be called. In my experiment I simply printout the message in console.
<bean id="messageListener" class="myexp.spring.ExampleListener"/>
<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="destination"/>
<property name="messageListener" ref="messageListener"/>
<property name="sessionAcknowledgeModeName" value="AUTO_ACKNOWLEDGE"/>
</bean>
My message sender is simple, it sends Text Messages a number of times, like this -

jmsTemplate.send(destination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
String msgText = "Message " + messageIndex;
System.out.println("Publishing - " + msgText);
Message message = session.createTextMessage(msgText);
message.setLongProperty("startTime", System.currentTimeMillis());
return message;
}
});

I an addition to a String message, I am also adding additional property into the message. The listener class must implement javax.jms.MessageListener and implement the following method -

public void onMessage(Message message) {
TextMessage msg = (TextMessage) message;
System.out.println("Reading - " + msg.getText());
}

see :

Wednesday, May 9, 2012

How t send multiple parameters to mybatis xml mapper file?

Problem

Using a single parameter is very easy. The example on page 30 of the user guide shows this (see below). But How do we use multiple parameters?
UserMapper.xml:
<select id=”selectUser” parameterType=”int” resultType=”User”>
  select id, username, hashedPassword
  from some_table
  where id = #{id}</sql>
UserMapper.java:
public interface UserMapper{
  User selectUser(int id);
}

Solution

  1. Add the @Param("name") to your Mapper.java
  2. Change the parameterType in Mapper.xml to "map"

1. Add the @Param("name") to your Mapper.java

UserMapper.java:
import org.apache.ibatis.annotations.Param;
public interface UserMapper{
   User selectUser(@Param("username") String usrename, 
                   @Param("hashedPassword") String hashedPassword);
}

2. Change the parameterType in Mapper.xml to "map"

UserMapper.xml:
<select id=”selectUser” parameterType=”map” resultType=”User”>
  select id, username, hashedPassword
  from some_table
  where username = #{username}
  and hashedPassword = #{hashedPassword}</sql>
 
 
see :
http://code.google.com/p/mybatis/wiki/HowToSelectMultipleParams 

Saturday, April 21, 2012

Configuring the WebSphere node agent to run as a Windows service

  1. Change to the \bin directory where WebSphere is installed, for example:
       C:\Program Files\IBM\WebSphere\AppServer\bin
  2. Run the following command:
      wasservice -add ctgNode01_nodeagent 
        -servername nodeagent 
        -profilePath "...\IBM\WebSphere\AppServer\profiles\ctgAppSrv01" 
        -wasHome "...\IBM\WebSphere\AppServer" 
        -logFile "...\IBM\WebSphere\AppServer\profiles\ctgAppSrv01\logs\nodeagent\startNode.log" 
        -logRoot "...\IBM\WebSphere\AppServer\ctgAppSrv01\logs\nodeagent" 
        -restart true 
        -startType automatic
  3. Use a registry editor, such as Regedit, and open this key:
      HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\IBMWAS61Service - ctgCellManager01
  4. Create a Multi-String Value named DependOnService.
  5. Enter the value "IBMWAS61Service - ctgNode01_nodeagent" for this new key. This will make the WAS Cell Manager service dependant on the node agent service starting first.

see : http://publib.boulder.ibm.com/infocenter/tivihelp/v10r1/index.jsp?topic=%2Fcom.ibm.srm.doc_7.1%2Finstalling%2Fsrc%2Ft_ccmdb_confignodeagentrtorunasservice.html