venerdì 3 agosto 2012

Dependency Injection in EJB3.0


To facilitate test driven development(TDD), the EJB 3.0 specification allows you to use annotations to inject dependencies through annotations on fields or setter methods. 

Instead of complicated XML ejb-refs or resource refs, you can use the @EJB and @Resource annotations to set the value of a field or to call a setter method within your session bean with anything registered within JNDI. 

You can use the @EJB annotation to inject EJB references and @Resource to access datasources. 


The example shows two ways to get access to the Calculator EJB. 
One is:
 
@EJB
private Calculator calculator;
 
or
 
private Calculator set;

@EJB(beanName="org.jboss.tutorial.injection.bean.CalculatorBean")
public void setCalculator(Calculator c)
{
   set = c;
}
 
 
When the ShoppingCartBean instance is created, the EJB container will set the calculator field using the jndiName of that particular referenced EJB. 

Another example should be the message driven context inside an MDB.

@Resource
private MessageDrivenContext mdc; 


The @javax.annotation.Resource annotation allows you to inject resources. 

@Resource(mappedName="DefaultDS")
private javax.sql.DataSource ds;

In JBoss, whenever the mappedName() attribute is specified (
@Resource, @EJB), jboss will use that as the GLOBAL jndi name to look it up.

The @Resource annotation is used to inject these singletons as well.

   @Resource
 javax.ejb.SessionContext ctx;
   @Resource
 javax.ejb.TimerService timer;
   @Resource
 javax.ejb.UserTransaction ut;

@EJB and @Resource also create an entry within the 
JNDI ENC of the bean.  So, the above @EJB injection
will create an entryfor the reference calculator beanver is 
currently being refactored in this area, 
so an EJB3 specific namespace is being used.
   







J2EE Basic - Message driven bean EJB 3 API






Session beans allow you to send JMS messages and to receive them synchronously, but not asynchronously.

Message-Driven Bean

Session beans allow you to send JMS messages and to receive them synchronously, but not asynchronously. 

To receive messages asynchronously,  a Message-driven bean is used. 

Message driven beans are the light weight components used for communication via messages (e.g., email or IM messages). 

In message driven beans, the messaging service is in asynchronous mode because the user is not intended to get the instant result.
Message-driven beans can implement any messaging type. 

Most commonly, they implement the Java Message Service (JMS) technology.

Message-driven beans have the following characteristics:
  • A message-driven bean's instances retain no data or conversational state for a specific client i.e. they are stateless.
  • A single message-driven bean can process messages from multiple clients.
  • They are invoked asynchronously.
  • They can be transaction-aware.
  • They do not represent directly shared data in the database, but they can access and update this data.
  • A message-driven bean has only a bean class i.e. unlike a session bean, the clients don't access message-driven beans through interfaces.
  • They don't have the remote or local interfaces that define client access.
The given diagram shows the working process of a Message driven bean.

In Message driven beans (MDB), the client components don't locate message-driven beans and invoke methods directly. 

Instead, The JMS clients send messages to message queues managed by the JMS server (e.g., an email inbox can be a message queue) for which the javax.jms.MessageListener interface is implemented. 

The message queue is monitored by a special kind of EJB(s) - Message Driven Beans (MDBs) That processes the incoming messages and perform the services requested by the message. 

The MDBs are the end-point for JMS service request messages. You assign a message-driven bean's destination during deployment by using Application Server resources.

JMS:
The Java Message Service (JMS) is an API for Java messaging clients. JMS provides two programming models: 
  1.  point-to-point and 
  2.  publish-and-subscribe.

In the point-to-point model, one sender puts a message on a queue that is delivered to only one receiver. 

The publish-and-subscribe model adds a broadcast mode in which any number of senders can add messages to a topic, and any number of recievers receive all messages posted to topics. 

JMS queues and topics are bound in the JNDI environment and made available to J2EE applications.

Example:
Our application assumes the point-to-point model, and requires setting up a queue with a QueueConnectionFactory in JMS. 

This section shows, how to implement an MDB with EJB 3.0 describing the source code of a simple message-driven bean application.
In this example, we are going to implement a Message-driven bean application named "massage" that has the following components:
  • A client application that sends several messages to a queue: MessageClient
     
  • A message-driven bean that asynchronously receives and processes the messages that are sent to the queue: MessageBean


    Code for the client application:
    package mdb; 
    import javax.jms.*;
    import javax.naming.*;
    import java.text.*;

    import javax.annotation.*;

    @Resource(mappedName="jms/Queue")
    class MessageConn{
     
      private static Queue queue = null;
      QueueConnectionFactory factory = null;
      QueueConnection connection = null;
      QueueSender sender = null;
      QueueSession session = null;

      public MessageConn(){
      try {
      
      //client creates the connection, session, and message sender:
      connection = factory.createQueueConnection();
      session = connection.createQueueSession(false, 
                                QueueSession.AUTO_ACKNOWLEDGE);
       
      sender = session.createSender(queue);
      //create and set a message to send
      TextMessage msg = session.createTextMessage();
      for (int i = 0; i < 5; i++) {
        msg.setText("This is my sent message " + (i + 1));
        //finally client sends messages
        //asynchronously to the queue

        sender.send(msg);
      } 
      System.out.println("Sending message"); 
     session.close ();
      } catch (Exception e) {
      e.printStackTrace ();
      }
      }
    }
      
     public class MessageClient{
      public static void main(String[] args){
      MessageConn msgcon = new MessageConn();
      }
     }
      

    Description of the given code:

    In the given code of MessageClient application, 
    the javax.jms.* package is imported for extending the Queue, QueueConnectionFactory, QueueConnection, QueueSender, and QueueSession class.
     
    After you get the QueueConnectionFactory object, you use its createQueueConnection to construct a QueueConnection object, like this:

    connection = factory.createQueueConnection( );

    Then, you use the createQueueSession method of the QueueConnection interface to create a QueueSession object, as in the following code:

    session = connection.createQueueSession(false, 
    QueueSession.AUTO_ACKNOWLEDGE);

    Note that you pass false as the first argument to the createQueueSession method to indicate that you are not creating a transactional session object.

    Next, you can call the createSender method of the QueueSession interface, passing a Queue object. The return value of this method is a message producer, which is a QueueSender:

    sender = session.createSender(queue);

    Then you create a TextMessage object based on the message received by passing the text for the TextMessage to the createTextMessage method of the QueueSession object and then set the text to the object of TextMessage 

    TextMessage msg = session.createTextMessage( );
    msg.setText("This is my sent message " + (i + 1));  

    Now, you are ready to send the new message. You do this by calling the send method of the QueueSender object, as you see here:

    sender.send(msg);

    The JMS resource is mapped to the JNDI name of the destination from which the bean receives messages. The New Message-Driven Bean wizard has already created the JMS resources for us. The EJB 3.0 API enables us to look up objects in the JNDI namespace from within the bean class so that we do not need to configure deployment descriptors to specify the JMS resources. The EJB 3.0 specifications allow us to use annotations to introduce resources directly into a class.
    The MDB's connection process can be seen in the figure shown below:

    javax.annotation.Resource(@Resource):

    The @Resource method specifies a dependence on an external resource, such as a JDBC data source or a JMS destination or connection factory.

    If you specify the annotation on a field or method, the EJB container injects an instance of the requested resource into the bean when the bean is initialized. 

    If you apply the annotation to a class, the annotation declares a resource that the bean will look up at runtime.

    The mappedName attribute of the annotation Resource specifies the global JNDI name of the dependent resource. For example:
     
    @Resource(mappedName ="jms/Queue")

    Specifies that the JNDI name of the dependent resources is jms/Queue and deployed in the JEE Server JNDI tree.

    For Web-client:
    In a Web-client application "jms/Queue" and ConnectionFactory" argument are used in the JNDI lookup. 

    Both are logical JNDI names, and use the outbound connectivity provided by the JMS resource adapter. Make the JNDI lookup to use a Web Service shown as.

      InitialContext ctx = new InitialContext();
      queue = (Queue) ctx.lookup("
    jms/Queue");
      QueueConnectionFactory factory =
      (QueueConnectionFactory) ctx.lookup("ConnectionFactory");
      connection = factory.createQueueConnection();
      session = cnn.createQueueSession(false,
          QueueSession.AUTO_ACKNOWLEDGE);

    Code for the message-driven bean:

    The MessageBean class demonstrates the following requirements to its implementation:

  • In EJB 3.0, the MDB bean class is annotated with the @MessageDriven annotation that specifies, which message queue monitors the MDB (i.e., jms/Queue). 
    If the queue does not exist, the EJB container automatically creates it at deploy time. 
    There is no XML configuration file needed!
    For the Application Server, the @MessageDriven annotation typically contains a mappedName attribute that specifies the JNDI name of the destination from which the bean will consume messages.

  • The class must be defined as public and must contain a public constructor with no arguments. It must not define the finalize method.
  • It is recommended, but not required, that a message-driven bean class should implement the MessageListener  interface for the message type it supports. This interface defines only one method onMessage( ). When the EJB container arrives a message, it calls the onMessage( ) method of the message-driven bean to process the message. The onMessage( ) method contains the business logic and handles the processing of the message in accordance with the application?s business logic. It can call helper methods, or invoke a session bean to process the information in the message or to store it in a database.
    A message is delivered to a message-driven bean within a transaction context, so all operations within the onMessage method are part of a single transaction. If message processing is rolled back, the message will be redelivered.

    In our example, the
    MessageBean.onMessage( ) method retrieves the message body, parses out the messages to a TextMessage, perform the necessary business logic, and displays the text to the message-client.

  • A message-driven bean can also inject a MessageDrivenContext resource which is commonly used to call the setRollbackOnly method to handle exceptions for a bean during container-managed transactions.
   package mdb;     import javax.ejb.*;
   import
javax.ejb.MessageDriven;
   import
javax.jms.Message;
   import
javax.jms.MessageListener;
   import
javax.jms.ObjectMessage;
   import
java.text.*;
   import
javax.naming.*;
  
import java.util.logging.Logger;
 @MessageDriven(mappedName="jms/Queue")
  public class MessageBean implements MessageListener {
  
@Resource
  
private MessageDrivenContext mdc;
   private static final Logger logger;
  
   public void onMessage(Message msg) {
     TextMessage tmsg = null;
   try {
    

     tmsg = (TextMessage) msg;
     logger.info(
"MESSAGE BEAN: Message received: " + tmsg.getText( ));

    
System.out.println ("The onMessage() is called");

  } catch (JMSException e) {
      e.printStackTrace( );
      mdc.setRollbackOnly( );
  }
  catch
(Throwable th) {
   th.printStackTrace();
  }
  }
  

 public void ejbRemove( )throws EJBException{
   loger.fine("ejbRemove()");
   }
}


Logger:
When writing log messages from EJBs within JRun, you have the following options:
  • Nonportable  Use JRun-specific methods and services. These methods write to the JRun server's event log.
  • Portable  Use one of the System.out.println methods. These methods write to the console (if used when starting JRun).
An EJB can acquire a logger instance from the container and use the logger's info( ) method to display the messages for the client-end, as shown in the following code examples:

logger.info("MESSAGE BEAN: Message received: " +  msg.getText( ));

giovedì 26 luglio 2012

Increase hard disk size in VirtualBox 4.x

Increase hard disk size in VirtualBox 4.x

0. Shut down virtual machine & quit VirtualBox

1. Locate VDI file

$ VBoxManage list hdds
UUID:        xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Parent UUID: base
Format:      VDI
Location:    /Users/user/Library/VirtualBox/HardDisks/XP.vdi
State:       created
Type:        normal
Usage:       XP (UUID: yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy)

2. Backup virtual machine

There are two methods:
  1. Simply copy the VDI file to another location. (If you try opening this copy in a new VM later, you may receive a "Cannot register the hard disk ... with UUID ... because a hard disk ... with UUID ... already exists in the media registry ..." error. This can be resolved by assigning a new UUID: $ VBoxManage internalcommands sethduuid XPcopy.vdi *)
  2. Or use the clonehd command, which creates a cloned copy with a new UUID automatically:
    $ VBoxManage clonehd XP.vdi XPclone.vdi

3. Resize drive

Specify the new size in MBs. In this example, we'll expand a 10GB virtual disk to 40GB:
$ sudo VBoxManage modifyhd XP.vdi --resize 40960
The process should complete in a few seconds.

4. Allocate new space 

  1. Download Parted Magic
  2. Open VirtualBox and select your VM
  3. Go to Settings > Storage to select the Parted Magic ISO image:

    and then to Settings > System > Motherboard to set the boot order.
  4. Start the virtual machine. Once Parted Magic is booted, double click "Partition Editor" on the Desktop. You'll see something like this:
  5. In this example, you'd resize /dev/sda1 to take up the additional 30GB and click Apply:

mercoledì 25 luglio 2012

The Meaning of 0.0.0.0 In Routing Table

The Meaning of 0.0.0.0 In Routing Table.

Each network host has a default route for each network card. 

This will create a 0.0.0.0 route for such card. The address 0.0.0.0 generally means "any address". 

If a packet destination doesn't match an individual address in the table, it must match a 0.0.0.0 gateway address. 

In other words, default gateway is always pointed by 0.0.0.0:

route -n

Sample outputs:

Kernel IP routing table
 
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
10.0.31.18      0.0.0.0         255.255.255.255 UH    0      0        0 ppp0
38.96.196.94    192.168.1.2     255.255.255.255 UGH   0      0        0 wlan0
192.168.84.0    0.0.0.0         255.255.255.0   U     0      0        0 vmnet8
192.168.1.0     0.0.0.0         255.255.255.0   U     2      0        0 wlan0
192.168.110.0   0.0.0.0         255.255.255.0   U     0      0        0 vmnet1
192.168.122.0   0.0.0.0         255.255.255.0   U     0      0        0 virbr0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 wlan0
10.0.0.0        0.0.0.0         255.0.0.0       U     0      0        0 ppp0
0.0.0.0         192.168.1.2     0.0.0.0         UG    0      0        0 wlan0

192.168.1.2 is my ISP router i.e. 
default gateway indicated by 0.0.0.0. 

Other destination such as 10.0.0.0/8 network use ppp0 interface as gateway. 

If you are MS-Windows user use route print command.

Flag G indicates path to route packets via a gateway. 

If you would like to visit yahoo.com from your computer you need to go via 192.168.1.1 gateway. 

This usually means that you have to set up a static route to the gateway beforehand. If you specify the address of one of your local interfaces, it will be used to decide about the interface to which the packets should be routed to. metric field used by routing daemons. This is required on large LAN and wan setups. The output of the kernel routing table is organized in the following columns:

  • Destination : The destination network or destination host.
  • Gateway : The gateway address or ’*’ if none set.
  • Genmask : The netmask for the destination net; 255.255.255.255 for a host destination and 0.0.0.0 for the default route.
  • Flags : Possible flags include
    • U (route is up)
    • H (target is a host)
    • G (use gateway)
    • R (reinstate route for dynamic routing)
    • D (dynamically installed by daemon or redirect)
    • M (modified from routing daemon or redirect)
    • A (installed by addrconf)
    • C (cache entry)
    • ! (reject route)
  • Metric : The distance to the target (usually counted in hops). It is not used by recent kernels, but may be needed by routing daemons.
  • Ref : Number of references to this route. (Not used in the Linux kernel.)
  • Use : Count of lookups for the route. Depending on the use of -F and -C this will be either route cache misses (-F) or hits (-C).
  • Iface : Interface to which packets for this route will be sent.
  • MSS : Default maximum segment size for TCP connections over this route.
  • Window : Default window size for TCP connections over this route.
  • irtt : Initial RTT (Round Trip Time). The kernel uses this to guess about the best TCP protocol parameters without waiting on (possibly slow) answers.
  • HH (cached only) : The number of ARP entries and cached routes that refer to the hardware header cache for the cached route. This will be -1 if a hardware address is not needed for the interface of the cached route (e.g. lo).
  • Arp (cached only) : Whether or not the hardware address for the cached route is up to date.
Your routing table is created automatically, based on the current TCP/IP configuration of your Linux / UNIX computer. You can manually add / modify / edit routing table using route and ip command. The types of entries in a routing table:
  • Network Route: A route (path) to a specific Network ID in the internetwork.
  • Host Route : A route to a specific internetwork address (Network ID and Host ID). Host routes allow intelligent routing decisions to be made for each network address. Host routes are used to create custom routes to control or optimize specific types of network traffic.
  • Default Route: A route that is used when no other routes for the destination are found in the routing table. If a router or end system (such as a PC running Microsoft Windows or Linux), cannot find a route for a destination, the default route is used. The default route is used if no other host or network route matches the destination address. Please see related FAQs below for more examples of route and ip command.

 

 

venerdì 18 maggio 2012

WebHarvest: Easy Java Web Scraping






Process of extracting data from Web pages is also referred as
Web Scraping or Web Data Mining.

World Wide Web, as the largest database, often contains various data that we would like to consume for our needs.

The problem is that this data is in most cases mixed together with formatting code - that way making human-friendly, but not machine-friendly content.

Doing manual copy-paste is error prone, tedious and sometimes even impossible.
Web software designers usually discuss how to make clean separation between content and style, using various frameworks and design patterns in order to achieve that.

Anyway, some kind of merge occurs usually at the server side, so that the bunch of HTML is delivered to the web client.
Every Web site and every Web page is composed using some logic.

It is therefore needed to describe reverse process - how to fetch desired data from the mixed content.

Every extraction procedure in Web-Harvest is user-defined through XML-based configuration files.
Each configuration file describes sequence of processors executing some common task in order to accomplish the final goal.

Processors execute in the form of pipeline.
Thus, the output of one processor execution is input to another one.

This can be best explained using the simple configuration fragment:

 
<xpath expression="//a[@shape='rect']/@href">
    <html-to-xml>
        <http url="http://www.somesite.com/"/>
    </html-to-xml>
</xpath>
 
When Web-Harvest executes this part of configuration, the following steps occur:
  1. http processor downloads content from the specified URL.
  2. html-to-xml processor cleans up that HTML producing XHTML content.
  3. xpath processor searches specific links in XHTML from previous step giving URL sequence as a result.
Web-Harvest supports a set of useful processors for variable manipulation, conditional branching, looping, functions, file operations, HTML and XML processing, exception handling. See User manual for technical description of provided processors.




Note inspired from the good article :



On web harvesting activity and the possible java direct interaction.

I often have a need to quickly scrape some data out of a web page (or list of web pages), which can then be fed into Excel and on to specialist data visualisation tools.

To this end I have turned to WebHarvest, an excellent scriptable open source API for web scraping in Java. 

I really really like it, but there are some quirks and setup issues that have cost me hours so I thought I’d roll together a tutorial with the fixes.

WebHarvest Config for Maven

When it works Maven is a lovely tool to hide dependency management for Java projects, but WebHarvest is not configured quite right out of the box to work transparently with it. 

(Describing Maven is beyond the scope of this post, but if you don’t know it, it’s easy to setup with the M2 plugin for Eclipse.)

This is the Maven POM I ended up with to use WebHarvest in a new JavaSE project:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
 <modelVersion>4.0.0</modelVersion>
 <groupId>WebScraping</groupId>
 <artifactId>WebScraping</artifactId>
 <packaging>jar</packaging>
 <version>0.00.01</version>
 <properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>

 <build>
   <plugins>
     <plugin>
       <artifactId>maven-compiler-plugin</artifactId>
       <configuration>
       <source>1.6</source>
       <target>1.6</target>
       </configuration>
     </plugin>
   </plugins>
 </build>

 <repositories>
   <repository>
     <id>wso2</id>
     <url>http://dist.wso2.org/maven2/</url>
   </repository>
   <repository>
     <id>maven-repository-1</id>
     <url>http://repo1.maven.org/maven2/</url>
   </repository>
 </repositories>
 
<dependencies>
  <dependency>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
     <version>1.1</version>
     <type>jar</type>
     <scope>compile</scope>
  </dependency>
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.12</version>
    <type>jar</type>
    <scope>compile</scope>
  </dependency>
  <dependency>
    <groupId>org.webharvest.wso2</groupId>
    <artifactId>webharvest-core</artifactId>
    <version>1.0.0.wso2v1</version>
    <type>jar</type>
    <scope>compile</scope>
  </dependency>
 
<!-- web harvest pom doesn't track dependencies well -->
  <dependency>
    <groupId>net.sf.saxon</groupId>
    <artifactId>saxon-xom</artifactId>
    <version>8.7</version>
  </dependency>
  <dependency>
    <groupId>org.htmlcleaner</groupId>
    <artifactId>htmlcleaner</artifactId>
    <version>1.55</version>
  </dependency>
  <dependency>
    <groupId>bsh</groupId>
    <artifactId>bsh</artifactId>
    <version>1.3.0</version>
  </dependency>
  <dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
  </dependency>
 </dependencies>
</project>



You’ll note that the WebHarvest dependencies had to be added explicitly, because the jar does not come with a working pom listing them.

Writing A Scraping Script

WebHarvest uses XML configuration files to describe how to scrape a site – and with a few lines of Java code you can run any XML configuration and have access to any properties that the script identified from the page. 

This is definitely the safest way to scrape data, as it decouples the code from the web page markup – so if the site you are scraping goes through a redesign, you can quickly adjust the config files without recompiling the code they pass data to.

The site some good example scripts to show you how to get started, so I won’t repeat them here. 

The easiest way to create your own is to run the WebHarvest GUI from the command line,(ie: java -jar webharvest_all_2.jar) start with a sample script, and then hack it around to get what you want – it’s an easy iterative process with good feedback in the UI.


FOR INSTANCE: let's have a look at the second example to start working on the Canon products at Yahoo Shopping sample.








As we can see we want to harvest around the following url:
http://shopping.yahoo.com/s:Digital%20Cameras:4168-Brand=Canon:browsename=Canon%20Digital%20Cameras:refspaceid=96303108;_ylt=AnHw0Qy0K6smBU.hHvYhlUO8cDMB;_ylu=X3oDMTBrcDE0a28wBF9zAzk2MzAzMTA4BHNlYwNibmF2

the simple script is :

<config charset="ISO-8859-1">
   
    <include path="functions.xml"/>
               
    <!-- collects all tables for individual products -->
    <var-def name="products">   
        <call name="download-multipage-list">
            <call-param name="pageUrl">http://shopping.yahoo.com/s:Digital%20Cameras:4168-Brand=Canon:browsename=Canon%20Digital%20Cameras:refspaceid=96303108;_ylt=AnHw0Qy0K6smBU.hHvYhlUO8cDMB;_ylu=X3oDMTBrcDE0a28wBF9zAzk2MzAzMTA4BHNlYwNibmF2</call-param>
            <call-param name="nextXPath">//a[starts-with(., 'Next')]/@href</call-param>
            <call-param name="itemXPath">//li[@class="hproduct" or @class="hproduct first" or @class="hproduct last"]</call-param>
            <call-param name="maxloops">10</call-param>
        </call>
    </var-def>
   
    <!-- iterates over all collected products and extract desired data -->
    <file action="write" path="D:/tmp/canon/catalog.xml" charset="UTF-8">
        <![CDATA[ <catalog> ]]>
        <loop item="item" index="i">
            <list><var name="products"/></list>
            <body>
                <xquery>
                    <xq-param name="item" type="node()"><var name="item"/></xq-param>
                    <xq-expression><![CDATA[
                            declare variable $item as node() external;

                            let $name := data($item//*[@class='title'])
                            let $desc := data($item//*[@class='desc'])
                            let $price := data($item//*[@class='price'])
                                return
                                    <product>
                                        <name>{normalize-space($name)}</name>
                                        <desc>{normalize-space($desc)}</desc>
                                        <price>{normalize-space($price)}</price>
                                    </product>
                    ]]></xq-expression>
                </xquery>
            </body>
        </loop>
        <![CDATA[ </catalog> ]]>
    </file>

</config>




As a simple example, this is a script to go to the Sony-Ericsson developer site’s handset gallery at http://developer.sonyericsson.com/device/searchDevice.do?restart=true, and rip each handset’s individual spec page URI:

<?xml version="1.0" encoding="UTF-8"?>
<config>
 
    <!-- indicates we want a loop, through the list defined in <list>, doing <body> for each item where the variables uri and i are defined as the index and value of the relevant item -->

    <loop item="uid" index="i">
        <!-- the list section defines what we will loop over - here, it pulls out the value attribute of all option tags -->
        <list>
            <xpath expression="//option/@value">
                <html-to-xml>
                    <http url="http://developer.sonyericsson.com/device/searchDevice.do?restart=true"/>
                </html-to-xml>
            </xpath>
        </list>
        <!-- the body section lists instructions which are run for every iteration of the loop -->
        <body>
            <!-- we define a new variable for every iteration, using the iteration count as a suffix  -->
            <var-def name="uri.${i}">
                <!-- template tag is important, else the $ var syntax will be ignored and won't do any value substitutions -->
                <template>device/loadDevice.do?id=${uid}</template>
            </var-def>
        </body>
    </loop>
</config>


mercoledì 16 maggio 2012

Core Spring and IOC concept in a nut. 1




Core Spring API Components

Spring is a container and component model. Everything else, including AOP, transactions, database access, web applications, and the like is built on top of this container and component model. Objects managed in the container do not have to know about Spring or the container because of Inversion of Control (IoC). 

This pattern specifies the involvement of the Spring container (which manages lifecycle), your object, and any other dependant objects – known as beans in Spring parlance. 

The container is able to inject any number or type of dependant beans together while specifying the relationship throughconfiguration. 

Dependency injection is enabled by creating properties and matching setter methods of your target object for the types of objects that you expect to inject. Alternatively, objects may be injected
during instantiation by providing a constructor with a signature that matches types you expect to inject.

The core of Spring framework’s functionality lies within this IoC container, which is discussed next.

The Inversion of Control Container

The Inversion of Control (IoC) container provides the dependency injection support to your applications that enables you to configure and integrate application and infrastructure components together. Through IoC, your applications may achieve a low-level of coupling, because all of the bean
configuration can be specified in terms of IoC idioms (such as property collaborators and constructors). Meanwhile, most if not all of your application’s bean lifecycle (construction to destruction) may be managed from within the container. 

This enables you to declare scope – how and when a new object
instance gets created, and when it gets destroyed. 

For example, the container may be instructed that a
specific bean instance be created only once per thread, or that, upon destruction, a database bean may disconnect from any active connections. 
Through requests to the Spring IoC container, a new bean may
either get constructed or a singleton bean may get passed back to the requesting bean. Either way, this is a transparent event that is configured along with the bean declaration.


Spring Container Metadata Configuration

Spring provides several implementations of the ApplicationContext interface out of the box. In standalone applications using XML metadata (still commonplace today), it is common to create an
instance of 

org.springframework.context.support.ClassPathXmlApplicationContext or
org.springframework.context.support.FileSystemXmlApplicationContext.

Configuration metadata consisting of bean definitions represented with XML or Java configuration is preferred for third-party APIs for which you do not have access to source code. 

In most other cases, configuration metadata – in addition to, or in place of XML – may be applied through Java annotations. 

ioc_basics.xml – 

A Basic Spring Application Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
<bean class="com.iocbasics.BasicPOJO"/>
 
</beans>

This is a simple XML document that makes use of the Spring beans namespace – the basis for resolving your POJO within the Spring container. 

Instantiating the IoC Container

To instantiate the IoC container and resolve a functional ApplicationContext instance, the relevant  ApplicationContext implementation must be invoked with a specified configuration. 

With a standard Java application with XML metadata configuration, the ClassPathXmlApplicationContext will resolve any number of Spring XML configuration resources given a path relative to the base Java classpath. This constructor is overloaded with a variety of argument arrangements that provide ways to specify the resource locations. 

Spring also provides a number of other applicationContext implementations. For example, FileSystemXmlApplicationContext is used to load XML configuration from the file system (outside of the classpath), and AnnotationConfigApplicationContext supports loading annotated Java classes.
 
In the next part of code, the context constructor is given a single resolvable path of the Spring configuration XML file. If the XML resource were located outside of classpath, the absolute file system path would be provided to the FileSystemApplicationContext factory class to obtain the ApplicationContext.

BasicIoCMain.java 
– Single Line of Code to Startup you Application Context

ApplicationContext ctx = new ClassPathXmlApplicationContext("ioc_basics.xml");

The next step is to obtain your configured beans. 

Simply calling ApplicationContext.getBean method (by passing it the class of the instance you want returned) will provide, by default, the singleton instance of the bean. 

That is, every bean will be the same instance.
BasicIocMain.java - Obtaining a Bean Reference by Class.

BasicPOJO basicPojo = ctx.getBean(BasicPOJO.class);

Alternatively, Spring can infer which bean definition your looking for by passing it the ID (or qualifier) of the bean instance instead of the bean class. This helps when dealing with multiple bean definitions of the same type. 

For instance, given a bean definition of the same BasicPojo class, The next sample illustrates the combined code effort in setting up and obtaining this bean resource.

BasicIocMain.java – Obtaining a Bean Reference by Name

BasicPOJO basicPojo = (BasicPOJO)ctx.getBean("basic-pojo");



Bean Instantiation from the IoC Container
 
A basic operation in a Spring context is instantiating beans. This is done in a variety of ways; however, we will focus on the most common use cases. 

In this example, the BasicPojo bean provides both a noarg and arguments-based constructor. In addition, we have a POJO property named color with type ColorEnum (see later). 

We will use both BasicPOJO and ColorEnum objects to illustrate how you can define and populate your beans within Spring XML configuration.

package com.sample.iocbasic;

public class BasicPOJO {

public String name;
public ColorEnum color;
 

public ColorRandomizer colorRandomizer;
// empty constructor

public BasicPOJO() {
}
 

public BasicPOJO(String name, ColorEnum color) {
 this.name = name;
 this.color = color;
}


public String getName() {
 return name;
}


public void setName(String name) {
 this.name = name;
}


public ColorEnum getColor() {
 return color;
}


public void setColor(ColorEnum color) {
 this.color = color;
}


public ColorRandomizer getColorRandomizer() {
 return colorRandomizer;
}


public void setColorRandomizer(ColorRandomizer colorRandomizer) {
 this.colorRandomizer = colorRandomizer;
}


}


package com.sample.iocbasic;
public enum ColorEnum {
  violet, blue, red, green, purple, orange, yellow
}




Constructor Injection

Constructor arguments may be set through XML configuration. This will enable you to inject dependencies through the constructor arguments. 


To do this, use the constructor-arg element within
the bean definition, as shown in next sample.
 

ioc_basics.xml – XML Bean Construction using Parameterized Arguments
…
<bean id="constructor-setup"
class="
com.sample.iocbasic.BasicPOJO">
  <constructor-arg name=”name” value="red"/>
  <constructor-arg name=”color” value="violet" />
</bean>

…


Bean References and Setter Injection


Bean properties may be injected into your target beans through references to other beans within the scope of your application context. 


This is known as bean collaboration. 

This requires defining the additional bean that you wish to refer to, also known as the collaborator. Using the ref attribute in the
property tag enables us to tell Spring which bean we want to collaborate with, and thus have injected
 

ioc_basics.xml – XML Configuration for Bean Collaboration by Setting Injection

<bean id="no-args"
class="
com.sample.iocbasic.BasicPOJO">
  <property name="color" ref="defaultColor"/>
  <property name="name" value="Mario"/>
</bean>


<bean id="defaultColor"
class="
com.sample.iocbasic.ColorEnum"
factory-method="valueOf">
  <constructor-arg value="blue"/>
</bean>

 
Static and Instance Factory Injection
 

Note the factory-method attribute on the defaultColor element. 
In this case the static factory method instantiation mechanism was used. 

Note also that the class attribute does not specify the type of object returned by a factory method, as it specifies only the type containing that factory method. 

For this simple example, a string was fed to the enum static factory method valueOf, which is the common approach to resolving enum constants from strings. 


When static factory methods are not practical, use instance factory methods instead. 

These are methods that get invoked from existing beans on the container to provide new bean instances. 
The class in the next sample demonstrates instance factory methods to provide random ColorEnum instances.

ColorRandomizer.java – Class Definition for the ColorRandomizer Factory Bean


package
com.sample.iocbasic;
import java.util.Random;
 

public class ColorRandomizer {
 

 ColorEnum colorException;
 

 public ColorEnum randomColor() {
  ColorEnum[] allColors = ColorEnum.values();
  ColorEnum ret = null;
  do {
   ret = allColors[new Random().nextInt(allColors.length - 1)];
  }
  while (colorException != null && colorException == ret);
  return ret;
 }


public ColorEnum exceptColor(ColorEnum ex) {
 ColorEnum ret = null;
 do {
  ret = randomColor();
 } while (ex != null && ex == ret);
  

 return ret;
}


public void setColorException(ColorEnum colorExceptions) {
 this.colorException = colorExceptions;
}


}

 
To invoke the factory within our Spring context, ColorRandomizer will be defined as a bean, then one of its methods will be invoked in another bean definition as a way to vend an instance of ColorEnum. 


We obtain two separate instances of ColorEnum using both ColorRandomizer factory methods to illustrate variances in factory method invocations.

Obtaining Bean Instances from Factory Methods in Spring
 

<!-- Factory bean for colors -->
<bean id="colorRandomizer" class="
com.sample.iocbasic.ColorRandomizer" />
 

<!-- gets a random color -->
<bean id="randomColor" factory-bean="colorRandomizer" factory-method="randomColor"/>
 

<!-- gets any color, except the random color defined above -->
<bean id="exclusiveColor" factory-bean="colorRandomizer" factory-method="exceptColor">

  <constructor-arg ref="randomColor"/>
</bean>



 
Bean Scopes

Spring uses the notion of bean scopes to determine how beans defined in the IoC container get issued to the application upon request with getBean methods, or through bean references. 


A bean’s scope is set with the scope attribute in the bean element, or by using the @Bean annotation in the class file. 
Spring defaults to the singleton scope, where a single instance of the bean gets shared throughout the entire container. Spring provides a total of six bean scopes out of the box for use in specific context implementations, although only singleton, prototype, and thread are available through all context
implementation. 


The other scopes – request, session, and globalSession – are available only to application contexts that are web-friendly, such as WebApplicationContext.

Bean scopes available in Spring:


Singleton Single bean instance per container, shared throughout the IoC container.


Prototype New bean instance created per request.


Request Web application contexts only: Creates a bean instance per HTTP request.


Session Web application contexts only: Creates a bean instance per HTTP session.


GlobalSession Web portlet only: Creates a bean instance per Global HTTP session.


Thread* Creates a bean instance per thread. Similar to request scope.


* Thread scope is not registered by default, and requires registration with the CustomScopeConfigurer bean.


To illustrate the behavior of prototype- and singleton-scoped beans, next sample declares two beans of the same type, which differ only in scope. 


The value from the singleton-scoped bean should always
return the same value, whereas the prototype-scoped bean will always return different values (since the
factory returns random numbers). 


This shows the Spring configuration file and the next one
shows the main class.


ioc_basics.xml – Overriding Default Scope for Beans with XML Metadata


<beans…>
  <bean id="randomeverytime" factory-bean="colorRandomizer" factory-  method="randomColor"
scope="prototype"/>


  <bean id="alwaysthesame" factory-bean="colorRandomizer factory-method="randomColor"
scope="singleton"/>
 

</beans>

BasicIocMain.java –Simple For-Loop
 

public static void demonstrateScopes(ApplicationContext ctx) {
 for (int i = 0; i < 5; i++) {
  System.out.println("randomeverytime: " +
    ctx.getBean("randomeverytime", ColorEnum.class));
  System.out.println("alwaysthesame: " +
    ctx.getBean("alwaysthesame", ColorEnum.class));
 }
}

 
The output of this loop will emit text similar to this:


Output of Bean Scope Induced Behavior
randomeverytime: green
alwaysthesame: orange
randomeverytime: purple
alwaysthesame: orange
randomeverytime: violet
alwaysthesame: orange
randomeverytime: violet
alwaysthesame: orange
randomeverytime: green
alwaysthesame: orange


You register the thread scope, or any other custom scope, in XML by defining a org.springframework.beans.factory.config.CustomScopeConfigurer bean. 


Pass the scope implementation class to the map property scopes. The map property is evaluated with the key providing the scope name,
and value having the scope’s implementation class. Registering in this fashion is always compatible to @Bean annotated properties with the @Scope annotation. That is, a scope definition once enabled for any given scope is activated throughout the container and for all manners of configuration (see next).


Ioc_basics.xml – Registering Custom Scopes in XML


<beans…>
 <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
 <property name="scopes">
  <map>
   <entry key="thread">
    <bean class="org.springframework.context.support.SimpleThreadScope"/>
   </entry>
  </map>
 </property>
</bean>
<bean id="threadColor" factory-bean="colorRandomizer" factory-method="randomColor"
scope="thread"/>
</beans…>