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

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);

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();
}

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

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);
}

two identical strings compare not equal

something is going wrong:
array dataFromFile is initialized with following code(and indeed when I trace it does output correct file content)"
var dataFromFile:Array;
var dataLoader:URLLoader = new URLLoader();
dataLoader.addEventListener(Event.COMPLETE, onLoaded);
dataLoader.load(new URLRequest("Data.txt"));
}
function onLoaded(e:Event):void
{
dataFromFile = e.target.data.split(/\n/);
trace(dataFromFile);
}
var dataFromFile:Array;
var sectionToLook:String = "[GAME]";
trace(dataFromFile[i1].toLowerCase());
trace(sectionToLook.toLowerCase());
trace("are equal:" + (dataFromFile[i1].toLowerCase() == sectionToLook.toLowerCase()));
trace("the type of data is:" + typeof(dataFromFile[i1]));
trace("the type of sectionData is:" + typeof(sectionToLook));
And the output I'm getting:
[game]
[game]
are equal:false
the type of data is:string
the type of sectionData is:string
How on earth is this possible that two identical strings compare as not equal?

Multipart/form-data Flex HTTPService uploading a file

I am new to Flex and also new to writing a client for a web service.
My question is more about Flex (Flash Builder 4.5) APIs, what APIs to use.
I want to access a web service, and create a Flex / AIRwrapper for it,
which anyone can use.
Here is the spec of webservice.
I have to do a post on POST https://build.phonegap.com/api/v1/apps
content type has to be "multipart/form-data"
JSON bodies of requests are expected to have the name 'data' and will be something like this:
data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}
include a zip file in the multipart body of your post, with the parameter name 'file'.
I want to make a 'multipart/form-data' Post and send one string and one zip file.
My first question to self was if I send both string + binary data in the body,
how will server understand where string end and where zip file starts?
Then I read how text + binary data can be sent through "multipart/form-data" post request. There has to be some boundaries.
After this I read and example in flex and tried following it.
http://codeio.wordpress.com/2010/04/03/5-minutes-on-adobe-flex-mimic-file-upload-for-in-memory-contents/
but it doesn't seem to be working for me.
public function createNewApp(cb:Function , appFile : File):void
{
var service:HTTPService = new HTTPService();
service.url = ROOT+"apps";
service.showBusyCursor = true;
service.addEventListener(ResultEvent.RESULT, function(e:ResultEvent):void {
//translate JSON
trace(e.result);
var result:String = e.result.toString();
var data:Object = JSON.parse(result);
cb(data.link);
});
service.addEventListener(FaultEvent.FAULT, defaultFaultHandler); //todo : allow user to add his own as well
authAndUploadNewApp(service,appFile);
}
private function authAndUploadNewApp(service:HTTPService,appFile : File):void {
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(username + ":"+password);
service.headers = {Accept:"application/json", Authorization:"Basic " + encoder.toString()};
service.method ="POST";
var boundary:String = UIDUtil.createUID();
service.contentType = "multipart/form-data; boundary=—————————" + boundary;
var stream:FileStream = new FileStream();
stream.open(appFile, FileMode.READ);
var binaryData:ByteArray = new ByteArray();
var fileData : String = new String();
stream.readBytes(binaryData);
stream.close();
fileData = binaryData.readUTFBytes(binaryData.bytesAvailable); // I think this is where I have problem.... how do
//how do i converrt this bytearray/stream of data to string and send it in my post request's body - i guess if this step work rest should work..
var params: String = new String();
var content:String = "—————————" + boundary + "nr";
content += 'Content-Disposition: form-data; name="data";' + '{"title":"ELS test app 2","package":"com.elsapp.captivate","version":"12.3.09","create_method":"file"}' + "nr";
content += "—————————" + boundary + "nr";
content += 'Content-Disposition: form-data; name="file";' + fileData + "nr";
content += "—————————–" + boundary + "–nr";
service.request = content;
service.send();
}

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());
}