Make my AS3 code go fetch information on a website that I don't own - actionscript-3

There is this website : http://www.swellmap.co.nz/ and I'd like to make my AS3 code go fetch some infos and displays it flash.
Is it possible if I don't own the website ?
Exemple :
I want to display these infos in my AS3 code. Is this possible ? How can I do ?
Thx for your help,
EDIT
Thx to the full answer of VC.One I've managed to paste infos in a String.
Here's what I did :
var myString:String;
var request:URLRequest = new URLRequest("http://www.swellmap.co.nz/ajr.php?r=plugin&a=Surfing&s=Anse%20Vata&country=nz&swellmap=1&country=ncd&swellmap=1&_=1460963404274");
var loader:URLLoader = new URLLoader();
loader.load(request);
loader.addEventListener(Event.COMPLETE,weatherLoaded);
function weatherLoaded(e:Event):void{
myString = e.target.data;
trace(myString); //output is {"tides":"High: 05:40 am (1.32 m); Low: 12:10 pm (0.57 m); High: 06:10 pm (1.19 m); ","seatemp":"27°C","forecastdate":"17h","rating":"<img src='http:\/\/www.swellmap.co.nz\/style\/img\/weathericons\/1r.png' alt='Poor conditions' title='Poor conditions' \/>","rating_class":"<span class='badge badge-important' alt='Poor conditions' title='Poor conditions'>1<\/span>","summary":"<img class='wx-summary' src='http:\/\/www.swellmap.co.nz\/style\/img\/weathericons\/suncloud.png' title='Sunny with some cloud' \/>","title":"Anse Vata","smaplink":"http:\/\/www.swellmap.co.nz\/surfing\/new-caledonia\/anse-vata","vars":{"hs_sw":{"value":"0.4","title":"Swell","unit":"m"},"hs":{"value":"0.6","title":"Wave","unit":"m"},"wface":{"value":"0.8","title":"Set face","unit":"m"},"tp":{"value":"13","title":"Period","unit":"s"},"dpm":{"value":"S","title":"Swell dir","unit":"°"},"windma":{"value":"E 12","title":"Wind","unit":"kts"},"gstma":{"value":"16","title":"Gusts","unit":"kts"}}}
}
Now, I didn't quite understand how could I retrieve only some infos (like the swell for exemple).
Is it possible to show me in AS3 code, how could I do that ? (in this exemple, we can see that the swell is "0.4 m # 13 s")
exemple of what I'd like to do :
function(searchTheSwell){
var swell_AnseVata;
swell_AnseVata =.... ?
info_txt.text = swell_AnseVata;
}

If you use the Developer Tools of your browser then you'll see that there's a PHP file being accessed to get the information. It starts http://www.swellmap.co.nz/ajr.php?r= and you need to find what it says for you. Now to view the contents just remove the part of the URL with &callback=XYZ where XYZ will be whatever the link has..
1)
Here's an example of how to get data for a location :
http://www.swellmap.co.nz/ajr.php?r=plugin&a=Surfing&s=ZZZZZ&country=nz&swellmap=1&country=YYY&swellmap=1&_=1460950764514
Replace &s=ZZZZZ with name of location, so if I want Anse Vata it becomes &s=Anse%20Vata and La Nera becomes &s=La%20Nera. So use %20 for any spaces in location name. Replace &country=YYY with example &country=fra.
2)
To get the JSON data for Anse Vata, declare your new String variable to later hold the JSON text and then just use URLStream in AS3 to load the link (open in browser tab to check contents) : http://www.swellmap.co.nz/ajr.php?r=plugin&a=Surfing&s=Anse%20Vata&country=nz&swellmap=1&country=ncd&swellmap=1&_=1460963404274
In the Event Complete listener function of URLStream you just use (example) myString = e.target.data;. Then use a JSON parser on your myString or do it manually yourself using String functions (like indexOf to word search).
3) If you opened the above link in an new tab you'll see the JSON entries you need to parse.
Swell : "hs_sw":{"value":"0.4","title":"Swell","unit":"m"} and for
extracting the # 13 s period use :
"tp":{"value":"13","title":"Period","unit":"s"}
Wind : "windma":{"value":"E 12","title":"Wind","unit":"kts"}
Icon : "summary":"<img class='wx-summary'
src='http:\/\/www.swellmap.co.nz\/style\/img\/weathericons\/suncloud.png'
You'll have to clean up the icon links so it becomes for example :
http://www.swellmap.co.nz/style/img/weathericons/suncloud.png
EDIT :
The code below extracts the expected information from the JSON string. Just replace &s= with any other location (eg: &s=Ilot%20Tenia) and it extracts the Swell, Wind and Icon URL entries...
var myURL : String = "http://www.swellmap.co.nz/ajr.php?r=plugin&a=Surfing&s=Anse%20Vata&country=nz&swellmap=1&country=ncd&swellmap=1&_=1460963404274";
var URL_Req : URLRequest = new URLRequest( myURL );
var URL_load:URLLoader = new URLLoader();
URL_load.addEventListener(Event.COMPLETE, completeHandler);
try { URL_load.load( URL_Req ); }
catch (error:Error)
{ trace("Could not load - Please check URL is correct : " + error.message); }
var idx_start : int = 0; var idx_end : int = 0;
var str_Swell : String = "";
var str_Swell_Period : String = "";
var str_Swell_Dir : String = "";
var str_Wind : String = ""; var url_Icon : String = "";
function completeHandler(e : Event):void
{
//var myData : Object = JSON.parse(e.target.data);
//for each (var s:* in myData) { trace("key:",s,"value:",myData[s]); }
var myString : String = String(e.target.data);
//trace ( "myString : " + myString);
//# Get Swell
idx_start = myString.indexOf("\"hs_sw\":" , 0 );
idx_end = myString.indexOf("," , idx_start + 1 );
str_Swell = myString.substring(idx_start + 18, idx_end-1);
str_Swell = str_Swell + " m";
//trace ("Swell : " + str_Swell );
//# Get Direction (for Swell)
idx_start = myString.indexOf("\"dpm\":" , 0 );
idx_end = myString.indexOf("," , idx_start + 1 );
str_Swell_Dir = myString.substring(idx_start + 16, idx_end-1);
//trace ("Swell dir : " + str_Swell_Dir );
//# Get time Period (for Swell)
idx_start = myString.indexOf("\"tp\":" , 0 );
idx_end = myString.indexOf("," , idx_start + 1 );
str_Swell_Period = myString.substring(idx_start + 15, idx_end-1);
str_Swell_Period = " # " + str_Swell_Period + " s";
//trace ("Period : " + string_Period );
//# Join Swell Direction, Size & Period entries into one sentence
str_Swell = str_Swell_Dir + " " + str_Swell + str_Swell_Period;
trace ("Swell : " + str_Swell );
//# Get Wind
idx_start = myString.indexOf("\"windma\":" , 0 );
idx_end = myString.indexOf("," , idx_start + 1 );
str_Wind = myString.substring(idx_start + 19, idx_end-1);
str_Wind = str_Wind + " kts";
trace ("Wind : " + str_Wind );
//# get Image URL
idx_start = myString.indexOf("\'wx-summary\'" , 0 );
idx_end = myString.indexOf("'" , idx_start + 18 );
url_Icon = myString.substring(idx_start + 18, idx_end);
url_Icon = url_Icon.replace(/\\/g, "");
trace ("URL : " + url_Icon );
//# load image using : new URLRequest (url_Icon);
}

Related

Firebase "MD5" & BloddyCrytpo's dont match

I'm trying to do a check to see if the user has a local file. If the user does, I get bloodycrypto to make a md5 out of it. Then I compare the two values. One from the firebase file's metadata and the other from the byte array of the file digested. They never match. Does Firebase do something different when trying to generate the md5 of a file I upload?
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA)
trace("Local hash = " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("Network hash = " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
if (byteHash != storageMetaData.md5Hash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
Upon closer inspetion (thanks to Organis) firebase doesn't return a proper MD5. What is it? In my storage consol I don't see an md5 property, so is this autogenerated? The files were uploaded through my rest API based off phantom's guide.
Update: Following Organis' comment about the way Firebase handle's MD5s
var byteHash:ByteArray = new ByteArray();
byteHash.writeUTFBytes(MD5.hashBytes(fileBA));
var byteHashWithLength:ByteArray = new ByteArray();
byteHashWithLength.writeUTF(MD5.hashBytes(fileBA));
trace("Bytehash with length = " + Base64.encode(byteHashWithLength)); //ACAyMTMzYTdmYjczYTEzZDQ3ZDkzMTEyY2I1OWQyYTBmMg==
trace("Plain = " + Base64.encode(byteHash)); //OTNiODg1YWRmZTBkYTA4OWNkZjYzNDkwNGZkNTlmNzE=
trace("Storage md5 = " + storageMetaData.md5Hash); //UsoNl5sL1+aLiAhTOTBXyQ==
Trying to take the md5 I get and turn it into base64 results in consistent mismatching results. Is there an argument I am missing or applying incorrectly when I try to decode everything?
...So I would do something like
var storageHash:String = Base64.decode(storageMetaData.md5Hash).toString();
to follow your example right?
Try this code below to get your storageMetaData.md5Hash correctly decoded from Base64 :
Let me know result of trace("storage hash : " + storageHash); to check if you're getting an (expected) sequence of 32 hex values.
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA); //Local hash
var ba_storageHash:ByteArray = new ByteArray();
ba_storageHash = Base64.decode(storageMetaData.md5Hash); //update ByteArray
var storageHash:String = bytesToHexString(ba_storageHash); //Hex values of bytes shown as String
trace("Network hash : " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
trace("Local hash : " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("storage hash : " + storageHash); //what is result??
if (byteHash != storageHash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
// # Byte values (Hex) shown as (returned) String type
private function bytesToHexString(input:ByteArray) : String
{
var strOut:String = ""; var strRead:String = "";
input.position = 0;
var intBASize:uint = input.length;
for (var i:int = 0; i < intBASize; i++)
{
strRead = input.readUnsignedByte().toString(16);
if(strRead.length < 2) { strRead = "0" + strRead; } //# do padding
strOut += strRead ;
}
return strOut.toLowerCase(); //strOut.toUpperCase();
}

How to take a specific info from a string in json format?

I've got this AS3 code :
var myString:String;
var request:URLRequest = new URLRequest("http://www.swellmap.co.nz/ajr.php?r=plugin&a=Surfing&s=Anse%20Vata&country=nz&swellmap=1&country=ncd&swellmap=1&_=1460963404274");
var loader:URLLoader = new URLLoader();
loader.load(request);
loader.addEventListener(Event.COMPLETE,weatherLoaded);
function weatherLoaded(e:Event):void{
myString = e.target.data;
trace(myString); //output is {"tides":"High: 05:40 am (1.32 m); Low: 12:10 pm (0.57 m); High: 06:10 pm (1.19 m); ","seatemp":"27°C","forecastdate":"17h","rating":"<img src='http:\/\/www.swellmap.co.nz\/style\/img\/weathericons\/1r.png' alt='Poor conditions' title='Poor conditions' \/>","rating_class":"<span class='badge badge-important' alt='Poor conditions' title='Poor conditions'>1<\/span>","summary":"<img class='wx-summary' src='http:\/\/www.swellmap.co.nz\/style\/img\/weathericons\/suncloud.png' title='Sunny with some cloud' \/>","title":"Anse Vata","smaplink":"http:\/\/www.swellmap.co.nz\/surfing\/new-caledonia\/anse-vata","vars":{"hs_sw":{"value":"0.4","title":"Swell","unit":"m"},"hs":{"value":"0.6","title":"Wave","unit":"m"},"wface":{"value":"0.8","title":"Set face","unit":"m"},"tp":{"value":"13","title":"Period","unit":"s"},"dpm":{"value":"S","title":"Swell dir","unit":"°"},"windma":{"value":"E 12","title":"Wind","unit":"kts"},"gstma":{"value":"16","title":"Gusts","unit":"kts"}}}
var myData : Object = JSON.parse(e.target.data);
for each (var s:* in myData) { trace("key:",s,"value:",myData[s]); }
trace(myData); }
My String is containing lots of infos.
How could I take specifics informations ?
Exemple:
If I want to take the swell (in this example, the swell is : "0.4 m # 13 s"). How could I do that? (the purpose is to displays it in a text box like that :
function(searchTheSwell){
var swell_AnseVata;
swell_AnseVata =.... ?
info_txt.text = swell_AnseVata;
}
Thx
Just set a breakpoint after you parse the data and examine the myData in the debugger - you will see the object structure. Or just trace the whole object structure out:
import mx.utils.ObjectUtil;
trace(ObjectUtil.toString(myData));
In your case you'd need to put your string together out of the vars in your object:
var hs_sw:Object = myData.vars.hs_sw;
var tp:Object = myData.vars.tp;
trace(hs_sw.value + " " + hs_sw.unit + " # " + tp.value + " " + tp.unit);

Dictionary uses values as keys

--Or so it seems. Confused about the AS3 Dictionary. I have this:
map = new Dictionary();
map["someKey"] = 1;
And I try to print it out in two ways:
for each( var key:Object in d ) {
trace( key + ": " + d[key] );
}
This prints 1: undefined
for each( var o:Object in d ) {
var key:String = o.toString();
var val:int = d[o];
trace( key + ": " + val );
}
This prints 1: null
I would expect that it comes out as someyKey: 1. Am I just printing it out wrong?
As shown in Efficient looping through AS3 dictionary you loop though it the wrong way. You should be doing:
for ( var key:Object in d ) {
trace( key + ": " + d[key] );
}

Sending Json Form from Flash AS3

i am having one form accepting json post in Asp.net which i need to call from Flash As3...
i am using below code to do that. I have seen some post in which they say its working fine.
But i am encountering below Error
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Here is my code.
var messages:Array = new Array ();
messages.push({"From":fromemailTxt.text,"To": ToemailTxt.text,"Body": BodyText.text,"Subject":SubjectText.text});
var JsonObj:String = JSON.encode(messages);
trace(JsonObj);
var variables:URLVariables=new URLVariables(JsonObj);
RequestURL= srvStringURL;
var JSONLoader:URLLoader = new URLLoader();
JSONLoader.dataFormat=URLLoaderDataFormat.TEXT;
JSONLoader.addEventListener(IOErrorEvent.IO_ERROR, GetBookmarkURLError, false, 0, true);
JSONLoader.addEventListener(Event.COMPLETE, parseBookmarkURLResult, false, 0, true);
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var request:URLRequest = new URLRequest(RequestURL);
request.requestHeaders.push(hdr);
request.data=variables;
request.method = URLRequestMethod.POST;
try
{
JSONLoader.load(request);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred."+error.errorID.toString());
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
catch (error:Error)
{
trace("Unable to load requested document.");
}
Anybody have any idea on this??
Thanks
The error is, because you are passing incorrect string to URLVariables constructor. Do not use URLVariables. Instead pass data as string: request.data=JsonObj;
Below is the code I am using to consume REST Web service and pass json parameter to service it shows. Error #2032: Stream Error.
Andy idea what is going wrong
var ldr:URLLoader = new URLLoader();
ldr.dataFormat = URLLoaderDataFormat.TEXT;
var strData:String = "{\"gparam\": [ {\"productid\": \"" + productId + "\"},{\"message\": \"" + mesage + "\"},{\"googleappid\": \"" + googleappid + "\"},{\"senderid\": \"" + senderid + "\"},{\"appname\": \"" + appName + "\"},{\"userid\": \"" + userId + "\"},{\"receiverid\": \"" + receiverId + "\"} ]}";
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var req:URLRequest = new URLRequest("http://localhost/AndroidGCM/GCMNotification.svc/SendGCM");
req.requestHeaders.push(hdr);
req.method = URLRequestMethod.POST;
req.data = strData;
trace("data: " + req.data);
ldr.addEventListener(Event.COMPLETE,onComplete);
ldr.addEventListener(IOErrorEvent.IO_ERROR , onError);
ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR ,onSecurityErr);
ldr.load(req);
function onComplete(e:Event):void
{
trace("LOAD COMPLETE: " + ldr.data);
TextField(parMC.getChildByName("txtCheck")).appendText("\n LOAD COMPLETE: " + ldr.data);
}
function onSecurityErr(e:SecurityErrorEvent):void
{
trace("error: " + e.text );
}
function onError(e:IOErrorEvent):void
{
trace("error: " + e.toString());
}

dict[obj] pulling wrong info at 35-36 xml node why?

I'm not sure how to explain this, but why isn't this code pulling the correct image and icon file? It continues to pull the wrong info at the line 35, which makes all other data one node behind. Even when I delete the three locations below, it still gets the xml wrong. Why would it be doing this?
I verified the xml data and made sure all the files were in the correct folder.
For example, this is a result from a trace:
pm#: 35 xmlnodename: Causey's Pharmacy iconFL: http://www.mysite.com/folder1/folder2/media/marker.png imgFL: http://www.mysite.com/folder1/folder2/media/century21_img.swf
pm#: 36 xmlnodename: Century 21 Property Shoppe iconFL: http://www.mysite.com/folder1/folder2/media/century21_icon.gif imgFL: http://www.mysite.com/folder1/folder2/media/century21_img.swf
pm#: 37 xmlnodename: Century 21 Property Shoppe iconFL: http://www.mysite.com/folder1/folder2/media/century21_icon.gif imgFL: http://www.mysite.com/folder1/folder2/media/type1.swf
Here is my xml at lines 34-36
<location>
<name>Bobby&apos;s Pharmacy</name>
<street>123 Steet St.</street>
<city>SomeCity</city>
<state>ZZ</state>
<zip>12345</zip>
<lat>45.7520099</lat>
<long>-80.0816701</long>
<iconFile>marker.png</iconFile>
<imageFile>type1.swf</imageFile>
<motion>no</motion>
<featured>no</featured>
<category>none</category>
</location>
<location>
<name>Century 21 Property Shoppe</name>
<street>456 SomeOther St</street>
<city>SomeCity</city>
<state>ZZ</state>
<zip>12345</zip>
<lat>45.5683603</lat>
<long>-80.483271</long>
<iconFile>century21_icon.gif</iconFile>
<imageFile>century21_img.swf</imageFile>
<motion>no</motion>
<featured>yes</featured>
<category>none</category>
</location>
<location>
<name>Century 21 Property Shoppe</name>
<street>none</street>
<city>none</city>
<state>none</state>
<zip>none</zip>
<lat>45.4949689</lat>
<long>-80.6597955</long>
<iconFile>century21_icon.gif</iconFile>
<imageFile>century21_img.swf</imageFile>
<motion>no</motion>
<featured>yes</featured>
<category>none</category>
</location>
Here is my flex code:
private var mediaLoc:String = "http://www.mysite.com/folder1/folder2/media/";
public function addMarkers():void
{
var dict:Object = new Object();
var i:Number = 0;
var e:Number = locXML..location.length()+1;
trace("add markers: " + locXML..location.length());
for(i;i<e;i++){
if (locXML.location.name[i.toString()]== "mapLogo"){
trace(i + " logo");
//get lat and long from xml
dict["locPointMarker_lat" + i.toString()] = locXML.location.lat[i.toString()];
dict["locPointMarker_long" + i.toString()] = locXML.location.long[i.toString()];
//get iconfile name from xml and append it to mediaLoc--filepath
dict["iconFileLink" + i.toString()] = mediaLoc + locXML.location.iconFile[i.toString()];
//create a new url request using the dict["iconFileLink" + i.toString()] filepath
dict["iconFileReq" + i.toString()] = new URLRequest(dict["iconFileLink"+i.toString()]);
//create a new pointmarker for the map
dict["locPointMarker"+i.toString()] = new PointMarker();
//apply buttonmode and handcursor to the new pointmarker
dict["locPointMarker"+i.toString()].buttonMode = dict["locPointMarker"+i.toString()].useHandCursor = true;
//create a loader to load the icon file
dict["icon"+i.toString()] = new Loader();
//load the icon file
dict["icon"+i.toString()].load(dict["iconFileReq"+i.toString()], context);
//put the marker on the map
_map.putMarker(new Location(locXML.location.lat[i.toString()], locXML.location.long[i.toString()]), dict["locPointMarker"+i.toString()]);
trace("pm#: " + i + " xmlnodename: " + locXML.location.name[i.toString()] + " iconFL: " + dict["iconFileLink" + i.toString()] + " imgFL: " + dict["imageFileLink" + i.toString()]);
dict["locPointMarker"+i.toString()].mouseChildren=false;
}else{
//the following else does the same thing except it also adds the image file
dict["locPointMarker_lat" + i.toString()] = locXML.location.lat[i.toString()];
dict["locPointMarker_long" + i.toString()] = locXML.location.long[i.toString()];
dict["iconFileLink" + i.toString()] = mediaLoc + locXML.location.iconFile[i.toString()];
dict["iconFileReq" + i.toString()] = new URLRequest(dict["iconFileLink"+i.toString()]);
dict["locPointMarker"+i.toString()] = new PointMarker();
dict["locPointMarker"+i.toString()].buttonMode = dict["locPointMarker"+i.toString()].useHandCursor = true;
dict["icon"+i.toString()] = new Loader();
dict["icon"+i.toString()].load(dict["iconFileReq"+i.toString()], context);
dict["icon"+i.toString()].x = -iconHeight/2;
dict["icon"+i.toString()].y = -iconWidth/2;
_map.putMarker(new Location(locXML.location.lat[i.toString()], locXML.location.long[i.toString()]), dict["locPointMarker"+i.toString()]);
trace("pm#: " + i + " xmlnodename: " + locXML.location.name[i.toString()] + " iconFL: " + dict["iconFileLink" + i.toString()] + " imgFL: " + dict["imageFileLink" + i.toString()]);
dict["locPointMarker"+i.toString()].mouseChildren=false;
}
}
}
the object class stores the value hashed by the toString() property of the key. So if two key renders as the same string the values will collide.
Use Dictionary instead.
here some more info: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Dictionary.html