rollback flash template

This commit is contained in:
wing328
2015-06-09 12:47:18 +08:00
parent 6253bbff3d
commit eee8685847
15 changed files with 579 additions and 508 deletions
@@ -1,87 +1,87 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<application xmlns="http://ns.adobe.com/air/application/2.0">
<!-- Adobe AIR Application Descriptor File Template.
<!-- Adobe AIR Application Descriptor File Template.
Specifies parameters for identifying, installing, and launching AIR applications.
Specifies parameters for identifying, installing, and launching AIR applications.
xmlns - The Adobe AIR namespace: http://ns.adobe.com/air/application/2.0
The last segment of the namespace specifies the version
of the AIR runtime required for this application to run.
xmlns - The Adobe AIR namespace: http://ns.adobe.com/air/application/2.0
The last segment of the namespace specifies the version
of the AIR runtime required for this application to run.
minimumPatchLevel - The minimum patch level of the AIR runtime required to run
the application. Optional.
-->
minimumPatchLevel - The minimum patch level of the AIR runtime required to run
the application. Optional.
-->
<!-- A universally unique application identifier. Must be unique across all AIR applications.
Using a reverse DNS-style name as the id is recommended. (Eg. com.example.ExampleApplication.) Required. -->
<id>AirExecutorApp</id>
<!-- A universally unique application identifier. Must be unique across all AIR applications.
Using a reverse DNS-style name as the id is recommended. (Eg. com.example.ExampleApplication.) Required. -->
<id>AirExecutorApp</id>
<!-- Used as the filename for the application. Required. -->
<filename>AirExecutorApp</filename>
<!-- Used as the filename for the application. Required. -->
<filename>AirExecutorApp</filename>
<!-- The name that is displayed in the AIR application installer.
May have multiple values for each language. See samples or xsd schema file. Optional. -->
<name>AirExecutorApp</name>
<!-- The name that is displayed in the AIR application installer.
May have multiple values for each language. See samples or xsd schema file. Optional. -->
<name>AirExecutorApp</name>
<!-- An application version designator (such as "v1", "2.5", or "Alpha 1"). Required. -->
<version>v1</version>
<!-- An application version designator (such as "v1", "2.5", or "Alpha 1"). Required. -->
<version>v1</version>
<!-- Description, displayed in the AIR application installer.
May have multiple values for each language. See samples or xsd schema file. Optional. -->
<!-- <description></description> -->
<!-- Description, displayed in the AIR application installer.
May have multiple values for each language. See samples or xsd schema file. Optional. -->
<!-- <description></description> -->
<!-- Copyright information. Optional -->
<!-- <copyright></copyright> -->
<!-- Copyright information. Optional -->
<!-- <copyright></copyright> -->
<!-- Publisher ID. Used if you're updating an application created prior to 1.5.3 -->
<!-- <publisherID></publisherID> -->
<!-- Publisher ID. Used if you're updating an application created prior to 1.5.3 -->
<!-- <publisherID></publisherID> -->
<!-- Settings for the application's initial window. Required. -->
<initialWindow>
<!-- The main SWF or HTML file of the application. Required. -->
<!-- Note: In Flash Builder, the SWF reference is set automatically. -->
<content>AirExecutorApp.swf</content>
<!-- The title of the main window. Optional. -->
<!-- <title></title> -->
<!-- Settings for the application's initial window. Required. -->
<initialWindow>
<!-- The main SWF or HTML file of the application. Required. -->
<!-- Note: In Flash Builder, the SWF reference is set automatically. -->
<content>AirExecutorApp.swf</content>
<!-- The type of system chrome to use (either "standard" or "none"). Optional. Default standard. -->
<!-- <systemChrome></systemChrome> -->
<!-- The title of the main window. Optional. -->
<!-- <title></title> -->
<!-- Whether the window is transparent. Only applicable when systemChrome is none. Optional. Default false. -->
<!-- <transparent></transparent> -->
<!-- The type of system chrome to use (either "standard" or "none"). Optional. Default standard. -->
<!-- <systemChrome></systemChrome> -->
<!-- Whether the window is initially visible. Optional. Default false. -->
<!-- <visible></visible> -->
<!-- Whether the window is transparent. Only applicable when systemChrome is none. Optional. Default false. -->
<!-- <transparent></transparent> -->
<!-- Whether the user can minimize the window. Optional. Default true. -->
<!-- <minimizable></minimizable> -->
<!-- Whether the window is initially visible. Optional. Default false. -->
<!-- <visible></visible> -->
<!-- Whether the user can maximize the window. Optional. Default true. -->
<!-- <maximizable></maximizable> -->
<!-- Whether the user can minimize the window. Optional. Default true. -->
<!-- <minimizable></minimizable> -->
<!-- Whether the user can resize the window. Optional. Default true. -->
<!-- <resizable></resizable> -->
<!-- Whether the user can maximize the window. Optional. Default true. -->
<!-- <maximizable></maximizable> -->
<!-- The window's initial width in pixels. Optional. -->
<!-- <width></width> -->
<!-- Whether the user can resize the window. Optional. Default true. -->
<!-- <resizable></resizable> -->
<!-- The window's initial height in pixels. Optional. -->
<!-- <height></height> -->
<!-- The window's initial width in pixels. Optional. -->
<!-- <width></width> -->
<!-- The window's initial x position. Optional. -->
<!-- <x></x> -->
<!-- The window's initial height in pixels. Optional. -->
<!-- <height></height> -->
<!-- The window's initial y position. Optional. -->
<!-- <y></y> -->
<!-- The window's initial x position. Optional. -->
<!-- <x></x> -->
<!-- The window's minimum size, specified as a width/height pair in pixels, such as "400 200". Optional. -->
<!-- <minSize></minSize> -->
<!-- The window's initial y position. Optional. -->
<!-- <y></y> -->
<!-- The window's minimum size, specified as a width/height pair in pixels, such as "400 200". Optional. -->
<!-- <minSize></minSize> -->
<!-- The window's initial maximum size, specified as a width/height pair in pixels, such as "1600 1200". Optional. -->
<!-- <maxSize></maxSize> -->
</initialWindow>
<!-- The window's initial maximum size, specified as a width/height pair in pixels, such as "1600 1200". Optional. -->
<!-- <maxSize></maxSize> -->
</initialWindow>
<!-- We recommend omitting the supportedProfiles element, -->
<!-- which in turn permits your application to be deployed to all -->
@@ -90,57 +90,57 @@
<!-- only the profiles which your application does support. -->
<!-- <supportedProfiles>desktop extendedDesktop mobileDevice extendedMobileDevice</supportedProfiles> -->
<!-- The subpath of the standard default installation location to use. Optional. -->
<!-- <installFolder></installFolder> -->
<!-- The subpath of the standard default installation location to use. Optional. -->
<!-- <installFolder></installFolder> -->
<!-- The subpath of the Programs menu to use. (Ignored on operating systems without a Programs menu.) Optional. -->
<!-- <programMenuFolder></programMenuFolder> -->
<!-- The subpath of the Programs menu to use. (Ignored on operating systems without a Programs menu.) Optional. -->
<!-- <programMenuFolder></programMenuFolder> -->
<!-- The icon the system uses for the application. For at least one resolution,
specify the path to a PNG file included in the AIR package. Optional. -->
<!-- <icon>
<image16x16></image16x16>
<image32x32></image32x32>
<image48x48></image48x48>
<image128x128></image128x128>
</icon> -->
<!-- The icon the system uses for the application. For at least one resolution,
specify the path to a PNG file included in the AIR package. Optional. -->
<!-- <icon>
<image16x16></image16x16>
<image32x32></image32x32>
<image48x48></image48x48>
<image128x128></image128x128>
</icon> -->
<!-- Whether the application handles the update when a user double-clicks an update version
of the AIR file (true), or the default AIR application installer handles the update (false).
Optional. Default false. -->
<!-- <customUpdateUI></customUpdateUI> -->
<!-- Whether the application handles the update when a user double-clicks an update version
of the AIR file (true), or the default AIR application installer handles the update (false).
Optional. Default false. -->
<!-- <customUpdateUI></customUpdateUI> -->
<!-- Whether the application can be launched when the user clicks a link in a web browser.
Optional. Default false. -->
<!-- <allowBrowserInvocation></allowBrowserInvocation> -->
<!-- Whether the application can be launched when the user clicks a link in a web browser.
Optional. Default false. -->
<!-- <allowBrowserInvocation></allowBrowserInvocation> -->
<!-- Listing of file types for which the application can register. Optional. -->
<!-- <fileTypes> -->
<!-- Listing of file types for which the application can register. Optional. -->
<!-- <fileTypes> -->
<!-- Defines one file type. Optional. -->
<!-- <fileType> -->
<!-- Defines one file type. Optional. -->
<!-- <fileType> -->
<!-- The name that the system displays for the registered file type. Required. -->
<!-- <name></name> -->
<!-- The name that the system displays for the registered file type. Required. -->
<!-- <name></name> -->
<!-- The extension to register. Required. -->
<!-- <extension></extension> -->
<!-- The description of the file type. Optional. -->
<!-- <description></description> -->
<!-- The MIME content type. -->
<!-- <contentType></contentType> -->
<!-- The icon to display for the file type. Optional. -->
<!-- <icon>
<image16x16></image16x16>
<image32x32></image32x32>
<image48x48></image48x48>
<image128x128></image128x128>
</icon> -->
<!-- </fileType> -->
<!-- </fileTypes> -->
<!-- The extension to register. Required. -->
<!-- <extension></extension> -->
<!-- The description of the file type. Optional. -->
<!-- <description></description> -->
<!-- The MIME content type. -->
<!-- <contentType></contentType> -->
<!-- The icon to display for the file type. Optional. -->
<!-- <icon>
<image16x16></image16x16>
<image32x32></image32x32>
<image48x48></image48x48>
<image128x128></image128x128>
</icon> -->
<!-- </fileType> -->
<!-- </fileTypes> -->
</application>
@@ -1,10 +1,14 @@
package io.swagger.event {
import io.swagger.event.Response;
import flash.events.Event;
/**
* Event dispatched by the SDK to communicate success events and failure events.
* If a custom dispatcher has been assigned by the consumer on the generated client then the dispatcher dispatches
* the ApiClientEvent to indicate success or failure of the invocation using the Response
*/
public class ApiClientEvent extends Event {
public class ApiClientEvent extends Event{
/**
* Event type to indicate a unsuccessful invocation
@@ -15,17 +19,18 @@ public class ApiClientEvent extends Event {
* Event type to indicate a successful invocation
*/
public static const SUCCESS_EVENT:String = "successfulInvocation";
public function ApiClientEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false) {
super(type, bubbles, cancelable);
}
/**
* The Response object which contains response info
*/
public var response:Response;
public var response: Response;
/**
* Any additional info
*/
public var message:String;
public function ApiClientEvent(type:String,bubbles:Boolean = false,cancelable:Boolean = false) {
super(type, bubbles, cancelable);
}
}
}
@@ -1,7 +1,10 @@
package io.swagger.exception {
public class ApiError extends Error {
public function ApiError(id:* = 0, message:* = "") {
super(message, id);
}
}
package io.swagger.exception
{
public class ApiError extends Error
{
public function ApiError(id:*=0, message:*="")
{
super(message,id);
}
}
}
@@ -1,32 +1,34 @@
package io.swagger.exception {
public class ApiErrorCodes {
/**
* System exception.
*/
public static const SYSTEM_EXCEPTION:Number = 0;
/**
* With Arguments as current key.
*/
public static const API_KEY_NOT_VALID:Number = 1000;
/**
* With arguments as current token value
*/
public static const AUTH_TOKEN_NOT_VALID:Number = 1001;
/**
* With arguments as input JSON and output class anme
*/
public static const ERROR_CONVERTING_JSON_TO_JAVA:Number = 1002;
/**
* With arguments as JAVA class name
*/
public static const ERROR_CONVERTING_JAVA_TO_JSON:Number = 1003;
public static const ERROR_FROM_WEBSERVICE_CALL:Number = 1004;
/**
* With arguments as current API server name
*/
public static const API_SERVER_NOT_VALID:Number = 1005;
}
package io.swagger.exception
{
public class ApiErrorCodes
{
/**
* System exception.
*/
public static const SYSTEM_EXCEPTION: Number = 0;
/**
* With Arguments as current key.
*/
public static const API_KEY_NOT_VALID: Number = 1000;
/**
* With arguments as current token value
*/
public static const AUTH_TOKEN_NOT_VALID: Number = 1001;
/**
* With arguments as input JSON and output class anme
*/
public static const ERROR_CONVERTING_JSON_TO_JAVA: Number = 1002;
/**
* With arguments as JAVA class name
*/
public static const ERROR_CONVERTING_JAVA_TO_JSON: Number = 1003;
public static const ERROR_FROM_WEBSERVICE_CALL: Number = 1004;
/**
* With arguments as current API server name
*/
public static const API_SERVER_NOT_VALID: Number = 1005;
}
}
@@ -1,17 +1,50 @@
package io.swagger.common {
package io.swagger.common
{
import asaxb.xml.bind.ASAXBContext;
import asaxb.xml.bind.Unmarshaller;
import io.swagger.event.ApiClientEvent;
import io.swagger.event.Response;
import io.swagger.common.ApiUserCredentials;
public class ApiInvoker extends EventDispatcher {
import flash.events.EventDispatcher;
import flash.utils.Dictionary;
import flash.utils.describeType;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.messaging.ChannelSet;
import mx.messaging.channels.HTTPChannel;
import mx.messaging.messages.HTTPRequestMessage;
import mx.rpc.AsyncToken;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.rpc.xml.SimpleXMLEncoder;
import mx.utils.ObjectUtil;
public class ApiInvoker extends EventDispatcher
{
private var _apiUsageCredentials:ApiUserCredentials;
internal var _apiProxyServerUrl:String = "";
private var _baseUrl: String = "";
internal var _useProxyServer: Boolean = true;
private var _proxyHostName:String = "";
private var _apiPath: String = "";
private var _proxyPath: String = "";
public var _apiEventNotifier:EventDispatcher;
private static const DELETE_DATA_DUMMY:String = "dummyDataRequiredForDeleteOverride";
private static const X_HTTP_OVERRIDE_KEY:String = "X-HTTP-Method-Override";
private static const CONTENT_TYPE_HEADER_KEY:String = "Content-Type";
public function ApiInvoker(apiUsageCredentials:ApiUserCredentials, eventNotifier:EventDispatcher, useProxy:Boolean = true) {
public function ApiInvoker(apiUsageCredentials: ApiUserCredentials, eventNotifier: EventDispatcher, useProxy: Boolean = true) {
_apiUsageCredentials = apiUsageCredentials;
_useProxyServer = useProxy;
if (_apiUsageCredentials.hostName != null) {
if(_apiUsageCredentials.hostName != null){
_proxyHostName = _apiUsageCredentials.hostName;
}
_apiPath = _apiUsageCredentials.apiPath;
@@ -19,33 +52,25 @@ public class ApiInvoker extends EventDispatcher {
_apiProxyServerUrl = _apiUsageCredentials.apiProxyServerUrl;
_apiEventNotifier = eventNotifier;
}
public var _apiEventNotifier:EventDispatcher;
internal var _apiProxyServerUrl:String = "";
internal var _useProxyServer:Boolean = true;
private var _apiUsageCredentials:ApiUserCredentials;
private var _baseUrl:String = "";
private var _proxyHostName:String = "";
private var _apiPath:String = "";
private var _proxyPath:String = "";
public function invokeAPI(resourceURL:String, method:String, queryParams:Dictionary, postObject:Object, headerParams:Dictionary):AsyncToken {
public function invokeAPI(resourceURL: String, method: String, queryParams: Dictionary, postObject: Object, headerParams: Dictionary): AsyncToken {
//make the communication
if (_useProxyServer) {
if(_useProxyServer) {
resourceURL = _apiProxyServerUrl + resourceURL;
}
else {
resourceURL = "http://" + _proxyHostName + _apiPath + resourceURL;
else{
resourceURL = "http://"+ _proxyHostName + _apiPath + resourceURL;
}
var counter:int = 0;
var symbol:String = "&";
var paramValue:Object;
var counter: int = 0;
var symbol: String = "&";
var paramValue: Object;
for (var paramName:String in queryParams) {
paramValue = queryParams[paramName];
//var key:String = paramName;
// do stuff
symbol = "&";
if (counter == 0) {
if(counter == 0){
symbol = "?";
}
resourceURL = resourceURL + symbol + paramName + "=" + paramValue.toString();
@@ -55,8 +80,8 @@ public class ApiInvoker extends EventDispatcher {
// trace(resourceURL);
//create a httpservice and invoke the rest url waiting for response
var requestHeader:Object = new Object();
if (headerParams != null) {
for (var key:String in headerParams) {
if(headerParams != null) {
for(var key: String in headerParams) {
requestHeader[key] = headerParams[key];
}
}
@@ -70,18 +95,131 @@ public class ApiInvoker extends EventDispatcher {
}
private function doRestCall( url : String, resultFunction : Function, faultFunction : Function = null,
restMethod : String = "GET",
bodyData : Object = null, headers: Object = null, contentType:String = "application/xml" ) : AsyncToken
{
var httpService : HTTPService = new HTTPService( );
if(headers == null){
headers = new Object();
}
httpService.method = restMethod;
if ( restMethod.toUpperCase() != HTTPRequestMessage.GET_METHOD )
{
//httpService.method = HTTPRequestMessage.POST_METHOD; - not required as we're using the proxy
if( bodyData == null )
{
bodyData = new Object();
}
if(restMethod == HTTPRequestMessage.DELETE_METHOD){
headers[X_HTTP_OVERRIDE_KEY]= HTTPRequestMessage.DELETE_METHOD;
bodyData = DELETE_DATA_DUMMY;
}
else if(restMethod == HTTPRequestMessage.PUT_METHOD){
headers[X_HTTP_OVERRIDE_KEY]= HTTPRequestMessage.PUT_METHOD;
}
else{
headers[CONTENT_TYPE_HEADER_KEY]= contentType;
}
}
else
{
//if the request type is GET and content type is xml then the Flex HTTPService converts it to a POST ... yeah
contentType = null;
}
httpService.url = url;
httpService.contentType = contentType;
httpService.resultFormat = "e4x";
httpService.headers = headers;
httpService.addEventListener( ResultEvent.RESULT, resultFunction );
if( faultFunction != null )
{
httpService.addEventListener( FaultEvent.FAULT, faultFunction );
}
if(_useProxyServer){
httpService.useProxy = true;
var channelSet: ChannelSet = new ChannelSet();
var httpChannel: HTTPChannel = new HTTPChannel();
httpChannel.uri = ApiUrlHelper.getProxyUrl(_proxyHostName, _proxyPath);
channelSet.addChannel(httpChannel);
httpService.channelSet = channelSet;
}
return httpService.send( bodyData );
}
private function onApiRequestResult(event:ResultEvent):void
{
var completionListener: Function = event.token.completionListener;
var result: Object = event.result;
var resultType: Class = event.token.returnType;
var resultObject:Object;
if(resultType != null) {
var context:ASAXBContext = ASAXBContext.newInstance(resultType);
var unmarshaller:Unmarshaller = context.createUnmarshaller();
var resultXML: XML = new XML(event.result);
try{
resultObject = unmarshaller.unmarshal(resultXML);
}
catch(error: TypeError){
var errorResponse: Response = new Response(false, null, "Could not unmarshall response");
if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher
var failureEvent: ApiClientEvent = new ApiClientEvent(event.token.completionEventType);
failureEvent.response = errorResponse;
_apiEventNotifier.dispatchEvent(failureEvent);
}
}
if(resultObject is ListWrapper){
resultObject = ListWrapper(resultObject).getList();
}
}
var response : Response = new Response(true, resultObject);
response.requestId = event.token.requestId;
var successEventType: String = event.token.completionEventType != null ? event.token.completionEventType : ApiClientEvent.SUCCESS_EVENT;
if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher
var successEvent: ApiClientEvent = new ApiClientEvent(successEventType);
successEvent.response = response;
_apiEventNotifier.dispatchEvent(successEvent);
}
}
private function onApiRequestFault(event:FaultEvent):void
{
var completionListener: Function = event.token.completionListener;
if(completionListener != null){
completionListener.call( null, new Response( false, null, event.fault.faultString) );
}
var failureEventType: String = event.token.completionEventType != null ? event.token.completionEventType : ApiClientEvent.FAILURE_EVENT;
if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher
var failureEvent: ApiClientEvent = new ApiClientEvent(failureEventType);
failureEvent.response = new Response( false, null, event.fault.faultString);
_apiEventNotifier.dispatchEvent(failureEvent);
}
}
public function marshal(source:Object):Object {
// trace("marshal got - " + source)
if (source is String) {
if(source is String) {
return source;
} else if (source is Array && source.length > 0) {
var writer:XMLWriter = new XMLWriter();
var sourceArray:Array = source as Array;
var arrayEnclosure:String = getArrayEnclosure(sourceArray);
} else if(source is Array && source.length > 0) {
var writer:XMLWriter=new XMLWriter();
var sourceArray: Array = source as Array;
var arrayEnclosure: String = getArrayEnclosure(sourceArray);
writer.xml.setName(arrayEnclosure);
for (var i:int = 0; i < sourceArray.length; i++) {
var o:Object = sourceArray[i];
var o: Object = sourceArray[i];
writer.xml.appendChild(marshal(o));
}
return writer.xml;
@@ -89,23 +227,24 @@ public class ApiInvoker extends EventDispatcher {
return marshalObject(source);
}
public function marshalObject(source:Object):XML {
var writer:XMLWriter = new XMLWriter();
var objDescriptor:XML = describeType(source);
public function marshalObject(source:Object):XML
{
var writer:XMLWriter=new XMLWriter();
var objDescriptor:XML=describeType(source);
var property:XML;
var propertyType:String;
var propertyValue:Object;
var qualifiedClassName:String = objDescriptor.@name;
qualifiedClassName = qualifiedClassName.replace("::", ".");
var className:String = qualifiedClassName.substring(qualifiedClassName.lastIndexOf(".") + 1);
var qualifiedClassName:String=objDescriptor.@name;
qualifiedClassName=qualifiedClassName.replace("::",".");
var className: String = qualifiedClassName.substring(qualifiedClassName.lastIndexOf(".") + 1);
className = className().toLowerCase() + className.substring(1);
writer.xml.setName(className);
for each(property in objDescriptor.elements("variable")) {
propertyValue = source[property.@name];
if (propertyValue != null) {
if (ObjectUtil.isSimple(propertyValue)) {
for each(property in objDescriptor.elements("variable")){
propertyValue=source[property.@name];
if (propertyValue!=null){
if (ObjectUtil.isSimple(propertyValue)){
writer.addProperty(property.@name, propertyValue.toString());
}
else {
@@ -113,13 +252,13 @@ public class ApiInvoker extends EventDispatcher {
}
}
}
for each(property in objDescriptor.elements("accessor")) {
if (property.@access == "readonly") {
for each(property in objDescriptor.elements("accessor")){
if (property.@access=="readonly"){
continue;
}
propertyValue = source[property.@name];
if (source[property.@name] != null) {
if (ObjectUtil.isSimple(propertyValue)) {
propertyValue=source[property.@name];
if (source[property.@name]!=null){
if (ObjectUtil.isSimple(propertyValue)){
writer.addProperty(property.@name, propertyValue.toString());
}
else {
@@ -130,119 +269,14 @@ public class ApiInvoker extends EventDispatcher {
return writer.xml;
}
public function escapeString(str:String):String {
public function escapeString(str: String): String {
return str;
}
private function doRestCall(url:String, resultFunction:Function, faultFunction:Function = null,
restMethod:String = "GET",
bodyData:Object = null, headers:Object = null, contentType:String = "application/xml"):AsyncToken {
var httpService:HTTPService = new HTTPService();
if (headers == null) {
headers = new Object();
}
httpService.method = restMethod;
if (restMethod.toUpperCase() != HTTPRequestMessage.GET_METHOD) {
//httpService.method = HTTPRequestMessage.POST_METHOD; - not required as we're using the proxy
if (bodyData == null) {
bodyData = new Object();
}
if (restMethod == HTTPRequestMessage.DELETE_METHOD) {
headers[X_HTTP_OVERRIDE_KEY] = HTTPRequestMessage.DELETE_METHOD;
bodyData = DELETE_DATA_DUMMY;
}
else if (restMethod == HTTPRequestMessage.PUT_METHOD) {
headers[X_HTTP_OVERRIDE_KEY] = HTTPRequestMessage.PUT_METHOD;
}
else {
headers[CONTENT_TYPE_HEADER_KEY] = contentType;
}
}
else {
//if the request type is GET and content type is xml then the Flex HTTPService converts it to a POST ... yeah
contentType = null;
}
httpService.url = url;
httpService.contentType = contentType;
httpService.resultFormat = "e4x";
httpService.headers = headers;
httpService.addEventListener(ResultEvent.RESULT, resultFunction);
if (faultFunction != null) {
httpService.addEventListener(FaultEvent.FAULT, faultFunction);
}
if (_useProxyServer) {
httpService.useProxy = true;
var channelSet:ChannelSet = new ChannelSet();
var httpChannel:HTTPChannel = new HTTPChannel();
httpChannel.uri = ApiUrlHelper.getProxyUrl(_proxyHostName, _proxyPath);
channelSet.addChannel(httpChannel);
httpService.channelSet = channelSet;
}
return httpService.send(bodyData);
}
private function onApiRequestResult(event:ResultEvent):void {
var completionListener:Function = event.token.completionListener;
var result:Object = event.result;
var resultType:Class = event.token.returnType;
var resultObject:Object;
if (resultType != null) {
var context:ASAXBContext = ASAXBContext.newInstance(resultType);
var unmarshaller:Unmarshaller = context.createUnmarshaller();
var resultXML:XML = new XML(event.result);
try {
resultObject = unmarshaller.unmarshal(resultXML);
}
catch (error:TypeError) {
var errorResponse:Response = new Response(false, null, "Could not unmarshall response");
if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher
var failureEvent:ApiClientEvent = new ApiClientEvent(event.token.completionEventType);
failureEvent.response = errorResponse;
_apiEventNotifier.dispatchEvent(failureEvent);
}
}
if (resultObject is ListWrapper) {
resultObject = ListWrapper(resultObject).getList();
}
}
var response:Response = new Response(true, resultObject);
response.requestId = event.token.requestId;
var successEventType:String = event.token.completionEventType != null ? event.token.completionEventType : ApiClientEvent.SUCCESS_EVENT;
if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher
var successEvent:ApiClientEvent = new ApiClientEvent(successEventType);
successEvent.response = response;
_apiEventNotifier.dispatchEvent(successEvent);
}
}
private function onApiRequestFault(event:FaultEvent):void {
var completionListener:Function = event.token.completionListener;
if (completionListener != null) {
completionListener.call(null, new Response(false, null, event.fault.faultString));
}
var failureEventType:String = event.token.completionEventType != null ? event.token.completionEventType : ApiClientEvent.FAILURE_EVENT;
if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher
var failureEvent:ApiClientEvent = new ApiClientEvent(failureEventType);
failureEvent.response = new Response(false, null, event.fault.faultString);
_apiEventNotifier.dispatchEvent(failureEvent);
}
}
private function getArrayEnclosure(arr:Array):String {
if (arr != null && arr.length > 0) {
var className:String = flash.utils.getQualifiedClassName(arr[0])
if (className.indexOf("::") > 0)
private function getArrayEnclosure(arr: Array) : String {
if(arr != null && arr.length > 0) {
var className: String = flash.utils.getQualifiedClassName(arr[0])
if(className.indexOf("::") > 0)
className = className.substr(className.indexOf("::") + 2, className.length)
return className.substring(0, 1).toLowerCase() + className.substring(1, className.length) + "s";
@@ -1,4 +1,6 @@
package io.swagger.common {
import io.swagger.common.ApiUserCredentials;
/**
* @private
* Internal class for the Rest client
@@ -10,17 +12,17 @@ internal class ApiUrlHelper {
private static const HTTP_URL_PREFIX:String = "http://";
internal static function appendTokenInfo(restUrl:String, requestHeader:Object, credentials:ApiUserCredentials):String {
internal static function appendTokenInfo(restUrl:String, requestHeader: Object, credentials: ApiUserCredentials): String {
//checks for the presence api credentials on client initialization and not repeated here
if (restUrl.indexOf("?") == -1) {
if(restUrl.indexOf("?") == -1){
restUrl += ( "?" + API_URL_KEY + "=" + credentials.apiToken );
}
else {
else{
restUrl += ( "&" + API_URL_KEY + "=" + credentials.apiToken );
}
requestHeader.api_key = credentials.apiToken;
if (credentials.authToken != null && credentials.authToken != "") {
if(credentials.authToken != null && credentials.authToken != ""){
restUrl += ( "&" + AUTH_TOKEN_URL_KEY + "=" + credentials.authToken );
requestHeader.auth_token = credentials.authToken;
}
@@ -28,7 +30,7 @@ internal class ApiUrlHelper {
return restUrl;
}
internal static function getProxyUrl(hostName:String, proxyPath:String):String {
internal static function getProxyUrl(hostName: String, proxyPath: String): String{
if (hostName(hostName.length - 1) == "/") //remove trailing slash
{
hostName = hostName.substring(0, hostName.length - 1);
@@ -5,24 +5,6 @@ package io.swagger.common {
*
*/
public class ApiUserCredentials {
/**
* Constructor of ApiUserCredentials
* @param apiToken An apitoken that is passed along with the requests
* @param authToken A valid auth_token which could necessary for certain operations
* @param hostName The host name for the Rest API eg. api.companyName.com
* @param userId The userId which is required for certain operations - currently, get user lists
*/
public function ApiUserCredentials(hostName:String, apiPath:String, apiToken:String,
authToken:String = null, userId:Number = -1, apiProxyServerUrl:String = "",
proxyPath:String = null) {
this.hostName = hostName;
this.apiToken = apiToken;
this.authToken = authToken;
this.userId = userId;
this.apiPath = apiPath;
this.apiProxyServerUrl = apiProxyServerUrl;
this.proxyPath = proxyPath;
}
/**
* An apitoken that is passed along with the requests
*/
@@ -39,21 +21,43 @@ public class ApiUserCredentials {
* The host name for the Rest API eg. api.companyName.com
*/
public var hostName:String;
/**
* The base path to the api resources - used along with the hostname
* eg. /v4
*/
public var apiPath: String;
/**
* The base path to the blazeds proxy
* eg. /v4/messagebroker/restproxy
*/
public var proxyPath: String;
/**
* If a proxy server has been set up for the services specify the URL here. This value is used when the Api is invoked with
* the value useProxy as true
*/
public var apiProxyServerUrl: String;
/**
* The base path to the api resources - used along with the hostname
* eg. /v4
* Constructor of ApiUserCredentials
* @param apiToken An apitoken that is passed along with the requests
* @param authToken A valid auth_token which could necessary for certain operations
* @param hostName The host name for the Rest API eg. api.companyName.com
* @param userId The userId which is required for certain operations - currently, get user lists
*/
public var apiPath:String;
/**
* The base path to the blazeds proxy
* eg. /v4/messagebroker/restproxy
*/
public var proxyPath:String;
/**
* If a proxy server has been set up for the services specify the URL here. This value is used when the Api is invoked with
* the value useProxy as true
*/
public var apiProxyServerUrl:String;
public function ApiUserCredentials(hostName: String, apiPath: String, apiToken: String,
authToken: String = null, userId: Number = -1, apiProxyServerUrl: String="",
proxyPath: String = null) {
this.hostName = hostName;
this.apiToken = apiToken;
this.authToken = authToken;
this.userId = userId;
this.apiPath = apiPath;
this.apiProxyServerUrl = apiProxyServerUrl;
this.proxyPath = proxyPath;
}
}
}
@@ -1,7 +1,9 @@
package io.swagger.common {
public interface ListWrapper {
function getList():Array;
}
package io.swagger.common
{
public interface ListWrapper
{
function getList(): Array;
}
}
@@ -6,47 +6,50 @@ package io.swagger.event {
*/
public class Response {
/**
* Indicates whether the invoked operation failed or succeeded
*/
public var isSuccess:Boolean;
/**
* The payload of the succesful operation eg. a Word in a WordRequest
*/
public var payload:Object;
/**
* Error message in case of failure
*/
public var errorMessage:String;
/**
* A request Id that was passed in by the user as a param when invoking the operation
*/
public var requestId:String;
private static const API_ERROR_MSG:String = "Api error response: ";
private static function getFriendlyMessage(errorMessage:String):String {
var result:String = errorMessage;
if (errorMessage == null)
public function Response(isSuccessful: Boolean, payload: Object = null, errorMessage: String = null, requestId: String = null) {
this.isSuccess = isSuccessful;
this.payload = payload;
this.errorMessage = getFriendlyMessage(errorMessage);
}
private static function getFriendlyMessage(errorMessage: String): String{
var result: String = errorMessage;
if(errorMessage == null)
return null;
var errorCode:String;
var errorCodeArray:Array = errorMessage.match(/(?<=HTTP\/1.1 )[0-9][0-9][0-9]/);
if (errorCodeArray != null && errorCodeArray.length == 1) {
var errorCode: String;
var errorCodeArray: Array = errorMessage.match(/(?<=HTTP\/1.1 )[0-9][0-9][0-9]/);
if(errorCodeArray != null && errorCodeArray.length == 1){
errorCode = String(errorCodeArray[0]);
}
var msgArray:Array = errorMessage.match(/(?<=HTTP\/1.1 [0-9][0-9][0-9] )[^]*/);
if (msgArray != null && msgArray.length == 1) {
var msgArray: Array = errorMessage.match(/(?<=HTTP\/1.1 [0-9][0-9][0-9] )[^]*/);
if(msgArray != null && msgArray.length == 1){
result = API_ERROR_MSG + String(msgArray[0]);
}
return result;
}
public function Response(isSuccessful:Boolean, payload:Object = null, errorMessage:String = null, requestId:String = null) {
this.isSuccess = isSuccessful;
this.payload = payload;
this.errorMessage = getFriendlyMessage(errorMessage);
}
/**
* Indicates whether the invoked operation failed or succeeded
*/
public var isSuccess:Boolean;
/**
* The payload of the succesful operation eg. a Word in a WordRequest
*/
public var payload:Object;
/**
* Error message in case of failure
*/
public var errorMessage:String;
/**
* A request Id that was passed in by the user as a param when invoking the operation
*/
public var requestId:String;
public function toString():String {
public function toString(): String {
return "Response (requestId:" + requestId + "; isSuccess:" + isSuccess + "; errorMessage:" + errorMessage + "; payload:" + payload + ")";
}
}
@@ -1,63 +1,75 @@
package io.swagger.common {
public class SwaggerApi extends EventDispatcher {
package io.swagger.common
{
import io.swagger.common.ApiUserCredentials;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import mx.utils.UIDUtil;
public class SwaggerApi extends EventDispatcher
{
protected var _apiUsageCredentials:ApiUserCredentials;
protected var _apiEventNotifier:EventDispatcher;
protected var _apiInvoker: ApiInvoker;
protected var _useProxyServer: Boolean = false;
/**
* Method for returning the path value
* For a string value an empty value is returned if the value is null
* @param value
* @return
*/
protected static function toPathValue(value:Object):String {
if (value is Array) {
return arrayToPathValue(value as Array);
}
return value == null ? "" : value.toString();
}
/**
* Method for returning a path value
* For a list of objects a comma separated string is returned
* @param objects
* @return
*/
protected static function arrayToPathValue(objects:Array):String {
var out:String = "";
return objects.join(",");
}
/**
* Constructor for the api client
* @param apiCredentials Wrapper object for tokens and hostName required towards authentication
* @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response
*/
public function SwaggerApi(apiCredentials:ApiUserCredentials, eventDispatcher:EventDispatcher = null) {
super();
_apiUsageCredentials = apiCredentials;
_apiEventNotifier = eventDispatcher;
}
protected var _apiUsageCredentials:ApiUserCredentials;
protected var _apiEventNotifier:EventDispatcher;
protected var _apiInvoker:ApiInvoker;
protected var _useProxyServer:Boolean = false;
public function useProxyServer(value:Boolean, proxyServerUrl:String = null):void {
_useProxyServer = value;
}
protected function getApiInvoker():ApiInvoker {
if (_apiInvoker == null) {
if (_apiEventNotifier == null) {
_apiEventNotifier = this;
}
_apiInvoker = new ApiInvoker(_apiUsageCredentials, _apiEventNotifier, _useProxyServer);
}
return _apiInvoker;
}
protected function getUniqueId():String {
return UIDUtil.createUID();
}
}
/**
* Constructor for the api client
* @param apiCredentials Wrapper object for tokens and hostName required towards authentication
* @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response
*/
public function SwaggerApi(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) {
super();
_apiUsageCredentials = apiCredentials;
_apiEventNotifier = eventDispatcher;
}
public function useProxyServer(value:Boolean, proxyServerUrl: String = null):void {
_useProxyServer = value;
}
protected function getApiInvoker():ApiInvoker {
if(_apiInvoker == null){
if(_apiEventNotifier == null){
_apiEventNotifier = this;
}
_apiInvoker = new ApiInvoker(_apiUsageCredentials, _apiEventNotifier, _useProxyServer);
}
return _apiInvoker;
}
protected function getUniqueId():String {
return UIDUtil.createUID();
}
/**
* Method for returning the path value
* For a string value an empty value is returned if the value is null
* @param value
* @return
*/
protected static function toPathValue(value: Object): String {
if(value is Array){
return arrayToPathValue(value as Array);
}
return value == null ? "" : value.toString();
}
/**
* Method for returning a path value
* For a list of objects a comma separated string is returned
* @param objects
* @return
*/
protected static function arrayToPathValue(objects: Array): String {
var out: String = "";
return objects.join(",");
}
}
}
@@ -1,24 +1,28 @@
package io.swagger.common {
public class XMLWriter {
public function XMLWriter() {
xml = <obj/>;
}
public var xml:XML;
public function reset():void {
xml = new XML();
}
public function addProperty(propertyName:String, propertyValue:String):XML {
var xmlProperty:XML = <new/>
xmlProperty.setName(propertyName);
xmlProperty.appendChild(propertyValue);
xml.appendChild(xmlProperty);
return xmlProperty;
}
public function addAttribute(propertyName:String, attribute:String, attributeValue:String):void {
xml.elements(propertyName)[0].@[attribute] = attributeValue;
}
}
package io.swagger.common
{
public class XMLWriter
{
public var xml:XML;
public function XMLWriter()
{
xml=<obj/>;
}
public function reset():void {
xml=new XML();
}
public function addProperty(propertyName:String, propertyValue:String):XML {
var xmlProperty:XML=<new/>
xmlProperty.setName(propertyName);
xmlProperty.appendChild(propertyValue);
xml.appendChild(xmlProperty);
return xmlProperty;
}
public function addAttribute(propertyName:String, attribute:String, attributeValue:String):void {
xml.elements(propertyName)[0].@[attribute]=attributeValue;
}
}
}
@@ -15,26 +15,26 @@ import flash.utils.Dictionary;
import flash.events.EventDispatcher;
{{#operations}}
public class {{classname}} extends SwaggerApi {
public class {{classname}} extends SwaggerApi {
/**
* Constructor for the {{classname}} api client
* @param apiCredentials Wrapper object for tokens and hostName required towards authentication
* @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response
*/
public function {{classname}}(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) {
super(apiCredentials, eventDispatcher);
super(apiCredentials, eventDispatcher);
}
{{#operation}}
{{#operation}}
public static const event_{{nickname}}: String = "{{nickname}}";
{{/operation}}
{{/operation}}
{{#operation}}
{{#operation}}
/*
* Returns {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}
*/
public function {{nickname}} ({{#allParams}}{{paramName}}: {{{dataType}}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}): String {
/*
* Returns {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}
*/
public function {{nickname}} ({{#allParams}}{{paramName}}: {{{dataType}}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}): String {
// create path and map variables
var path: String = "{{path}}".replace(/{format}/g,"xml"){{#pathParams}}.replace("{" + "{{paramName}}" + "}", getApiInvoker().escapeString({{{paramName}}})){{/pathParams}};
@@ -43,14 +43,14 @@ import flash.events.EventDispatcher;
var headerParams: Dictionary = new Dictionary();
{{#requiredParamCount}}
// verify required params are set
if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
throw new ApiError(400, "missing required params");
// verify required params are set
if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
throw new ApiError(400, "missing required params");
}
{{/requiredParamCount}}
{{#queryParams}}if("null" != String({{paramName}}))
queryParams["{{paramName}}"] = toPathValue({{paramName}});
queryParams["{{paramName}}"] = toPathValue({{paramName}});
{{/queryParams}}
{{#headerParams}}headerParams["{{paramName}}"] = toPathValue({{paramName}});
@@ -66,8 +66,8 @@ import flash.events.EventDispatcher;
token.returnType = {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null {{/returnType}};
return requestId;
}
{{/operation}}
}
{{/operations}}
{{/operation}}
}
{{/operations}}
}
@@ -1,8 +1,8 @@
package com.wordnik.client.model {
public class FacetValue {
public var value:String = null;
public var count:Number = 0;
}
public class FacetValue {
public var value: String = null;
public var count: Number = 0;
}
}
@@ -4,37 +4,37 @@ package {{package}} {
{{/imports}}
{{#models}}
{{#model}}
[XmlRootNode(name="{{classname}}")]
public class {{classname}} {
{{#vars}}
{{#model}}
[XmlRootNode(name="{{classname}}")]
public class {{classname}} {
{{#vars}}
{{#description}}/* {{description}} */
{{/description}}
{{#description}}/* {{description}} */
{{/description}}
{{#isList}}
// This declaration below of _{{name}}_obj_class is to force flash compiler to include this class
private var _{{name}}_obj_class: {{baseType}} = null;
[XmlElementWrapper(name="{{name}}")]
[XmlElements(name="{{nameSingular}}", type="{{baseType}}")]
{{/isList}}
{{#isNotContainer}}[XmlElement(name="{{name}}")]
{{/isNotContainer}}
public var {{name}}: {{{datatype}}} = {{{defaultValue}}};
{{#isList}}
// This declaration below of _{{name}}_obj_class is to force flash compiler to include this class
private var _{{name}}_obj_class: {{baseType}} = null;
[XmlElementWrapper(name="{{name}}")]
[XmlElements(name="{{nameSingular}}", type="{{baseType}}")]
{{/isList}}
{{#isNotContainer}}[XmlElement(name="{{name}}")]
{{/isNotContainer}}
public var {{name}}: {{{datatype}}} = {{{defaultValue}}};
{{/vars}}
{{/vars}}
public function toString(): String {
var str: String = "{{classname}}: ";
{{#vars}}
var str: String = "{{classname}}: ";
{{#vars}}
str += " ({{name}}: " + {{name}} + ")";
{{/vars}}
return str;
{{/vars}}
return str;
}
}
{{/model}}
{{/models}}
}
{{/model}}
{{/models}}
}
@@ -5,19 +5,19 @@ import io.swagger.common.ListWrapper;
{{/imports}}
{{#models}}
{{#model}}
public class {{classname}}List implements ListWrapper {
{{#model}}
public class {{classname}}List implements ListWrapper {
// This declaration below of _{{name}}_obj_class is to force flash compiler to include this class
private var _{{classVarName}}_obj_class: {{package}}.{{classname}} = null;
[XmlElements(name="{{classVarName}}", type="{{package}}.{{classname}}")]
public var {{classVarName}}: Array = new Array();
public function getList(): Array{
return {{classVarName}};
return {{classVarName}};
}
}
{{/model}}
{{/models}}
}
{{/model}}
{{/models}}
}