Project

General

Profile

Statistics
| Branch: | Revision:

colonymech / docs / www / colonyscout / internal / includes / uploadify / com / adobe / protocols / dict / Dict.as @ f59acf11

History | View | Annotate | Download (9.54 KB)

1
package com.adobe.protocols.dict
2
{
3
	import com.adobe.protocols.dict.events.*;
4
	import com.adobe.protocols.dict.util.*;
5
	
6
	import flash.events.Event;
7
	import flash.events.EventDispatcher;
8
	import flash.events.IOErrorEvent;
9
	import flash.events.ProgressEvent;
10
	import flash.events.SecurityErrorEvent;
11
	import flash.net.Socket;
12
	import mx.rpc.http.HTTPService;
13
	import mx.rpc.events.ResultEvent;
14
	import mx.rpc.events.FaultEvent;
15
	import flash.xml.XMLNode;
16
	import mx.utils.StringUtil;
17

    
18
	public class Dict
19
		extends EventDispatcher
20
	{
21
		// Event type names.
22
		public static var CONNECTED:String = "connected";
23
		public static var DISCONNECTED:String = "disconnected";
24
		public static var IO_ERROR:String = IOErrorEvent.IO_ERROR;
25
		public static var ERROR:String = "error";
26
		public static var SERVERS:String = "servers";
27
		public static var DATABASES:String = "databases";
28
		public static var MATCH_STRATEGIES:String = "matchStrategies";
29
		public static var DEFINITION:String = "definition";
30
		public static var DEFINITION_HEADER:String = "definitionHeader";
31
		public static var MATCH:String = "match";
32
		public static var NO_MATCH:String = "noMatch";
33

    
34
		public static var FIRST_MATCH:uint = 0;
35
		public static var ALL_DATABASES:uint = 1;
36

    
37
		private var socket:SocketHelper;
38
		
39
		private var dbShortList:Boolean;
40

    
41
		public function Dict()
42
		{
43
			this.socket = new SocketHelper();
44
			this.socket.addEventListener(Event.CONNECT, connected);
45
			this.socket.addEventListener(Event.CLOSE, disconnected);
46
			this.socket.addEventListener(SocketHelper.COMPLETE_RESPONSE, incomingData);
47
			this.socket.addEventListener(IOErrorEvent.IO_ERROR, ioError);
48
			this.socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
49
		}
50

    
51
		public function connect(server:String, port:uint = 2628):void
52
		{
53
			if (this.socket.connected)
54
			{
55
				this.socket.close();
56
			}
57
			this.socket.connect(server, port);
58
		}
59

    
60
		public function connectThroughProxy(proxyServer:String,
61
											proxyPort:int,
62
											server:String,
63
											port:uint = 2628):void
64
		{
65
			if (this.socket.connected)
66
			{
67
				this.socket.close();
68
			}
69
			this.socket.setProxyInfo(proxyServer, proxyPort);
70
			this.socket.connect(server, port);
71
		}
72

    
73
		public function disconnect():void
74
		{
75
			this.socket.close();
76
			this.disconnected(null);
77
		}
78

    
79
		public function getServers():void
80
		{
81
			var http:HTTPService = new HTTPService();
82
			http.url = "http://luetzschena-stahmeln.de/dictd/xmllist.php";
83
			http.addEventListener(ResultEvent.RESULT, incomingServerXML);
84
			http.addEventListener(FaultEvent.FAULT, httpError);
85
			http.resultFormat = HTTPService.RESULT_FORMAT_E4X;
86
			http.send();
87
		}
88

    
89
		public function getDatabases(shortList:Boolean=true):void
90
		{
91
			this.dbShortList = shortList;
92
			this.socket.writeUTFBytes("show db\r\n");
93
			this.socket.flush();
94
		}
95

    
96
		public function getMatchStrategies():void
97
		{
98
			this.socket.writeUTFBytes("show strat\r\n");
99
			this.socket.flush();
100
		}
101

    
102
		public function match(database:String, term:String, scope:String="prefix"):void
103
		{
104
			this.socket.writeUTFBytes("match " + database + " " + scope + " \"" + term + "\"\r\n");
105
			this.socket.flush();
106
		}
107

    
108
		public function define(database:String, term:String):void
109
		{
110
			this.socket.writeUTFBytes("define " + database + " \"" + term + "\"\r\n");
111
			this.socket.flush();
112
		}
113

    
114
		public function lookup(term:String, scope:uint):void
115
		{
116
			var flag:String;
117
			if (scope == Dict.ALL_DATABASES)
118
			{
119
				flag = "*";
120
			}
121
			else if (scope == Dict.FIRST_MATCH)
122
			{
123
				flag = "!";
124
			}
125
			this.socket.writeUTFBytes("define " + flag + " \"" + term + "\"\r\n");
126
			this.socket.flush();
127
		}
128

    
129
		//// Private functions ////
130

    
131
		private function connected(event:Event):void
132
		{
133
        	// Wait to dispatch an event until we get the 220 response.
134
    	}
135

    
136
		private function disconnected(event:Event):void
137
		{
138
        	dispatchEvent(new DisconnectedEvent());
139
    	}
140

    
141
		private function incomingServerXML(event:ResultEvent):void
142
		{
143
			var dictd:Namespace = new Namespace("http://www.luetzschena-stahmeln.de/dictd/");
144
			var result:XML = event.result as XML;
145
			var server:String, description:String;
146
			var servers:Array = new Array();
147
			for each (var serverNode:XML in result.dictd::server)
148
			{
149
				server = serverNode.dictd::dictdurl;
150
				description = serverNode.dictd::description;
151
				if (StringUtil.trim(server).length != 0 &&
152
					StringUtil.trim(description).length != 0)
153
				{
154
					var dServer:DictionaryServer = new DictionaryServer();
155
					dServer.server = server.replace("dict://", "");
156
					dServer.description = description;
157
					servers.push(dServer);
158
				}
159
			}
160
			var dEvent:DictionaryServerEvent = new DictionaryServerEvent();
161
			dEvent.servers = servers;
162
			dispatchEvent(dEvent);
163
		}
164

    
165
		private function incomingData(event:CompleteResponseEvent):void
166
		{			
167
			var rawResponse:String = event.response;
168
			var response:Response = this.parseRawResponse(rawResponse);
169
			var responseCode:uint = response.code;
170
			if (responseCode == 552) // no matches
171
			{
172
				throwNoMatchEvent(response);
173
			}
174
			else if (responseCode >= 400 && responseCode <= 599) // error
175
			{
176
				throwErrorEvent(response);
177
			}
178
			else if (responseCode == 220) // successful connection
179
			{
180
				dispatchEvent(new ConnectedEvent());
181
			}
182
			else if (responseCode == 110) // databases are being returned
183
			{
184
				throwDatabasesEvent(response);				
185
			}
186
			else if (responseCode == 111) // matches strategies
187
			{
188
				throwMatchStrategiesEvent(response);
189
			}
190
			else if (responseCode == 152) // matches
191
			{
192
				throwMatchEvent(response);
193
			}
194
			else if (responseCode == 150)
195
			{
196
				throwDefinitionHeaderEvent(response);
197
			}
198
			else if (responseCode == 151)
199
			{
200
				throwDefinitionEvent(response);
201
			}
202
    	}
203

    
204
    	private function ioError(event:IOErrorEvent):void
205
    	{
206
			dispatchEvent(event);
207
    	}
208

    
209
    	private function httpError(event:FaultEvent):void
210
    	{
211
    		trace("httpError!");
212
    	}
213

    
214
    	private function securityError(event:SecurityErrorEvent):void
215
    	{
216
    		trace("security error!");
217
    		trace(event.text);
218
    	}
219

    
220
    	// Dispatch new events.
221

    
222
    	private function throwDatabasesEvent(response:Response):void
223
    	{
224
			var databases:Array = new Array();
225
			var responseArray:Array = response.body.split("\r\n");
226
    		for each (var line:String in responseArray)
227
    		{
228
    			var name:String = line.substring(0, line.indexOf(" "));
229
    			if (name == "--exit--")
230
    			{
231
    				if (this.dbShortList)
232
    				{
233
    					break;
234
    				}
235
    				continue;
236
    			}
237
    			var description:String = line.substring(line.indexOf(" ")+1, line.length).replace(/\"/g,"");
238
    			databases.push(new Database(name, description));
239
    		}
240
    		var event:DatabaseEvent = new DatabaseEvent();
241
    		event.databases = databases;
242
    		dispatchEvent(event);
243
    	}
244

    
245
    	private function throwMatchStrategiesEvent(response:Response):void
246
    	{
247
			var strategies:Array = new Array();
248
			var responseArray:Array = response.body.split("\r\n");
249
    		for each (var line:String in responseArray)
250
    		{
251
    			var name:String = line.substring(0, line.indexOf(" "));
252
    			var description:String = line.substring(line.indexOf(" ")+1, line.length).replace(/\"/g,"");
253
    			strategies.push(new MatchStrategy(name, description));
254
    		}
255
    		var event:MatchStrategiesEvent = new MatchStrategiesEvent();
256
    		event.strategies = strategies;
257
    		dispatchEvent(event);
258
    	}
259

    
260
    	private function throwMatchEvent(response:Response):void
261
    	{
262
			var matches:Array = new Array();
263
			var responseArray:Array = response.body.split("\r\n");
264
    		for each (var line:String in responseArray)
265
    		{
266
    			var match:String = line.substring(line.indexOf(" ")+1, line.length).replace(/\"/g,"");
267
    			matches.push(match);
268
    		}
269
    		var event:MatchEvent = new MatchEvent();
270
    		event.matches = matches;
271
    		dispatchEvent(event);
272
    	}
273

    
274
    	private function throwErrorEvent(response:Response):void
275
    	{
276
    		var event:ErrorEvent = new ErrorEvent();
277
    		event.code = response.code;
278
    		event.message = response.headerText;
279
			dispatchEvent(event);
280
    	}
281

    
282
    	private function throwNoMatchEvent(response:Response):void
283
    	{
284
			dispatchEvent(new NoMatchEvent());
285
    	}
286

    
287
    	private function throwDefinitionHeaderEvent(response:Response):void
288
    	{
289
			var event:DefinitionHeaderEvent = new DefinitionHeaderEvent();
290
			event.definitionCount = uint(response.headerText.substring(0, response.headerText.indexOf(" ")));
291
			dispatchEvent(event);
292
    	}
293

    
294
    	private function throwDefinitionEvent(response:Response):void
295
    	{
296
    		var event:DefinitionEvent = new DefinitionEvent();
297
    		var def:Definition = new Definition();
298
    		var headerText:String = response.headerText;
299
    		var tokens:Array = headerText.match(/"[^"]+"/g);
300
    		def.term = String(tokens[0]).replace(/"/g, "");
301
    		def.database = String(tokens[1]).replace(/"/g, "");
302
    		def.definition = response.body;
303
    		event.definition = def;
304
			dispatchEvent(event);
305
    	}
306

    
307
    	private function parseRawResponse(rawResponse:String):Response
308
    	{
309
    		var response:Response = new Response();
310
    		var fullHeader:String;
311
    		if (rawResponse.indexOf("\r\n") != -1)
312
    		{
313
	    		fullHeader = rawResponse.substring(0, rawResponse.indexOf("\r\n"));
314
    		}
315
    		else
316
    		{
317
    			fullHeader = rawResponse;
318
    		}
319
      		var responseCodeMatch:Array = fullHeader.match(/^\d{3}/);
320
    		response.code = uint(responseCodeMatch[0]);
321
    		response.headerText = fullHeader.substring(fullHeader.indexOf(" ")+1, fullHeader.length);
322
			var body:String = rawResponse.substring(rawResponse.indexOf("\r\n")+2, rawResponse.length);
323
			body = body.replace(/\r\n\.\./, "\r\n.");
324
			response.body = body;
325
    		return response;
326
    	}
327
	}
328
}