Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Interacting with Server-Side Applications - Adobe Flex 2

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Client Technologies - Adobe Flex 2 and Rich Internet Applications

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Interacting with Server-Side Applications - Adobe Flex 2

Flex makes it easy to consume web services.

Interacting with Server-Side Applications

 

Flex makes it easy to consume web services. In this example (Fig. 18.15), we use a web service from WebServiceX.net to obtain weather data based on a zip code. The user inputs the zip code, clicks a button and a five-day forecast is displayed on the screen (Fig. 18.16). Additionally, a marker is placed on a Yahoo! Map at the zip code’s location, and the fore-cast information is displayed in the marker’s tool tip (Fig. 18.17). You can test a live version of this application at test.deitel.com/examples/iw3htp4/flex/weather/. More information on web services is available in Chapter 28, Web Services, and at our Web Services Resource Center at  www.deitel.com/webservices.

1     <?xml version = "1.0" encoding = "utf-8" ?>

 

2     <!-- Fig. 18.15: weather.mxml -->

 

3     <!-- Weather Forecast application in Flex 2 -->

 

4     <mx:Application xmlns:mx = "http://www.adobe.com/2006/mxml"

 

5           layout = "absolute" xmlns:yahoo = "com.yahoo.webapis.maps.*"

 

6           creationComplete = "initMap();" >

7

8        <mx:Script source = "map.as" />

 

9

10          <mx:Script>

 

11          <![CDATA[

 

12                 import mx.controls.dataGridClasses.DataGridColumn;

 

13                 import mx.rpc.events.ResultEvent;

 

14                 import mx.managers.CursorManager;

 

15                 import mx.controls.Alert;

 

16                 import mx.collections.ArrayCollection;

 

17                 import flash.events.MouseEvent;

18

19                 // define default namespace

 

20                 default xml namespace = "http://www.webservicex.net";

21           

22                 [Bindable]

 

23                 private var xmlData : XML;

 

24                 [Bindable]

 

25                 private var highLowTemp : String;

 

26                 [Bindable]

 

27                 private var fiveDayForecast : String = "";

 

28                 [Bindable]

 

29                 private var placeName : String;

30

31                 // handle getWeatherButton click action

 

32                 private function getWeather() : void

33                 {

 

34                       // disable button while request is pending

 

35                       getWeatherButton.enabled = false;

36

37                       // hide the old forecast data before displaying new data

 

38                       forecastBox.visible = false;

39

40                       // reset place name while loading new data

 

41                       placeNameText.text = "";

42

43                       // show the loading progress bar

 

44                       loadingBar.visible = true;

45

46                       // request the new data

 

47                       weatherService.GetWeatherByZipCode.send();

 

48                 } // end function getWeather

49

 

50                 private function weatherResultHandler(event : ResultEvent) : void

51                 {

 

52                       // save the result of the web service as XML

 

xmlData = XML( event.result );

55                       // check that result is valid by checking length of StateCode

 

56                       if ( xmlData.GetWeatherByZipCodeResult[ 0 ].

57                              StateCode.text().length() != 0 )

{

59        // set placeNameText to the city and state of the zip code

60        placeName = xmlData.GetWeatherByZipCodeResult[ 0 ].

61                    PlaceName.text() + ", " +

62                    xmlData.GetWeatherByZipCodeResult[ 0 ].StateCode.text();

63        placeNameText.text = "5 Day Forecast for " + placeName;

64                                           

65                    // set image, temperature and date for each day           

66                    setData( weatherImage0, weatherTemp0, weatherDay0, 0 ); 

67                    setData( weatherImage1, weatherTemp1, weatherDay1, 1 ); 

68                    setData( weatherImage2, weatherTemp2, weatherDay2, 2 ); 

69                    setData( weatherImage3, weatherTemp3, weatherDay3, 3 ); 

70                    setData( weatherImage4, weatherTemp4, weatherDay4, 4 ); 

71                                           

72        forecastBox.visible = true;

73                                           

74        // save today’s high/low as a string

75        highLowTemp =  xmlData.GetWeatherByZipCodeResult.

76                    Details.WeatherData.MaxTemperatureF[ 0 ].text() +

77                    "/" + xmlData.GetWeatherByZipCodeResult.Details.

78                    WeatherData.MinTemperatureF[ 0 ].text();

79                                           

80        // save the five-day forecast as a string

81        fiveDayForecast = highLowTemp;

82                                           

83                    for ( var i : int = 1; i < 5; i++ )          

84                    {                      

85                    fiveDayForecast += ", " + xmlData.          

86                    GetWeatherByZipCodeResult.Details.WeatherData.  

87                    MaxTemperatureF[ i ].text() + "/" + xmlData.       

88                    GetWeatherByZipCodeResult.Details.   

89                    WeatherData.MinTemperatureF[ i ].text();           

90                    } // end for     

91                                           

92        // place a marker on the map with the forecast

93        mapController.addCustomPOIMarker(

94                    zipcode.text, placeName, highLowTemp, fiveDayForecast,

95                    0x990099, 0xFFFFFF);

96                                           

97        mapController.setCenterByAddressAndZoom(

98                    zipcode.text, 7, 0 );

99        }                                  

100                     else

101                     {

 

102                           Alert.show( "Invalid zip code" );

103                     }

 

104                     // hide the loading progress bar

 

105                     loadingBar.visible = false;

106

 

107                     // enable getWeatherButton

 

108                     getWeatherButton.enabled = true;

 

109              } // end function weatherResultHandler

110        

111              private function setData( forecastImage : Image,

 

112                     tempText : Text, dateText : Text, i : int ) : void

113              {

 

114                     // set the image for each day

 

115                     forecastImage.source = xmlData.GetWeatherByZipCodeResult.

 

116                           Details.WeatherData.WeatherImage[ i ].text();

117

118                     // set the temperature for each day

 

119                     tempText.text = xmlData.GetWeatherByZipCodeResult.

 

120                           Details.WeatherData.MaxTemperatureF[ i ].text() +

 

121                           "\n" + xmlData.GetWeatherByZipCodeResult.Details.

 

122                           WeatherData.MinTemperatureF[ i ].text();

123

124                     // set the date for each day

 

125                     dateText.text = xmlData.GetWeatherByZipCodeResult.

 

126                           Details.WeatherData.Day[ i ].text();

127              }

128       ]]>

 

129       </mx:Script>

130

131       <!-- show/hide animations for forecast boxes -->

 

132       <mx:Parallel id = "forecastAnimationIn">

 

133              <mx:Fade duration = "1000" alphaFrom = "0.0" alphaTo = "1.0" />

 

134              <mx:Zoom zoomWidthTo = "1" zoomHeightTo = "1" zoomWidthFrom = "0

 

135                    zoomHeightFrom = "0" />

 

136       </mx:Parallel>

137

138       <mx:Parallel id = "forecastAnimationOut">

 

139              <mx:Fade duration = "500" alphaFrom = "1.0" alphaTo = "0.0" />

 

140              <mx:Zoom zoomWidthTo = "0" zoomHeightTo = "0" zoomWidthFrom = "1"

 

141                     zoomHeightFrom = "1" />

 

142       </mx:Parallel>

143

144       <!-- WebService description -->

 

145       <mx:WebService id = "weatherService"

 

146              wsdl = "http://www.webservicex.net/WeatherForecast.asmx?WSDL"

 

147              fault = "Alert.show( event.fault.faultString )"

 

148              result = "weatherResultHandler( event )"

 

149              showBusyCursor = "true">

 

150              <mx:operation name = "GetWeatherByZipCode" resultFormat = "e4x">

 

151                     <mx:request>

 

152                           <ZipCode>{ zipcode.text }</ZipCode>

 

153                     </mx:request>

 

154              </mx:operation>

 

155       </mx:WebService>

156

157       <!-- user interface begins here -->

 

158       <mx:Panel title = "Weather" width = "100%" height = "100%">

 

<mx:Accordion id = "accordion" width = "100%" height = "100%"

160                     creationPolicy = "all">

 

161                     <mx:VBox label = "Forecast View" width = "100%" height = "100%">

 

<mx:ApplicationControlBar

163     defaultButton =        "{ getWeatherButton }">

164     <mx:Label width       = "100%"

165     text = "Enter a zip code:" />

166     <mx:TextInput id = "zipcode" left = "10" />

167     <mx:Button id =        "getWeatherButton" label = "Get Weather"

168     click = "getWeather()" left = "10" />

169     </mx:ApplicationControlBar>

170                

171     <mx:Text fontWeight = "bold" id = "placeNameText" />

 

172     <mx:ProgressBar id = "loadingBar" indeterminate = "true"

 

labelPlacement = "bottom" visible = "false" minimum = "0"                

173                            

174     maximum =   "100" label = "Loading Weather Data"                

175     direction         = "right" width = "75%" />               

176                                        

177     <!-- forecastBox holds the five-day forecast -->

 

178     <!-- start off as hidden, define show and hide effects -->

 

179     <mx:HBox id = "forecastBox" width = "100%" height = "100%"

 

visible = "false" showEffect = "{ forecastAnimationIn }"                      

180                            

181     hideEffect = "{ forecastAnimationOut }">                       

182     <mx:VBox id = "forecastBox0" horizontalAlign = "center"       

183     borderStyle = "solid" width = "20%" height = "0%">     

184     <mx:Text id = "weatherDay0" />   

185     <mx:Image id = "weatherImage0" />        

186     <mx:Text id = "weatherTemp0" /> 

187     </mx:VBox>  

188                            

189     <mx:VBox horizontalAlign = "center"      

190     borderStyle = "solid" width = "20%">       

191     <mx:Text id = "weatherDay1" />   

192     <mx:Image id = "weatherImage1" />        

193     <mx:Text id = "weatherTemp1" /> 

194     </mx:VBox>  

195                            

196     <mx:VBox horizontalAlign = "center"      

197     borderStyle = "solid" width = "20%">       

198     <mx:Text id = "weatherDay2" />   

199     <mx:Image id = "weatherImage2" />        

200     <mx:Text id = "weatherTemp2" /> 

201     </mx:VBox>  

202                            

203     <mx:VBox horizontalAlign = "center"      

204     borderStyle = "solid" width = "20%">       

205     <mx:Text id = "weatherDay3" />   

206     <mx:Image id = "weatherImage3" />        

207     <mx:Text id = "weatherTemp3" /> 

208     </mx:VBox>  

209                            

210     <mx:VBox horizontalAlign = "center"      

211     borderStyle = "solid" width = "20%">       

212     <mx:Text id = "weatherDay4" />   

                                   

213                 <mx:Image id = "weatherImage4" />

214                 <mx:Text id = "weatherTemp4" />

215                 </mx:VBox>  

216                 </mx:HBox> 

217                 </mx:VBox>  

218                 <mx:VBox label =     "Map View" width = "100%" height = "100%">

219                 <!-- create Yahoo! Map -->

220                 <yahoo:YahooMapService id = "yahooMap" UUID = "{ UUID }"

221                 swfDomId =   "{ swfDomID }"

222                 apiId = "{        YahooAPIKey }"

223                 mapURL = "{ mapURL }" width = "600" height = "400" />

224                 <mx:HBox>  

225                 <mx:Button    label = "Back"

226                 click = "accordion.selectedIndex=0;" />

227                 <mx:Button    label = "Clear"

228                 click = "mapController.removeAllMarkers();" />

229                 </mx:HBox> 

230                 </mx:VBox> <!-- end "Map View" Section -->

231                 </mx:Accordion>     

232                 </mx:Panel> 

233     </mx:Application>   

Fig. 18.15 | Weather Forecast application in Flex 2.


 

We first look at the user interface part of weather.mxml (lines 158–232). Line 158 begins the user interface definition with a Panel, which holds an Accordion. In the Accor-dion (lines 159–231), there are two VBoxes, one for the Forecast View section (lines 161– 217) and one for the Map View section (lines 218–230). The Forecast View VBox holds a ApplicationControlBar (lines 162–169) that contains the zipcode TextInput box, the Get Weather Button and a ProgressBar that notifies the user that the web service call is


being processed. The ProgressBar element allows you to give the user an idea of an operation’s state. We set the indeterminate attribute of this ProgressBar to true because the application doesn’t know when the web service call will complete.

 

The VBox also holds an HBox (lines 179–216) that contains the five-day forecast. Each day’s forecast is held in a VBox that displays the date, an image representing the weather, and the high and low temperature in Fahrenheit. The HBox containing the forecast is not initially visible (line 180) because we do not want to see the borders of its VBoxes before there is any content. It also has the attributes showEffect and hideEffect (lines 180– 181). These tell Flex which animation to use when the element is shown or hidden. These animations (lines 132–142) use the Parallel element to play effects simultaneously. Each Parallel element contains two effects, Fade and Zoom. The Map View VBox (lines 218–230) contains the YahooMapService element, as well as two Buttons. The first Button simply returns the user to the Forecast View, and the second Button tells the YahooMap-Service object to remove any markers from the map.

 

The weatherService WebService element (lines 145–155) specifies the URL of the Web Services Description Language (WSDL) file for the web service. A WSDL file is an XML file describing what services are available on a server, how to consume those services, what parameters they accept and what they return. Flex uses this WSDL file to make it easy to access the services without further configuration. We specify the fault event han-dler for the web service (line 147) to show an Alert dialog, and the result event handler to be weatherResultHandler (line 148). We then describe a specific method using the operation element (lines 150–154), which specifies the name of the method (GetWeath- erByZipCode), and the desired format of the result (e4x). One way to send parameters to the web service is to enclose request elements in the operation element. In this case, the ZipCode parameter is bound to the text property of the zipcode TextInput. Alternatively, you can specify the parameters when you actually make the web service call using the same syntax that is used to send parameters to a function.

 

ActionScript for Weather Application

 

A Script element (lines 10–129) contains most of this application’s ActionScript. Because the code is located in a CDATA section, the MXML compiler knows not to parse this section as XML in case it contains any reserved characters, such as angle brackets (< and >), that might confuse the compiler. In this section, we define the default XML namespace to be  http://www.webservicex.net (line 20). This prevents us from having to specify this namespace every time we access the XML returned by the web service. Function getWeather (lines 32–48) is invoked when getWeatherButton is clicked. It first disables getWeatherButton and sets the busy cursor. It then hides the HBox containing the forecast data, because it is about to be changed, and resets placeNameText. It continues by showing the loadingBar ProgressBar (line 44) and finally requests the weather data through weatherService.GetWeatherByZipCode’s send method (line 47).

 

Method weatherResultHandler (lines 50–109) is called upon completion of this request. It first saves the web service’s result as an XML object (line 53). It then checks whether the result is valid by seeing if the StateCode returned by the service is not empty. If it is empty, an Alert (line 102) will notify the user that the zip code is invalid. If the StateCode exists, that indicates that the zip code was valid, and that we have received weather data. In this case, the program continues to set placeNameText (line 63) based on the city and state returned by the service, traversing the XML’s tree down to the PlaceName and StateCode items using dot operators (lines 60–62). Next, it displays the data for each data with multiple calls to the setData function (lines 66–70).

 

This function (lines 111–127) sets the source URL of the forecast image for a given day to the URL in the XML’s corresponding WeatherImage element (lines 115–116). The first WeatherImage in the XML has an index of 0. We apply a similar technique to populate the high and low temperature (lines 119–122) and the date for a given day (lines 125– 126). Lines 75–78 save today’s high and low temperature, as well as the five-day forecast, as strings for use in the map marker.

 

Finally, we place a marker on the map using mapController’s addCustomPOIMarker function (lines 93–95). We specify the location of the marker to be the zip code we obtained data for, and title of the marker to be the name of that town or city, as well as today’s high and low temperature. The body of the marker is set to display the five-day forecast. The setCenterByAddressAndZoom function (lines 97–98) zooms in and centers the map on the zip code’s location. The function finally hides the ProgressBar, removes the busy cursor, and enables getWeatherButton.

 

The map.as ActionScript file (Fig. 18.18) handles the map functionality of the weather application. You need to copy the Yahoo! Map com folder and as2map.swf file into the application’s base directory, just as we did for the addressBook application. This version of map.as contains the same initMap, onMapLoaded and onMapError functions as addressBook’s version of map.as, but doesn’t include the function setMarkerByAddress.

The only other change is the swfDomID, which is set to weather (line 10).

 

 

1    // Fig. 18.18: map.as

 

2    // Handle the map functions for the Weather application

 

3    import mx.managers.CursorManager;

 

4    import com.yahoo.webapis.maps.methodgroups.*;

 

5    import mx.controls.Alert;

6

7    // define constants

 

8    private const swfDomID : String = "weather";

 

9    private const UUID : int = Math.random() * 10000;

10          

11  // YahooAPIKey string must be your own from developer.yahoo.com

 

12  private const YahooAPIKey : String = "Your Yahoo API Key Here";

 

13  private const mapURL : String = "as2map.swf";

 

14  private var mapController : MapController;

15

16  private function initMap() : void

17  {

 

18         CursorManager.setBusyCursor(); // turn on busy cursor

19          

20         // wait for map to load, then call onMapLoaded method

 

21         yahooMap.addEventListener( 'onMapLoad', onMapLoaded );

 

22         yahooMap.addEventListener( 'onMapError', onMapError );

 

23  } // end function initMap

24

25  // handle map after it has loaded

 

26  public function onMapLoaded( event : Object ) : void

27  {

 

28         // instantiate map controller

 

29         mapController = new MapController( yahooMap );

30

31         // instantiate panTool method

 

32         var panTools : PanTool = new PanTool( yahooMap );

33          

34         // allow user to pan across the map

 

35         panTools.setPanTool( true );

36

37         // instantiate the maps widget class

 

38         var widgets : Widgets = new Widgets( yahooMap );

39          

40         // activate Navigator widget

 

41         widgets.showNavigatorWidget();

42          

43         // activate map-type selection widget

 

44         widgets.showSatelliteControlWidget();

45          

46         // turn off busy cursor

 

47         CursorManager.removeBusyCursor();

 

48  } // end function onMapLoaded

49

 

50    public function onMapError( errorCode:String, httpStatus:String ) : void

51  {

 

52         Alert.show(errorCode + '\n' + httpStatus, 'Map Load Error');

 

} // end function onMapError

Fig. 18.18 | Handle the map functions for the Weather application.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.