Listing 1

<?xml version="1.0" encoding="utf-8"?>
<!-- FinancialNews1.mxml -->
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" 
	title="News" width="100%" height="100%" creationComplete="onCreationComplete()" >
	<mx:DataGrid id="newsGrid" width="100%" height="100%"
		dataProvider="{newsFeed.lastResult.channel.item}" variableRowHeight="true">
	<mx:columns>
		<mx:Array>
			<mx:DataGridColumn headerText="Date" dataField="pubDate" width="200"/>
			<mx:DataGridColumn headerText="Title" dataField="title" wordWrap="true" />
			<mx:DataGridColumn headerText="Description" dataField="description" 
			       wordWrap="true" />
			<mx:DataGridColumn headerText="Link" width="130" dataField="link" 
			       wordWrap="true" />
		</mx:Array>
	</mx:columns>
	</mx:DataGrid>
		 
	<mx:HTTPService id="newsFeed" useProxy="true" destination="YahooFinancialNews" 
	   concurrency="last" 	resultFormat="e4x" fault="onFault(event)" >
	</mx:HTTPService>
	
	<mx:Script>
		<![CDATA[
			private function onCreationComplete():void {
				newsFeed.send({s:"ADBE"});
			}
			import mx.rpc.events.*;
			private function onFault(event:FaultEvent):void {
				mx.controls.Alert.show(
				 "Destination:" + event.currentTarget.destination + "\n" +
				 "Fault code:" + event.fault.faultCode + "\n" +
				 "Detail:" + event.fault.faultDetail, "News feed failure"
				);
			}	
		]]>
	</mx:Script>
</mx:Panel>

Listing 2

<?xml version="1.0" encoding="utf-8"?>
<!-- FinancialNews2.mxml -->
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" 	title="News" width="100%" height="100%" >
	<mx:DataGrid id="newsGrid" width="100%" height="100%"
		dataProvider="{newsList}" variableRowHeight="true"> 
	<mx:columns> 
		<mx:Array>
			<mx:DataGridColumn headerText="Date" dataField="pubDate" width="200"/>
			<mx:DataGridColumn headerText="Title" dataField="title" wordWrap="true" />
			<mx:DataGridColumn headerText="Description" dataField="description" 
                                wordWrap="true" />
			<mx:DataGridColumn headerText="Link" width="130">
				<mx:itemRenderer>
					<mx:Component> 
						<mx:LinkButton label="{data.link}" 
             click="navigateToURL(new URLRequest(data.link), '_blank')"/>
					</mx:Component>
				</mx:itemRenderer>
			</mx:DataGridColumn>
		</mx:Array>
	</mx:columns>
	</mx:DataGrid>
	<mx:XMLListCollection id="newsList" source="{newsFeed.result.channel.item}" />
	<mx:HTTPService id="newsFeed" useProxy="true" destination="YahooFinancialNews"   
   concurrency="last"	resultFormat="e4x" fault="onFault(event)" > 
	</mx:HTTPService>
	
	<mx:Script>
		<![CDATA[
			import mx.rpc.events.*;
			public function set security(value:String):void {
				this.title = "News: " + value;
				newsFeed.send({s:value});
			}

			private function onFault(event:FaultEvent):void {
				mx.controls.Alert.show(
				 "Destination:" + event.currentTarget.destination + "\n" +
				 "Fault code:" + event.fault.faultCode + "\n" +
				 "Detail:" + event.fault.faultDetail, "News feed failure"
				);
			}
		]]>
	</mx:Script>
</mx:Panel>

Listing 3

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
	 "xmlns="*" > 
 	<mx:VDividedBox width="100%" height="100%">
 	 <PortfolioView5 id="pv"/>
	 <FinancialNews2 id="fn" security="{pv.selectedSecurity}"/> 
 	</mx:VDividedBox>
</mx:Application>

Listing 4

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" >
...	 <mx:DataGrid id="portfolioGrid" dataProvider="{portfolioModel.security}" 
    selectable="true" change="selectedSecurity=portfolioGrid.selectedItem.Symbol">
	    	...
		</mx:DataGrid>
		... 
		<mx:PieChart id="portfolioPie" itemClick="portfolioPieOnClick(event)"
    dataProvider="{portfolioModel.security}" showDataTips="true" >
			...
		</mx:PieChart> 
	...
 <mx:Script><![CDATA[
    import mx.controls.Alert;
    import mx.rpc.events.FaultEvent;

		[Bindable]
		public var selectedSecurity:String;
			
		import mx.charts.events.*;
		private function portfolioPieOnClick(event:ChartItemEvent):void {
			selectedSecurity=event.hitData.item.Symbol;
		}	
		... 
  ]]></mx:Script>
	...
</mx:Canvas>

Listing 5

private function portfolioPieOnClick(event:ChartItemEvent):void {
 selectedSecurity=event.hitData.item.Symbol;
 var currentWedgeIndex:int = event.hitData.index;
 var perWedgeExplosion:Array = [];
 for (var i:int=0; i<portfolioPie.dataProvider.length; i++) {
 	perWedgeExplosion[i] = (i==currentWedgeIndex)?10:2;
 }
 portfolioPie.series[0].perWedgeExplodeRadius = perWedgeExplosion;
}	

Listing 6

public class JndiExample {
	public static void main(String[] args) {

		Context ctx = null;
		try {
			Hashtable env = new Hashtable();    
			env.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
			env.put(Context.PROVIDER_URL, " tcp://localhost:61616");
			env.put(Context.SECURITY_PRINCIPAL, "admin"); 
			env.put(Context.SECURITY_CREDENTIALS , "admin"); 
 
			ctx = new InitialContext(env);
			System.out.println("ActiveMQ initial context is obtained");

// Now you can lookup for JMS objects, i.e. topic connection factory
// TopicConnectionFactory factory = (TopicConnectionFactory) 
//             ctx.lookup("jms/flex/TopicConnectionFactory");

		} catch(Excaption e){...}
	}
}
 
Listing 7

// Lookup factory and create topic connection
TopicConnectionFactory factory = (TopicConnectionFactory) context.lookup("topicConnectionFactory");
Topic connection = factory.createTopicConnection();
// Create publisher session
boolean transacted = false;
pubSession = connection.createTopicSession(transacted, Session.AUTO_ACKNOWLEDGE);
// Lookup topic
Topic topic = (Topic) context.lookup("ticker");
// Create a publisher
publisher = pubSession.createPublisher(topic);

ObjectMessage message = pubSession.createObjectMessage( mySerializableObject);
publisher.publish(message);

Listing 8

TopicConnectionFactory factory = (TopicConnectionFactory) context.lookup("topicConnectionFactory");
TopicSession subSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

Topic topic = (Topic) ctx.lookup("ticker");
TopicSubscriber subscriber = subSession.createSubscriber(topic); 
connection.start();
subscriber.setMessageListener(this);

public void onMessage(Message message) {
= 	// Work with your message here
	// Cast it to your specific type, etc. ge");
}

Listing 9

<?xml version="1.0" encoding="UTF-8"?>
<service id="message-service" class="flex.messaging.services.MessageService" messageTypes="flex.messaging.messages.AsyncMessage">

 <adapters>
  <adapter-definition id="actionscript" class="flex.messaging.services.messaging.adapters.ActionScriptAdapter"
   default="true" />
  <adapter-definition id="jms" 
     class="flex.messaging.services.messaging.adapters.JMSAdapter"/>
  </adapters>
  <destination id="ticker-topic-jms">
    <properties>
      <server>
        <durable>false</durable>
        <durable-store-manager>flex.messaging.durability.FileStoreManager</durable-store-manager>
      </server>
      <jms>
        <destination-type>Topic</destination-type>
        <message-type>javax.jms.ObjectMessage</message-type>
        <connection-factory>topicConnectionFactory</connection-factory>
        <destination-jndi-name>ticker</destination-jndi-name>
        <destination-name>Ticker</destination-name>
        <durable-consumers>false</durable-consumers>
        <delivery-mode>NON_PERSISTENT</delivery-mode>
        <message-priority>DEFAULT_PRIORITY</message-priority>
        <acknowledge-mode>AUTO_ACKNOWLEDGE</acknowledge-mode>
        <transacted-sessions>false</transacted-sessions>
	  <initial-context-environment>
        <property>
                        <name>java.naming.factory.initial</name>
                        <value>org.apache.activemq.jndi.ActiveMQInitialContextFactory</value>
                    </property>
                    <property>
                        <name>java.naming.provider.url</name>
                        <value>tcp://localhost:61616</value>
                    </property>
                </initial-context-environment>
      </jms>
    </properties>

    <channels>
      <channel ref="my-rtmp"/>
      <channel ref="my-polling-amf"/>
    </channels>

    <adapter ref="jms"/>

  </destination>
</service>

Listing 10

package com.theriabook.jms;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.activemq.broker.BrokerService;
public class ActiveMQBrokerListener implements ServletContextListener {

	BrokerService broker = new BrokerService();
	
	public void contextInitialized(ServletContextEvent arg0) {
        try{
        		broker.addConnector("tcp://localhost:61616?trace=true");
        		broker.start();
        }catch(Exception e){
        		e.printStackTrace();
        		throw new RuntimeException(e);
        }
	}

	public void contextDestroyed(ServletContextEvent arg0) {
		try{
			broker.stop();
		}catch(Exception e){
			e.printStackTrace();
        	throw new RuntimeException(e);
       	}
	}
}


Listing 11

#jndi.properties for TickerFeed program running against ActiveMQ
#
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory

# use the following property to configure the default connector
java.naming.provider.url = tcp://localhost:61616

# use the following property to specify the JNDI name the connection factory
connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactory

# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.ticker = chat.TicketTopic


Listing 12

// TickerFeed.java
package com.theriabook.jms;

import com.theriabook.ro.Portfolio;
import java.util.*;
import javax.jms.*;
import javax.naming.*;
import com.theriabook.jms.dto.StockQuoteDTO;

public class TickerFeed {

  public static void main(String args[]) {

    TopicSession pubSession;
    TopicPublisher publisher;
    TopicConnection connection;

	try {
      // Obtain JNDI Context
      Context context = new InitialContext();

      // Lookup a JMS connection factory
      TopicConnectionFactory factory = (TopicConnectionFactory) context.lookup("topicConnectionFactory");

      // Create a JMS connection
      connection = factory.createTopicConnection();

      // Create publisher session
      boolean transacted = false;
      pubSession = connection.createTopicSession(transacted, Session.AUTO_ACKNOWLEDGE);

      // or lookup a JMS topic
      Topic topic = (Topic) context.lookup("ticker");

      // Create a publisher and a subscriber
      publisher = pubSession.createPublisher(topic);

     Portfolio port = new Portfolio(); 
      while (true) {
      	StockQuoteDTO[] quotes = port.getQuotes();
      	QuotesHolder holder = new QuotesHolder();
      	holder.quotes = quotes;
        Thread.sleep(1000); // just to slow down the feed
       
        ObjectMessage message = pubSession.createObjectMessage( holder);
        publisher.publish(message);
        System.out.println("Publishing quotes..." );
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (NamingException e) {
      e.printStackTrace();
    } catch (JMSException e) {
      e.printStackTrace();
    }
  }
}

LISTING 13

<?xml version="1.0" encoding="utf-8"?>
<!-PortflolioViewJMS.mxml 
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"  
    width="100%" height="100%"  creationComplete="startQuotes();" >
<mx:XML  format="e4x" id="portfolioModel" source="portfolio.xml" />
<mx:Panel width="100%" height="100%" title="Portfolio">
	<mx:ViewStack id="vs" width="100%" height="100%">
	<mx:VBox label="Show Grid"  icon="{iconGrid}" >
	<mx:DataGrid id="portfolioGrid" width="100%" height="100%"
		dataProvider="{portfolioModel.security}"  
	 change="selectedSecurity = portfolioGrid.selectedItem.Symbol;">
		<mx:columns><mx:Array>
				<mx:DataGridColumn dataField="Symbol"/>
				<mx:DataGridColumn dataField="Quantity" textAlign="right"/>
				<mx:DataGridColumn dataField="Price" textAlign="right"/>
				<mx:DataGridColumn dataField="Value" textAlign="right"/>
		</mx:Array></mx:columns>
	</mx:DataGrid>
	</mx:VBox>
	<mx:HBox label="Show Chart"  icon="{iconChart}"   horizontalAlign="center" verticalAlign="middle">
	<mx:PieChart id="portfolioPie" dataProvider="{portfolioModel.security}" showDataTips="true" 
			itemClick="selectedSecurity=event.hitData.item.Symbol"  height="90%"> 
		<mx:series><mx:Array>
               <mx:PieSeries labelPosition="callout" field="Value"   labelFunction="showPosition" nameField="Symbol"
			      	explodeRadius="2"/>
            </mx:Array>
		</mx:series>
	</mx:PieChart> 
	<mx:Legend  verticalAlign="middle" dataProvider="{portfolioPie}" label="{data.Symbol}"/>
	</mx:HBox> 
	</mx:ViewStack>
</mx:Panel>
<mx:HBox horizontalAlign="right"  width="98%" >
		<mx:Label color="red" toolTip="{errorTip}" text="{errorText}" width="100"/>
	    <mx:ToggleButtonBar   dataProvider="{vs}" paddingTop="4" />
</mx:HBox>

<mx:Consumer   id="consumer"  destination="ticker-topic-jms" message="applyQuotes(event.message.body.quotes)"  
channelFault="processFault(event)" />

   <mx:Script><![CDATA[
   	import mx.controls.Alert;
        [Bindable] public var selectedSecurity:String;
        private function showPosition(data:Object, field:String, index:Number, percentValue:Number):String    {
            return data.Symbol +  "\n" + "Shares:" + data.Quantity + "\n" + "Price:" + data.Price + "\n" + "Value:" +
			 data.Value ;
        }
        [Embed(source="./images/icon_chart.png")] [Bindable] public var iconChart : Class;
        [Embed(source="./images/icon_grid.png")]  [Bindable] public var iconGrid : Class;
        import com.theriabook.jms.dto.StockQuoteDTO;
        internal var row:XML;
		[Bindable]
		private var errorText:String="";
		[Bindable]
		private var errorTip:String="";
		import mx.messaging.events.ChannelFaultEvent;
		private function processFault(evt:ChannelFaultEvent):void{
			errorText = "Server Error";
			errorTip = evt.faultDetail;
			startQuotes();
		}
        private function applyQuotes(quotes: Array):void {
            errorText = "";
			errorTip = "";
            for (var i:int=0; i<quotes.length; i++) { 
				var quote:StockQuoteDTO = StockQuoteDTO(quotes[i]);  
				var list: XMLList = portfolioModel.security.(Symbol==quote.symbol);
				if (list.length()!=0) {
					var row:XML = XML(list);
					row.Price = Math.round(100*quote.last)/100;
					row.Value = Math.round(row.Price * row.Quantity);
				}	
            }	
        }
		internal var quote:StockQuoteDTO = null;
		private function startQuotes():void{
			consumer.subscribe();
		}
    ]]></mx:Script>
</mx:Canvas>