could not be able to create http service programmatically in flex - flex4.5

I'm trying to create HttpService through Action Script and I want to convert this mxml code to my Action Script
mxml code code is here:
<s:HTTPService id="weatherService"
url="{BASE_URL}"
resultFormat="object"
result="weatherService_resultHandler(event)"
fault="weatherService_faultHandler(event)"
showBusyCursor="true">
<s:request xmlns="">
<q>{cityName.text.toString()}</q>
<format>{FORMAT}</format>
<num_of_days>{NUMBER_OF_DAYS}</num_of_days>
<key>{API_KEY}</key>
</s:request>
</s:HTTPService>
How to convert this in actionscript?

This might help you and please note here the following code not using binding
import mx.rpc.http.HTTPService;
private function callService():void
{
var requestObj:Object = {};
requestObj.q = cityName.text.toString();
requestObj.format = FORMAT;
requestObj.num_of_days = cNUMBER_OF_DAYS;
requestObj.key = API_KEY;
var weatherService:HTTPService = new HTTPService();
weatherService.url = BASE_URL;
weatherService.resultFormat = "object";
weatherService.showBusyCursor = true;
weatherService.request = requestObj;
weatherService.addEventListener(ResultEvent.RESULT , weatherService_resultHandler);
weatherService.addEventListener(FaultEvent.FAULT, weatherService_faultHandler);
weatherService.send();
}
protected function weatherService_resultHandler(event:ResultEvent):void
{
trace("got result");
}
protected function weatherService_faultHandler(event:FaultEvent):void
{
trace("got fault");
}

Related

Mirth HTTP POST request with Parameters using Javascript

The following code by #Nick Rupley works well, but, I need also to pass parameters as POST. How do we pass POST parameters?
from java.net.URL
var url = new java.net.URL('http://localhost/myphpscript.php');
var conn = url.openConnection();
var is = conn.getInputStream();
try {
var result = org.apache.commons.io.IOUtils.toString(is, 'UTF-8');
} finally {
is.close();
}
2 Parameters to pass: firstname="John" and lastname="Smith"
Thanks
This will POST with MIME type application/x-www-form-urlencoded. It is using apache httpclient, which is already included with mirth, as it is used internally by the HTTP Sender connector, as well as some other functionality. Other solutions may require you to download jars and add library resources.
Closer is part of Google Guava, which is also already included with mirth.
Check comments where Rhino javascript allows for simplified code compared to direct Java conversion.
It wouldn't be a bad idea to wrap all of this up in a code template function.
var result;
// Using block level Java class imports
with (JavaImporter(
org.apache.commons.io.IOUtils,
org.apache.http.client.methods.HttpPost,
org.apache.http.client.entity.UrlEncodedFormEntity,
org.apache.http.impl.client.HttpClients,
org.apache.http.message.BasicNameValuePair,
com.google.common.io.Closer))
{
var closer = Closer.create();
try {
var httpclient = closer.register(HttpClients.createDefault());
var httpPost = new HttpPost('http://localhost:9919/myphpscript.php');
// javascript array as java List
var postParameters = [
new BasicNameValuePair("firstname", "John"),
new BasicNameValuePair("lastname", "Smith")
];
// Rhino JavaBean access to set property
// Same as httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
httpPost.entity = new UrlEncodedFormEntity(postParameters, "UTF-8");
var response = closer.register(httpclient.execute(httpPost));
// Rhino JavaBean access to get properties
// Same as var is = response.getEntity().getContent();
var is = closer.register(response.entity.content);
result = IOUtils.toString(is, 'UTF-8');
} finally {
closer.close();
}
}
logger.info(result);
Following is a complete working HTTP POST request solution tested in Mirth 3.9.1
importPackage(Packages.org.apache.http.client);
importPackage(Packages.org.apache.http.client.methods);
importPackage(Packages.org.apache.http.impl.client);
importPackage(Packages.org.apache.http.message);
importPackage(Packages.org.apache.http.client.entity);
importPackage(Packages.org.apache.http.entity);
importPackage(Packages.org.apache.http.util);
var httpclient = HttpClients.createDefault();
var httpPost = new HttpPost("http://localhost/test/");
var httpGet = new HttpGet("http://httpbin.org/get");
// FIll in each of the fields below by entering your values between the ""'s
var authJSON = {
"userName": "username",
"password": "password",
};
var contentStr =JSON.stringify(authJSON);
//logger.info("JSON String: "+contentStr);
httpPost.setEntity(new StringEntity(contentStr,ContentType.APPLICATION_JSON,"UTF-8"));
httpPost.setHeader('Content-Type', 'application/json');
httpPost.setHeader("Accept", "application/json");
// Execute the HTTP POST
var resp;
try {
// Get the response
resp = httpclient.execute(httpPost);
var statusCode = resp.getStatusLine().getStatusCode();
var entity = resp.getEntity();
var responseString = EntityUtils.toString(entity, "UTF-8");
var authHeader = resp.getFirstHeader("Authorization");
// logger.info("Key : " + authHeader.getName()+" ,Value : " + authHeader.getValue());
// Save off the response and status code to Channel Maps for any potential troubleshooting
channelMap.put("responseString", responseString);
channelMap.put("statusCode", statusCode);
// Parse the JSON response
var responseJson = JSON.parse(responseString);
// If an error is returned, manually throw an exception
// Else save the token to a channel map for use later in the processing
if (statusCode >= 300) {
throw(responseString);
} else {
logger.info("Token: "+ authHeader.getValue());
channelMap.put("token", authHeader.getValue());
}
} catch (err) {
logger.debug(err)
throw(err);
} finally {
resp.close();
}
This linke + above answers helped me to come up with a solution
https://help.datica.com/hc/en-us/articles/115005322946-Advanced-Mirth-Functionality
There are plenty of libraries that can help you with URI building in Java. You can find them below. But if you want to stay in Javascript just add your parameters manually than create it.
function addParam(uri, appendQuery) {
if (appendQuery != null) {
uri += "?" + appendQuery;
}
return uri;
}
var newUri = addParam('http://localhost/myphpscript.php', 'firstname="John"');
var url = new java.net.URL(newUri);
Java EE 7
import javax.ws.rs.core.UriBuilder;
...
return UriBuilder.fromUri(url).queryParam(key, value).build();
org.apache.httpcomponents:httpclient:4.5.2
import org.apache.http.client.utils.URIBuilder;
...
return new URIBuilder(url).addParameter(key, value).build();
org.springframework:spring-web:4.2.5.RELEASE
import org.springframework.web.util.UriComponentsBuilder;
...
return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();
There are multiple ways to provide http client connection with java. Since your question is specific to java.net.URL I will stick to that.
Basically you can pass parameters as POST, GET, PUT, DELETE using .setRequestMethod this will be used along with new java.net.URL(ur-destination-url).openConnection();
Here is the complete code I've using javascript in Mirth using the same java.net.URL use this it will be helpful. It worked well for me.
do {
try {
// Assuming your writing this in the destination Javascript writer
var data = connectorMessage.getEncodedData();
//Destination URL
destURL = “https://Your-api-that-needs-to-be-connected.com”;
//URL
var url = new java.net.URL(destURL);
var conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
enter code here
conn.setRequestProperty (“Authorization”, globalMap.get(‘UniversalToken’));
conn.setRequestMethod(“DELETE”); // this can be post or put or get or patch
conn.setRequestProperty(“Content-length”, data.length());
conn.setRequestProperty(“Content-type”, “application/json”);
var outStream = conn.getOutputStream();
var outWriter = new java.io.OutputStreamWriter(outStream);
outWriter.write(data);
outWriter.close();
// Get response Code (200, 500 etc.)
var respCode = conn.getResponseCode();
if (respCode != 200) {
// Write error to error folder
var stringData = response.toString() + “\n”;
FileUtil.write(“C:/Outbox/Errors/” + $(“originalFilename”) + “.ERROR_RESPONSE”, false, stringData);
// Return Error to Mirth to move the file to the error folder
return ERROR;
}
errorCond = “false”;
break;
}
catch(err) {
channelMap.put(“RESPONSE”, err);
responseMap.put(“WEBSVC”, ResponseFactory.getErrorResponse(err))
throw(err);
// Can return ERROR, QUEUED, SENT
// This re-queues the message on a fatal error. I”m doing this since any fatal message may be
// caused by HTTPS connect errors etc. The message will be re-queued
return QUEUED; // Re-queue the message
java.lang.Thread.sleep(6000); // 6 seconds * 10
errorCond = “true”;
}
}
while (errorCond == “true”);

ActionScript 3.0 and 'TypeError: Error#1034: type Coercion failed'

I'm currently following a tutorial, and I watched it like 6-7 times over, but for some reason I keep getting:
TypeError: Error#1034: type Coercion failed.
I'm trying to make a matching game for a school assignment, and I currently have this:
package {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.events.MouseEvent;
public class MatchingGame extends MovieClip {
var fClip:Logo
var sClip:Logo
var myTimer:Timer
var frames:Array = new Array(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10);
public function MatchingGame() {
// Constructor code
for(var i:Number=1; i<=5; i++) {
for(var j:Number=1; j<=4; j++) {
var myLogo:Logo = new Logo();
var index = Math.floor(Math.random() * frames.length)
myLogo.frameNo = frames[index];
frames.splice(index, 1);
addChild(myLogo);
myLogo.x = j*100;
myLogo.y = i*100;
myLogo.gotoAndStop(11);
myLogo.addEventListener(MouseEvent.CLICK, openLogo);
}
}
}
private function openLogo(e:MouseEvent) {
var clickObj:Logo = Logo(e.target);
if(fClip == null) {
fClip = clickObj;
fClip.gotoAndStop(fClip.frameNo);
}
else if(sClip == null && fClip != clickObj) {
sClip = clickObj;
sClip.gotoAndStop(sClip.frameNo);
if(fClip.frameNo == sClip.frameNo) {
myTimer = new Timer(1000, 1);
myTimer.start();
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, removeLogos);
}
else {
myTimer = new Timer(1000, 1);
myTimer.start();
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, resetLogos);
}
}
}
private function removeLogos(e:TimerEvent) {
removeChild(fClip);
removeChild(sClip);
myTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, removeLogos);
fClip = null;
sClip = null;
}
private function resetLogos(e:TimerEvent) {
fClip.gotoAndStop(11);
sClip.gotoAndStop(11);
myTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, resetLogos);
fClip = null;
sClip = null;
}
}
}
The error pops up at line 38 and when I try debugging it tell me that clickObj is undefined.
How can I fix this problem?
This is the entire error message:
TypeError: Error #1034: Type Coercion failed: cannot convert flash.display::MovieClip#a3e4a61 to Logo.
at MatchingGame/openLogo()[H:\Informatica\Matching game\MatchingGame.as:39]
It looks like the cast from MovieClip to Logo isn't working.
put a trace before that line to see what event.target is.
Depending on the display list structure and event bubbling, you might be getting a different element that what you expect.
Try var clickObj:Logo = Logo(e.currentTarget); as a quick test.
Be sure to go through Trevor McCauley's article to get a better understanding of event bubbling.

HiQPdf Evaluation tag added when printing

I have a c# dll that uses HiQPdf to print a PDF from file. The issue is the printed PDF has a string added to the top left saying "HiQPdf Evaluation". The marigins are also greatly increased making the image smaller.
When I open the pdf and print from there it is fine. I couldn't find anything on the string being added so hoping someone here might have some insight :)
code:
public void PrintFromFile(string fileName, System.Drawing.Printing.PrinterSettings printerSettings)
{
var imagePrinter = new PdfPrinter();
imagePrinter.PrinterSettings.Copies = printerSettings.Copies;
imagePrinter.PrinterSettings.Duplex = printerSettings.Duplex;
imagePrinter.PrinterSettings.FromPage = printerSettings.FromPage;
imagePrinter.PrinterSettings.MaximumPage = printerSettings.MaximumPage;
imagePrinter.PrinterSettings.MinimumPage = printerSettings.MinimumPage;
imagePrinter.PrinterSettings.PrinterName = printerSettings.PrinterName;
imagePrinter.PrinterSettings.PrintFileName = printerSettings.PrintFileName;
imagePrinter.PrinterSettings.PrintRange = printerSettings.PrintRange;
imagePrinter.PrinterSettings.PrintToFile = printerSettings.PrintToFile;
imagePrinter.PrinterSettings.ToPage = printerSettings.ToPage;
imagePrinter.PrinterSettings.Collate = printerSettings.Collate;
var pdf = new MemoryStream(System.IO.File.ReadAllBytes("V:\\AccW2\\" + fileName));
pdf.Position = 0;
imagePrinter.PrintPdf(pdf);
}
If you have an HtmlToPdf element in you PrintPdf function you should set your SerialNumber
private void PrintPdf(string htmlbody, string pdfname)
{
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// set a demo serial number
htmlToPdfConverter.SerialNumber = "-- HiQPdf Serial Number --";
}

Setting up Touch Events on Materials in Papervision

I am working with papervision and would like to setup a TouchEvent on each side of a Cube. How would i go about it ? Right now i am setting up the events on the movieclip which i pass to the MovieMaterial class. The MouseEvent is working fine but the TouchEvent doesn't seem to fire.
public function MiniCube(k:int, j:int, i:int)
{
var matList:Object = {all:new ColorMaterial(0xff0000,1,true)};
matList.back = createColorMC(0x000000,'back');
matList.front = createColorMC(0x000000,'front');
matList.top = createColorMC(0x000000,'top');
matList.bottom = createColorMC(0x000000,'bottom');
matList.right = createColorMC(0x000000,'right');
matList.left = createColorMC(0x000000,'left');
cube = new Cube(new MaterialsList(matList),10,10,10);
}
private function createColorMC(color:uint, name:String):MovieMaterial
{
var ClassReference:Class = getDefinitionByName(iconArr[Math.floor(Math.random() * iconArr.length)]) as Class;
var mc=new ClassReference();
mc.name = name;
//MOUSE EVENT WORKS
mc.addEventListener(MouseEvent.MOUSE_DOWN, onMovieMatClicked);
//TOUCH EVENT DOESNT
mc.addEventListener(TouchEvent.TOUCH_BEGIN, onMovieMatClicked);
var movieMat:MovieMaterial = new MovieMaterial(mc,true,true);
movieMat.interactive = true;
movieMat.smooth = true;
movieMat.animated = true;
return movieMat;
}
Did you enable multitouch on your application? The following line goes in the constructor of your main application class:
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
or
Multitouch.inputMode = MultitouchInputMode.GESTURE;

How do I create an anonymous JavaScript function/callback with Dart's JS interop?

I am using Dart and its JS interop. I need to convert the following JavaScript code to Dart:
ID3.loadTags("filename.mp3", function() {
var tags = ID3.getAllTags("filename.mp3");
if (tags.artist)
artist.textContent = tags.artist;
if (tags.title)
track.textContent = tags.title;
}, {
dataReader: FileAPIReader(file)
});
Note the anonymous callback as the second parameter to loadTags. How do I create that with Dart and the dart:js library?
The closest I got was creating a named function with:
js.context['loadTagsCallback'] = () {
var tags = ID3.callMethod('getAllTags', ["filename.mp3"]);
var artistTag = tags['artist'];
var titleTag = tags['title'];
if (artistTag != null) {
artist.text = artistTag;
}
if (titleTag != null) {
track.text = titleTag;
}
};
And then using this Dart code:
ID3.callMethod('loadTags', [
"filename.mp3",
js.context['loadTagsCallback'],
new js.JsObject.jsify({'dataReader': id3FileReader})
]);
However, I don't want to create the named function. Any ideas or tips?
Dart closures are automatically converted to JS closures when sent across the border. You can just do this:
ID3.callMethod('loadTags', ["filename.mp3", () {
var tags = ID3.callMethod('getAllTags', ["filename.mp3"]);
var artistTag = tags['artist'];
var titleTag = tags['title'];
if (artistTag != null) {
artist.text = artistTag;
}
if (titleTag != null) {
track.text = titleTag;
}
},
new js.JsObject.jsify({'dataReader': id3FileReader})
]);

Resources