AgeFileFilter

To get the list of files of directory is simple. If we want the list of files depending on the modified date time of the file. This can be achived by using AgeFileFilter from Apache’s commons-io.

Get the list of files which is modified with in 24 hrs:

String files[] = new File("myLocation").list();

will return all files in the folder(myLocation).
To get the recent files we can use AgeFileFilter

private static FileFilter getFileFilter() {
	Calendar cal = Calendar.getInstance();
	cal.add(Calendar.DATE, -1);
	return new AgeFileFilter(cal.getTime(), false);
}

Here AgeFileFilter takes cutoff period and a boolean
boolean false indicates the files created after the given cutoff period and vice versa.
And this FileFilter has to apply for the listFiles of dir

Files files[] = new File("myLocation").listFiles(getFileFilter());

will return the array of files which are been modified with in 24 hrs.

Optimizing code

I posted about shortcuts in eclipse in my earlier post, those I use while writing code. Most of the times I try to write code as fast as possible but always fail to do that. There will be different thoughts while writing the code and gets confused and wastes time. I thought to optimize the code while writing it for the first time itself. I don’t know its correct to think like that or not. I always try to minimize the code of lines. I googled about tips and tricks for coding I got this links

http://www.insideria.com/2009/04/51-actionscript-30-and-flex-op.html

http://osflash.org/as3_speed_optimizations.It will be helpful for ActionScript 3.0 guys.

Few useful shortcuts in Eclipse

To copy selected rows : ctrl + alt + [up or down]key

To move selected rows up or down : alt + [up or down] key

Programing comment/Uncommon : ctrl + / or  ctrl + shift + c

Block comment :  ctrl + shift + /

Block Uncommon : ctrl + shift + \

Delete complete row : ctrl + d

Delete next word : ctrl + del

Delete previous word : ctrl + backspace

Delete row from the cursor to the end of row : ctrl + shift + Del

Convert selected text to upper case :  ctrl + shift + x

Convert selected text to lower case :  ctrl + shift + y

These shortcuts will also works fine in Flex Builder

Get attribute names and values of xml in flex

One more sample to parse xml file with attributes in flex. Here is a sample, which displays the capital city and language of the selected country in the combobox. The details were getting through xml file with three attributes “country”, ”capital” and “language”.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="onLoad()">

 <mx:Script>
 <![CDATA[
 import mx.events.ListEvent;
 import mx.collections.XMLListCollection;
 import mx.rpc.events.FaultEvent;
 import mx.rpc.events.ResultEvent;
 import mx.rpc.http.HTTPService;

 /**
 * Call a service to get the xml data
 */
 private function onLoad():void {
 var service:HTTPService = new HTTPService;
 var localurl:String = "capitals.xml";

 service.url = localurl;
 service.resultFormat = "e4x";
 service.send();
 service.addEventListener(ResultEvent.RESULT, resultHandler);

 }

 /**
 * handling the result of the above service
 */
 private function resultHandler(event:ResultEvent):void {
 var allXml:XML = new XML(event.result);

 var xmlList:XMLListCollection = new XMLListCollection(allXml.record);

 countryCB.dataProvider = xmlList;
 display(xmlList[0]);
 }

 /**
 *     Displaying the data
 */
 private function display(xml:XML):void {

 var attNames:XMLList = xml.attributes();
 var str:String = '';
 for (var i:int=0; i<attNames.length(); i++) {

 str += attNames[i].name() + ' : ' + attNames[i] + '\n\n';
 }
 displayStr.text = str;

 }

 /**
 *     Event raised by changing the combo value selection
 */
 private function onChange(event:ListEvent):void {
 display(event.currentTarget.selectedItem);
 }
 ]]>
 </mx:Script>
 <mx:VBox  x="44" y="38" >
 <mx:ComboBox id="countryCB" minWidth="200" labelField="@country" change="onChange(event)"/>
 <mx:Text text="" id="displayStr" fontWeight="bold" />
 </mx:VBox>

</mx:Application>

country.xml


<countries>
 <record country="Abkhazia" capital="Sukhum" language="Abhazian,Russian,Cyrillic script"/>
 <record country="Afghanistan" capital="Kabul" language="Dari-Persian, Pashtu"/>
 <record country="Albania" capital="Tirana" language="Albanian"/>
 <record country="Algeria" capital="Algiers" language="Arabic"/>
 <record country="American Samoa" capital="Pago Pago" language="Samoan,English"/>
 <record country="Andorra" capital="Andorra la Vella" language="Catalan"/>
 <record country="Angola" capital="Luanda" language="Portuguese"/>
 <record country="Anguilla" capital="The Valley" language="English"/>
 <record country="Antigua and Barbuda" capital="Saint John's" language="English"/>
 <record country="Argentina" capital="Buenos Aires" language="Spanish"/>
 <record country="Armenia" capital="Yerevan" language="Armenian"/>
 <record country="Aruba" capital="Oranjestad" language="Dutch"/>
 <record country="Australia" capital="Canberra" language="English/ Aborginal native languages"/>
 <record country="Austria" capital="Vienna" language="German"/>
 <record country="Azerbaijan" capital="Baku" language="Azeri"/>
 <record country="Bahamas" capital="Nassau" language="English"/>
 <record country="Bahrain" capital="Manama" language="Arabic"/>
 <record country="Bangladesh" capital="Dhaka" language="Bengali"/>
 <record country="Barbados" capital="Bridgetown" language="English"/>
 <record country="Belarus" capital="Minsk" language="Belarusian,Russian"/>
 <record country="Belgium" capital="Brussels" language="Dutch,French,German"/>
 <record country="Belize" capital="Belmopan" language="English"/>
 <record country="Benin" capital="Porto-Novo" language="French"/>
 <record country="Bermuda" capital="Hamilton" language="English"/>
 <record country="Bhutan" capital="Thimphu" language="Dzongkha"/>
 <record country="Bolivia" capital="La Paz" language="Spanish, Quechua,Ayamara,Guaranj"/>
 <record country="Bosnia-Herzegovina" capital="Sarajevo" language="Bosnian, Serbian, Croatian"/>
 <record country="Botswana" capital="Gaborone" language="English"/>
 <record country="Brazil" capital="Brasilia" language="Portuguese"/>
 <record country="Brunei" capital="Bandar Seri Begawan" language="Malay"/>
 <record country="Bulgaria" capital="Sofia" language="Bulgarian"/>
 <record country="Burkina Faso" capital="Ouagadougou" language="French"/>
 <record country="Burundi" capital="Bujumbura" language="Kirundi"/>
 <record country="Cambodia" capital="Phnom Penh" language="Khmer"/>
 <record country="Cameroon" capital="Yaound�" language="French, English"/>
 <record country="Canada" capital="Ottawa" language="English, French"/>
 <record country="Cape Verde" capital="Praia" language="Portuguese"/>
 <record country="Cayman Islands" capital="George Town" language="English"/>
 <record country="Central African Republic" capital="Bangui" language="French, Sango"/>
 <record country="Chad" capital="N'Djamena" language="French, Arabic"/>
 <record country="Chile" capital="Santiago" language="Spanish"/>
 <record country="China (PRC)" capital="Beijing" language="mandarin"/>
 <record country="Christmas Island" capital="The Settlement" language="English"/>
 <record country="Cocos Islands" capital="West Island" language="English"/>
 <record country="Colombia" capital="Bogot�" language="Spanish"/>
 <record country="Comoros" capital="Moroni" language="Shikomor, Arabic, French"/>
 <record country="Congo" capital="Brazzaville" language="French"/>
 <record country="Congo (DRC)" capital="Kinshasa" language="French"/>
 <record country="Cook Islands" capital="Avarua" language="English"/>
 <record country="Costa Rica" capital="San Jos�" language="Spanish"/>
 <record country="C�te d'Ivoire" capital="Yamoussoukro" language="French"/>
 <record country="Croatia" capital="Zagreb" language="Croatian"/>
 <record country="Cuba" capital="Havana" language="Spanish"/>
 <record country="Cyprus" capital="Nicosia" language="Greek, Turkish"/>
 <record country="Czech Republic" capital="Prague" language="Czech"/>
 <record country="Denmark" capital="Copenhagen" language="Danish"/>
 <record country="Djibouti" capital="Djibouti City" language="Arabic, French"/>
 <record country="Dominica" capital="Roseau" language="English"/>
 <record country="Dominican Republic" capital="Santo Domingo" language="Spanish"/>
 <record country="East Timor" capital="D�li" language="Tetum, Portuguese"/>
 <record country="Ecuador" capital="Quito" language="Spanish"/>
 <record country="Egypt" capital="Cairo" language="Arabic"/>
 <record country="El Salvador" capital="San Salvador" language="Spanish"/>
 <record country="Equatorial Guinea" capital="Malabo" language="Spanish"/>
 <record country="Eritrea" capital="Asmara" language="Arabic, Tigrinya"/>
 <record country="Estonia" capital="Tallinn" language="Estonian"/>
 <record country="Ethiopia" capital="Addis Ababa" language="Amharic"/>
 <record country="Faroe Islands" capital="T�rshavn" language="Faroese"/>
 <record country="Fiji" capital="Suva" language="English, Fijian, Hindustani"/>
 <record country="Finland" capital="Helsinki" language="Finnish, Swedish"/>
 <record country="France" capital="Paris" language="French"/>
 <record country="French Guiana" capital="Cayenne" language="French"/>
 <record country="French Polynesia" capital="Papeete" language="French"/>
 <record country="Gabon" capital="Libreville" language="French"/>
 <record country="Gambia" capital="Banjul" language="English"/>
 <record country="Georgia" capital="T'bilisi" language="Georgian"/>
 <record country="Germany" capital="Berlin" language="German"/>
 <record country="Ghana" capital="Accra" language="English"/>
 <record country="Gibraltar" capital="Gibraltar" language="English"/>
 <record country="Greece" capital="Athens" language="Greek"/>
 <record country="Greenland" capital="Nuuk" language="Greenlandic, Danish"/>
 <record country="Grenada" capital="St. George's" language="English"/>
 <record country="Guadeloupe" capital="Basse-Terre" language="French"/>
 <record country="Guam" capital="Hag�t�a" language="English"/>
 <record country="Guatemala" capital="Guatemala City" language="Spanish"/>
 <record country="Guernsey" capital="St Peter Port" language="English"/>
 <record country="Guinea" capital="Conakry" language="French, Maninka, Susu, Pular"/>
 <record country="Guinea-Bissau" capital="Bissau" language="Portuguese"/>
 <record country="Guyana" capital="Georgetown" language="English"/>
 <record country="Haiti" capital="Port-au-Prince" language="French, Haitian Creole"/>
 <record country="Honduras" capital="Tegucigalpa" language="Spanish"/>
 <record country="Hungary" capital="Budapest" language="Hungarian"/>
 <record country="Iceland" capital="Reykjav�k" language="Icelandic"/>
 <record country="India" capital="New Delhi" language="Assamese,Bengali,English,Hindi,Kannada,Kashmiri,Konkani,Malayalam,Marathi"/>
 <record country="Indonesia" capital="Jakarta" language="Indonesian"/>
 <record country="Iran" capital="Tehran" language="Persian"/>
 <record country="Iraq" capital="Baghdad" language="Arabic"/>
 <record country="Ireland" capital="Dublin" language="Irish, English"/>
 <record country="Isle of Man" capital="Douglas" language="English, Manx"/>
 <record country="Israel" capital="Jerusalem" language="Hebrew, Arabic"/>
 <record country="Italy" capital="Rome" language="Italian"/>
 <record country="Jamaica" capital="Kingston" language="English"/>
 <record country="Japan" capital="Tokyo" language="Japanese"/>
 <record country="Jersey" capital="St. Helier" language="English, French, J�rriais"/>
 <record country="Jordan" capital="Amman" language="Arabic"/>
 <record country="Kazakhstan" capital="Astana" language="Kazakh, Russian"/>
 <record country="Kenya" capital="Nairobi" language="English, Swahili"/>
 <record country="Kiribati" capital="South Tarawa" language="English, Gilbertese"/>
 <record country="Korea (South)" capital="Seoul" language="Korean"/>
 <record country="Korea (North)" capital="P'y?ngyang" language="Korean"/>
 <record country="Kosovo" capital="Prishtin�" language="Albanian, Serbian"/>
 <record country="Kuwait" capital="Kuwait City" language="Arabic"/>
 <record country="Kyrgyzstan" capital="Bishkek" language="Kyrgyz, Russian"/>
 <record country="Laos" capital="Vientiane" language="Lao,Lao alphabet"/>
 <record country="Latvia" capital="Riga" language="Latvian"/>
 <record country="Lebanon" capital="Bairut" language="Arabic"/>
 <record country="Lesotho" capital="Maseru" language="Sesotho, English"/>
 <record country="Liberia" capital="Monrovia" language="English"/>
 <record country="Libya" capital="Tripoli" language="Arabic"/>
 <record country="Liechtenstein" capital="Vaduz" language="German"/>
 <record country="Lithuania" capital="Vilnius" language="Lithuanian"/>
 <record country="Luxembourg" capital="Luxembourg" language="Luxembourgish, German, French"/>
 <record country="Macedonia" capital="Skopje" language="Macedonian"/>
 <record country="Madagascar" capital="Antananarivo" language="Malagasy, French"/>
 <record country="Malawi" capital="Lilongwe" language="English, Chichewa"/>
 <record country="Malaysia" capital="Kuala Lumpur" language="Malay, English, Dhivehi"/>
 <record country="Maldives" capital="Mal�" language="Dhivehi"/>
 <record country="Mali" capital="Bamako" language="French, Bambara"/>
 <record country="Malta" capital="Valletta" language="Maltese"/>
 <record country="Marshall Islands" capital="Majuro" language="English, Marshallese"/>
 <record country="Martinique" capital="Fort-de-France" language="French"/>
 <record country="Mauritania" capital="Nouakchott" language="French, Arabi"/>
 <record country="Mauritius" capital="Port Louis" language="French"/>
 <record country="Mayotte" capital="Mamoudzou" language="French"/>
 <record country="Mexico" capital="Mexico City" language="Spanish"/>
 <record country="Micronesia" capital="Palikir" language="English"/>
 <record country="Moldova" capital="Chi?in?u" language="Romanian, French"/>
 <record country="Monaco" capital="" language=""/>
 <record country="Mongolia" capital="Ulaanbaatar" language="Mongolian"/>
 <record country="Montenegro" capital="Podgorica" language="Croatian"/>
 <record country="Montserrat" capital="Brades Estate" language="English"/>
 <record country="Morocco" capital="Rabat" language="Arabic"/>
 <record country="Mozambique" capital="Maputo" language="Portuguese"/>
 <record country="Myanmar" capital="Naypyidaw" language="Burmese"/>
 <record country="Namibia" capital="Windhoek" language="English, German, Afrikaans"/>
 <record country="Nauru" capital="no capital" language="English, Nauruan"/>
 <record country="Nepal" capital="Kathmandu" language="Nepali, Devanagari"/>
 <record country="Netherlands" capital="Amsterdam" language="Dutch"/>
 <record country="Netherlands Antilles" capital="Willemstad" language="Dutch"/>
 <record country="New Caledonia" capital="Noum�a" language="French"/>
 <record country="New Zealand" capital="Wellington" language="English, Maori"/>
 <record country="Nicaragua" capital="Managua" language="Spanish"/>
 <record country="Niger" capital="Niamey" language="French"/>
 <record country="Nigeria" capital="Abuja" language="English,Hausa,Igbo,Yoruba,Fulfulde,Broken English"/>
 <record country="Niue" capital="Alofi" language="Niuean, English"/>
 <record country="Norfolk Island" capital="Kingston" language="English"/>
 <record country="Northern Mariana Islands" capital="Saipan" language="English"/>
 <record country="Norway" capital="Oslo" language="Norwegian Bokmal, Norwegian Nynorsk"/>
 <record country="Oman" capital="Muscat" language="Arabic"/>
 <record country="Pakistan" capital="Islamabad" language="Urdu"/>
 <record country="Palau" capital="Melekeok" language="English, Palauan"/>
 <record country="Palestinian territories" capital="Ramallah" language="Arabic"/>
 <record country="Panama" capital="Panama City" language="Spanish"/>
 <record country="Papua New Guinea" capital="Port Moresby" language="English, Tok Pisin, Hiri Motu"/>
 <record country="Paraguay" capital="Asunci�n" language="Spanish, Guaranj"/>
 <record country="Peru" capital="Lima" language="Spanish"/>
 <record country="Philippines" capital="Manila" language="Filipino, English, Spanish"/>
 <record country="Pitcairn Islands" capital="Adamstown" language="English"/>
 <record country="Poland" capital="Warsaw" language="Polish"/>
 <record country="Portugal" capital="Lisbon" language="Portuguese"/>
 <record country="Puerto Rico" capital="San Juan" language="Spanish"/>
 <record country="Qatar" capital="Doha" language="Arabic"/>
 <record country="R�union" capital="Saint-Denis" language="French"/>
 <record country="Romania" capital="Bucharest" language="Romanian"/>
 <record country="Russia" capital="Moscow" language="Russian"/>
 <record country="Rwanda" capital="Kigali" language="French, Kinyarwanda, English"/>
 <record country="Saint-Pierre and Miquelon" capital="Saint-Pierre" language="French"/>
 <record country="Saint Helena" capital="Jamestown" language="English"/>
 <record country="Saint Kitts and Nevis" capital="Basseterre" language="English"/>
 <record country="Saint Lucia" capital="Castries" language="English"/>
 <record country="Saint Vincent and the Grenadines" capital="Kingstown" language="English"/>
 <record country="Samoa" capital="Apia" language="English"/>
 <record country="San Marino" capital="San Marino" language="Italian"/>
 <record country="S?o Tom� and Pr�ncipe" capital="S?o Tom�" language="Portuguese"/>
 <record country="Saudi Arabia" capital="Riyadh" language="Arabic"/>
 <record country="Senegal" capital="Dakar" language="French"/>
 <record country="Serbia" capital="Belgrade" language="Serbian"/>
 <record country="Seychelles" capital="Victoria" language="Seychellois Creole, French, English"/>
 <record country="Sierra Leone" capital="Freetown" language="English"/>
 <record country="Singapore" capital="" language="Malay, English, Mandarin, Tamil"/>
 <record country="Slovakia" capital="Bratislava" language="Slovak"/>
 <record country="Slovenia" capital="Ljubljana" language="Slovene"/>
 <record country="Solomon Islands" capital="Honiara" language="English"/>
 <record country="Somalia" capital="Mogadishu" language="Somali, Arabic"/>
 <record country="South Africa" capital="Pretoria (administrative capital), Cape Town (legislative capital), Bloemfo" language="English, Afrikaans, Zulu, Xhosa, Pedi, Sotho, Tswana, Venda, Tsonga, Swazi,"/>
 <record country="South Ossetia" capital="Tskhinval" language="Ossetian, Russian"/>
 <record country="Spain" capital="Madrid" language="Spanish/Galician, Catalan, Basque, Aranese"/>
 <record country="Sri Lanka" capital="Sri Jayawardenepura Kotte" language="Sinhala, Tamil"/>
 <record country="Sudan" capital="Khartoum" language="Arabic"/>
 <record country="Suriname" capital="Paramaribo" language="Dutch"/>
 <record country="Svalbard" capital="Longyearbyen" language="Norwegian"/>
 <record country="Swaziland" capital="Mbabane" language="English"/>
 <record country="Sweden" capital="Stockholm" language="Swedish"/>
 <record country="Switzerland" capital="Berne" language="German, French, Italian, Romansh"/>
 <record country="Syria" capital="Damascus" language="Arabic"/>
 <record country="Taiwan" capital="Taipei" language="Chinese"/>
 <record country="Tajikistan" capital="Dushanbe" language="Tajiki-Persian"/>
 <record country="Tanzania" capital="Dodoma" language="English"/>
 <record country="Thailand" capital="Bangkok" language="Thai"/>
 <record country="Togo" capital="Lom�" language="French"/>
 <record country="Tokelau" capital="" language="English"/>
 <record country="Tonga" capital="Nuku?alofa" language="Tongan"/>
 <record country="Transnistria" capital="Tiraspol" language="Russian, Ukrainian, Moldovan"/>
 <record country="Trinidad and Tobago" capital="Port of Spain" language="English"/>
 <record country="Tunisia" capital="Tunis" language="Arabic"/>
 <record country="Turkey" capital="Ankara" language="Turkish"/>
 <record country="Turkmenistan" capital="Ashgabat" language="Turkmen"/>
 <record country="Turks and Caicos Islands" capital="Cockburn Town" language="English"/>
 <record country="Tuvalu" capital="Fongafale (in Funafuti)" language="English"/>
 <record country="Uganda" capital="Kampala" language="English"/>
 <record country="Ukraine" capital="Kiev" language="Ukrainian"/>
 <record country="United Arab Emirates" capital="Abu Dhabi" language="Arabic"/>
 <record country="United Kingdom" capital="London" language="English, Welsh, Scots, Scots gaelic, Irish"/>
 <record country="United States" capital="Washington, D.C." language="English, Spanish, Cajun French, Hawaiian"/>
 <record country="Uruguay" capital="Montevideo" language="Spanish"/>
 <record country="Uzbekistan" capital="Tashkent" language="Uzbek"/>
 <record country="Vanuatu" capital="Port Vila" language="English"/>
 <record country="Vatican City" capital="" language="Latin"/>
 <record country="Venezuela" capital="Caracas" language="Spanish"/>
 <record country="Vietnam" capital="Hanoi" language="Vietnamese"/>
 <record country="Virgin Islands, British" capital="Road Town" language="English"/>
 <record country="Virgin Islands, US" capital="Charlotte Amalie" language="English"/>
 <record country="Wales" capital="Cardiff" language="English, Welsh"/>
 <record country="Wallis and Futuna" capital="Mat�'Utu" language="French"/>
 <record country="Western Sahara" capital="Laayoune (French transliteration)" language="Arabic"/>
 <record country="Yemen" capital="Sana�" language="Arabic"/>
 <record country="Zambia" capital="Lusaka" language="English"/>
 <record country="Zimbabwe" capital="Harare" language="English"/>

</countries>

In the creationComplete event of application an HttpService is sent and got country.xml as its response. To get the attributes details attributes() method of XML is used and it will return XMLList (this can also be achieved  by xml.@* and it will also return XMLList). To get the attribute name use name() method of XMLList and we can directly get the value of attribute from the list by index number.

We can modify the attributes names, count and values without change in the flex code, just by changing in the xml file. In this xml I just included country name, capital city and language and you can include values like currency, continent etc.,

Dynamic Width of ComboBox (Small Tweak)

Recently I have gone through a situation where there will be a ComboBox and it will have a list of data, some items will be too lengthy. And I have to show the width of Combo with the maximum size of the item in the dropdown list of Combo. First I thought I must iterate through through all the list items and get all the lenths and find the maximum length of the item. And then set that length to the comob. I search for samples with any simpler solution than the above, but all the people suggest the above process only.

Instead of doing the above process just remove the width property to the combo, instead provide minWidth (so that combo will show minimum width even there is no data). This solves my problem.

ComboBox ItemRenderer in flex DataGrid

For my Application I need a CobmboBox in Datagrid, and the combo will have a list of data. For this I googled a few samples. Here is a sample code, I modified it with my requirements.

My requirement is populate the Datagrid and there will be columns in datagrid that can be modified and updated to the database. To achive this I created ComboBox as ItemRenderer in the DataGridColumn. The data to the Combo must be dynamic.

Sample Code

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
 creationComplete="fillDataGrid()">

 <mx:Script>
 <![CDATA[
 import mx.collections.ArrayCollection;

 //  data provider of combo in datagrid, can get dynamic data by a service
 private var comboData:Array = new Array("Value0","Value1","Value2","Value3");

 /**
  *  populate the datagrid with sample data
  */
 private function fillDataGrid():void {
 var arrColl:ArrayCollection = new ArrayCollection;
 for (var i:int=0,j:int=0; i<50; i++,j++ ) {
 if ( j>3 ) j=0;

// create an object that will be provided to combo
 var obj:Object = new Object;
 obj.value = "Value"+j;
 obj.list = comboData;

// data is for first column, com is for the itemrenderer in that com object
 //value is slectedItem of combo and list is the provider of that combo
 arrColl.addItem({data:"data"+i, com:obj});

}

dg.dataProvider = arrColl;

}
 ]]>

</mx:Script>
 <mx:DataGrid id="dg" x="60" y="21" rowCount="5">
 <mx:columns>
 <mx:DataGridColumn dataField="data" headerText="Data" />
 <mx:DataGridColumn headerText="Value" itemRenderer="DynRender" />
 </mx:columns>
 </mx:DataGrid>
 </mx:Application>

DynRender.mxml


<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" horizontalScrollPolicy="off">

<mx:Script>
<![CDATA[

 override public function set data(value:Object):void {
   if(value != null) {
    super.data = value;
    mycombo.selectedItem=data.com.value;
   }

 }
 ]]>

</mx:Script>
<mx:ComboBox id="mycombo" dataProvider="{data.com.list}" width="100%"  />
</mx:Canvas>

The required data for the combo box is provided by the collection in ‘com’ item, In that we will provide the list item as dataprovider of the combo box. And value will the the selectedItem.

Embedding font in Flex 4 (spark components)

Embedding fonts in Flex 3 can be achived by


@font-face {
 src : url("comic.TTF");
 fontFamily : comic;
 }

But this will not work in flex 4. We need to add one more property ‘cff’ and setting it to true.


<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
minWidth="1024" minHeight="768">

 <fx:Style>
 @namespace mx "library://ns.adobe.com/flex/halo";
 @namespace s "library://ns.adobe.com/flex/spark";

 @font-face {
 src : url("comic.TTF");
 fontFamily : comic;
 cff : true;
 }
 .myStyle {
 font-family : comic;
 font-size : 24;
 }
 </fx:Style>

 <s:RichText fontFamily="comic" x="40" y="23">
 Embedding font in flex 4 - RichText
 </s:RichText>
 <s:SimpleText styleName="myStyle" x="40" y="63">
 Embedding font in flex 4 - RichText
 </s:SimpleText>
</s:Application>

Adding milliseconds to given time in flex

This is a sample example to add milliseconds to the given time

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
 <mx:Script>
 <![CDATA[
 import mx.controls.Alert;

 private function convert():void {
 if (timeGiven.text != "") {
 var arr:Array = timeGiven.text.split(':');

 var time:Number = Number(arr[3]);
 time += Number(arr[2]) * 1000;
 time += Number(arr[1]) * 60 * 1000;
 time += Number(arr[0]) * 60 * 60 * 1000;
 time += Number(addSec.text);

 var starr:Array = new Array;
 starr[3] = time % 1000;
 time -= starr[3];
 starr[2] = (time/1000) % 60;
 time -= starr[2] *1000;
 starr[1] = (time/(1000*60)) % 60;
 time -= starr[1] * 1000 * 60;
 starr[0] = (time/ (1000*60*60)) %60;
 finalTime.text = starr[0] + ":" + starr[1] + ":" + starr[2] + ":" + starr[3];
 }
 }
 ]]>
 </mx:Script>
 <mx:Label x="10" y="61" text="Time(HH:MM:SS:mmm)"/>
 <mx:Label x="10" y="102" text="Enter millisec to add:"/>
 <mx:TextInput id="timeGiven" x="170" y="61"/>
 <mx:Button x="170" y="147" label="add" click="convert()"/>
 <mx:TextInput x="170" y="100" id="addSec"/>
 <mx:Label x="256" y="149" id="finalTime"/>

</mx:Application>

screen shot

BlazeDS,LiveCycle DS Configuration

Configuration of the destinations of messaging is done in the messaging-config.xml file. The file looks like this.

<?xml version="1.0" encoding="UTF-8"?>
<service id="message-service">
    <adapters>
        <adapter-definition id="actionscript"
                            default="true"/>
        <adapter-definition id="jms" default="false"/>
    </adapters>

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

    <destination id="stock-topic-jms">
        <properties>
            <jms>
                <destination-type>Topic</destination-type>
                <message-type>javax.jms.ObjectMessage</message-type>
                <connection-factory>java:comp/env/jms/flex/TopicConnectionFactory</connection-factory>
                <destination-jndi-name>java:comp/env/jms/stockMessageTopic</destination-jndi-name>
                <delivery-mode>NON_PERSISTENT</delivery-mode>
                <message-priority>DEFAULT_PRIORITY</message-priority>
                <acknowledge-mode>AUTO_ACKNOWLEDGE</acknowledge-mode>
                <initial-context-environment>
                    <property>
                        <name>Context.INITIAL_CONTEXT_FACTORY</name>
                        <value>org.apache.activemq.jndi.ActiveMQInitialContextFactory</value>
                    </property>
                    <property>
                        <name>Context.PROVIDER_URL</name>
                        <value>tcp://localhost:61616</value>
                    </property>
                </initial-context-environment>
            </jms>
        </properties>
        <adapter ref="jms"/>
    </destination>
</service>

There are a few things to notice here. You can see the message type, the connection factory and destination using JNDI. The initial context environment is coming from ActiveMQ and the provider url should be familiar by now.

The client

The final step is the flex client. Flex has very good support for consumers and producers. On the client I am mainly using Mate, which is a flex event driven framework. It has support for messaging as well through the MessageHandlers tag. It turns however that flex 3.2 has a problem together with Mate. Check this blog post for the way it should work and go through the comments to get an idea why it does not work. Because of this problem I had to take a slight detour. The most important part is very easy though. The following code block shows the most important part of configuring a consumer.

<mx:Consumer id="consumer" destination="stock-topic-jms" message="messageHandler(event)"
acknowledge="acknowledgeHandler(event);" fault=" faultHandler(event)"/>

Then finally you need to login, this can best be done in the creationComplete handler.

private function logon():void {
consumer.subscribe();
}

That is it, now you just have to implement the three methods that are attached to the consumer. I’ll show the messageHandler implementation as the last piece of the puzzle.

private function messageHandler(event:MessageEvent):void {
    var stock:Stock = event.message.body as Stock;
    var updateEvent:StockEvent = new StockEvent(StockEvent.UPDATE_STOCKITEM_EVENT);
    updateEvent.stock = stock;
    dispatchEvent(updateEvent);
}

Notice that by using the ObjectMessage type, the body of a message is a stock object.