Flex HttpService authorization to obtain xml feed - actionscript-3

im trying to obtain a xml feed from my cpanel though API. I have tried several methods (see below) to pass the authorization to obtain the xml feed.
In my browser i can get the feed through the following way:
http://user:pass#domain.com:2086/xml-api/listaccts?
The feed example from the server:
<listaccts>
<acct>
<disklimit>2500M</disklimit>
<diskused>56M</diskused>
<domain>domain.com</domain>
<email>dot#domain.com</email>
<ip>xx.xx.xx.xx</ip>
<max_defer_fail_percentage>unlimited</max_defer_fail_percentage>
<max_email_per_hour>unlimited</max_email_per_hour>
<maxaddons>*unknown*</maxaddons>
<maxftp>5</maxftp>
<maxlst>*unknown*</maxlst>
<maxparked>*unknown*</maxparked>
<maxpop>25</maxpop>
<maxsql>1</maxsql>
<maxsub>5</maxsub>
<min_defer_fail_to_trigger_protection>5</min_defer_fail_to_trigger_protection>
<owner>root</owner>
<partition>home</partition>
<plan>Basic</plan>
<shell>/usr/local/cpanel/bin/noshell</shell>
<startdate>13 Feb 17 07:05</startdate>
<suspended>0</suspended>
<suspendreason>not suspended</suspendreason>
<suspendtime/>
<theme>x3</theme>
<unix_startdate>1361109935</unix_startdate>
<user>xxxxxxxx</user>
</acct>
</listaccts>
My Application script:
<s:HTTPService id="clientList" method="GET" resultFormat="e4x"/>
In Scripts:
[Bindable]
private var clientInfo:Object = new Object();
private function clients(event:Event):void{
clientList.url = 'http://' +loginUsername.text
clientList.url += ':' + loginPassword.text
clientList.url += '#' + loginServer.text;
clientList.url += ':2086/xml-api/listaccts?';
clientList.addEventListener("result", clientResult);
clientList.addEventListener("fault", clientFault);
clientList.send();
CursorManager.setBusyCursor();
}
public function clientResult(event:ResultEvent):void {
clientInfo = clientList.lastResult.acct;
CursorManager.removeBusyCursor();
}
public function clientFault(event:FaultEvent):void {
var faultstring:String = event.fault.faultString;
Alert.show("Unable to obtain client list","Error");
CursorManager.removeBusyCursor();
}
What am i doing wrong, i keep getting the error (Unable to obtain client list), i think i could be trying the authentication way i use.

Don't concatenate a string to add your username and password.
Call this as a WebService and use setCredentials.

Related

Google Translate free api assist

I am kind of new to javascript and building websites, I program c# most of the times.
I am trying to build something and I need to use google translate api, the problem that is cost money so I prefer use Free API so I found this.
https://ctrlq.org/code/19909-google-translate-api
so I changed it a bit and tried alone, because I wasn't sure what e type ment.
so this is my code:
function doGet(text) {
var sourceText = text;
var translatedText = LanguageApp.translate('en', 'iw', sourceText);
var urllog = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
+ "en" + "&tl=" + "iw" + "&dt=t&q=" + encodeURI(text);
var result = JSON.parse(UrlFetchApp.fetch(urllog).getContentText());
translatedText = result[0][0][0];
console.log(translatedText);
}
so the url is downloading me a text file called "f.txt" that include the translate code the problem is that I doesnt want it to download File,
I just need the translate inside the txt file its gives me,
also the problem is I am not sure how to get that info inside a javascript variable, And I doesnt want it to give me that file as well..
So how Can I read it?
how can I use the file without download it, and How can I push it to a string variable?
And How I can cancel the download and get only the translate?
THANKS!
By the way
and if anyone know the function doGet(e) that I showed on the link, what is "e"? what does the function wants?
I know I'm a year late but I came to same problem and fixed it using PHP. I have created this simple PHP function:
function translate($text, $from, $to) {
if($text == null)
echo "Please enter a text to translate.";
if($from == null)
$from = "auto";
if($to == null)
$to = "en";
$NEW_TEXT = preg_replace('/\s+/', '+', $text);
$API_URL = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" . $from . "&tl=" . $to . "&dt=t&q=" . $NEW_TEXT;
$OUTPUT = get_remote_data($API_URL);
$json = json_decode($OUTPUT, true); // decode the JSON into an associative array
$TRANSLATED_OUTPUT = $json[0][0][0];
echo $TRANSLATED_OUTPUT;
}
Example usage (English to Spanish):
translate("Hello", "en", "es"); //Output: Hola
/*
sourceLanguage: the 2-3 letter language code of the source language (English = "en")
targetLanguage: the 2-3 letter language code of the target language (Hebrew is "iw")
text: the text to translate
callback: the function to call once the request finishes*
* Javascript is much different from C# in that it is an asynchronous language, which
means it works on a system of events, where anything may happen at any time
(which makes sense when dealing with things on the web like sending requests to a
server). Because of this, Javascript allows you to pass entire
functions as parameters to other functions (called callbacks) that trigger when some
time-based event triggers. In this case, as seen below,
we use our callback function when the request to google translate finishes.
*/
const translate = function(sourceLanguage,targetLanguage,text,callback) {
// make a new HTTP request
const request = new XMLHttpRequest();
/*
when the request finishes, call the specified callback function with the
response data
*/
request.onload = function() {
// using JSON.parse to turn response text into a JSON object
callback(JSON.parse(request.responseText));
}
/*
set up HTTP GET request to translate.googleapis.com with the specified language
and translation text parameters
*/
request.open(
"GET",
"https://translate.googleapis.com/translate_a/single?client=gtx&sl=" +
sourceLanguage + "&tl=" + targetLanguage + "&dt=t&q=" + text,
true
);
// send the request
request.send();
}
/*
translate "This shouldn't download anything" from English to Hebrew
(when the request finishes, it will follow request.onload (specified above) and
call the anonymous
function we use below with the request response text)
*/
translate("en","iw","This shouldn't download anything!",function(translation) {
// output google's JSON object with the translation to the console
console.log(translation);
});

Serving urls to a Web view controller in Java javafx

I'm trying to serve requests to Google API using a JavaFX app. I'm using the Google roads API. Problem is I'm asking user to import an excel document with coordinates and the document can hold as many latitude and longitude data as possible but the Google API only allows less than 100 pairs of coordinates. So how can I serve the data which is in an array list from index at position 0 to 99 and on button press serve the next set of coordinates from 100 to 199 or less. I'm currently able to serve the arraylist.sublist(0to99) and get back a json response. Thanks in advance
//On fx button click the following happens
#FXML public void loadURL(Event event){
co_ordinates = Excel_Exchange.value;
if(!next){
limit = (int)co_ordinates.size();
next = true;//some global boolean variable so that this is done once
}
if(co_ordinates.size()<100){
StringBuilder urlCaseOne = new StringBuilder(co_ordinates.subList(start, co_ordinates.size()).toString().replaceAll("[\\[\\]]","").replaceAll(", ",""));
url_link = "https://roads.googleapis.com/v1/snapToRoads?path="+urlCaseOne.deleteCharAt(urlCaseOne.length()-1)+"&interpolate=true&key="+API_KEY;
}else{
if(limit>100){
StringBuilder urlCaseTwo = new StringBuilder(co_ordinates.subList(start, end).toString().replaceAll("[\\[\\]]","").replaceAll(", ",""));
url_link = "https://roads.googleapis.com/v1/snapToRoads?path="+urlCaseTwo.deleteCharAt(urlCaseTwo.length()-1)+"&interpolate=true&key="+API_KEY;
//System.out.println("l"+limit+" s"+start+" e"+end);
start+=100; end+=100; limit-=100;
}else if(limit<100){
StringBuilder urlCaseThree = new StringBuilder(co_ordinates.subList(start, co_ordinates.size()).toString().replaceAll("[\\[\\]]","").replaceAll(", ",""));
url_link = "https://roads.googleapis.com/v1/snapToRoads?path="+urlCaseThree.deleteCharAt(urlCaseThree.length()-1)+"&interpolate=true&key="+API_KEY;
}
}
//System.out.println(co_ordinates.size());
//System.out.println(url_link);
//System.out.println(co_ordinates.toString().lastIndexOf("|"));
//System.out.println(co_ordinates.subList(0, 99).size());
startLoadState.apply();
this.engine.load(url_link);
}// i have another method that navigates back by to the first url

Occasional (and recurrent) problems with FacebookMobile.init()

Seems this API is broken and/or abandoned because in some days, this API call always fails during a few hours. Today is happening again, but it's taking more time than previous times.
I don't know what to do. I have 2 Air apps and they aren't working today.
Any solution on this?
Here is a simple piece of code:
FacebookMobile.init(APP_ID, onInit);
private function onInit(fbSession:Object, fail:Object):void
{
if (fbSession){
trace(fbSession.accessToken);
}
else{
traceV2(fail); // it's a "deep" trace
// other API methods related to login
}
}
In FacebookMobile.init(), we have to expect for an session object (containing FB acess token), or a "fail" object.
The fail object is returning this to me:
[Object]
| [error:Object]
| code = 190
| message = Malformed access token AAAEWSUA8XjUBAJo4JuO5hUMwSnKC95LNRr1nHHIU8rwPGzxvHIuhUcDziZA9ZC3xDf4ZBwYcqjVU1ir5wf5jlEsJ5zwyMhnnWGyWxXeKQZDZD,AAAEWSUA8XjUBAJo4JuO5hUMwSnKC95LNRr1nHHIU8rwPGzxvHIuhUcDziZA9ZC3xDf4ZBwYcqjVU1ir5wf5jlEsJ5zwyMhnnWGyWxXeKQZDZD
| type = OAuthException
Thanks in advance!
Problem fixed.
The solution to this specific problem is at at com.facebook.graph.FacebookMobile:560, inside the handleLogin() function.
protected function handleLogin(result:Object, fail:Object):void {
loginWindow.loginCallback = null;
if (fail) {
loginCallback(null, fail);
return;
}
// ---------------||--------------------//
// ---------------\/--------------------//
// This line below solves this problem
result.access_token = String(result.access_token).split(',')[0];
// ---------------/\-------------------//
// ---------------||-------------------//
session = new FacebookSession();
session.accessToken = result.access_token;
session.expireDate = (result.expires_in == 0) ? null : FacebookDataUtils.stringToDate(result.expires_in) ;
if (_manageSession) {
var so:SharedObject = SharedObject.getLocal(SO_NAME);
so.data.accessToken = session.accessToken;
so.data.expireDate = session.expireDate;
so.flush();
}
verifyAccessToken();
}
Seems like its a bug with Facebook returning the Access token as an Array:
http://developers.facebook.com/bugs/276418065796236?browse=search_5034a345a2cb15e92344737
I would try edit the String that is returned by removing the second access token value in it. (Everything after the comma) and signing that to your local sessions access token variable. It might resolve the issue

google maps api : internal server error when inserting a feature

I try to insert features on a custom google map : i use the sample code from the doc
but i get a ServiceException (Internal server error) when i call the
service's insert method.
Here is what i do :
I create a map and get the resulting MapEntry object :
myMapEntry = (MapEntry) service.insert(mapUrl, myEntry);
This works fine : i can see the map i created in "my maps" on google.
I use the feed url from the map to insert a feature :
final URL featureEditUrl =
myMapEntry.getFeatureFeedUrl();
I create a kml string using the sample from the doc :
String kmlStr = "< Placemark xmlns=\"http://www.opengis.net/kml/2.2\">"
+ "<name>Aunt Joanas Ice Cream Shop</name>"
+ "<Point>"
+ "<coordinates>-87.74613826475604,41.90504663195118,0</
coordinates>"
+ "</Point></Placemark>";
And when i call the insert method i get an internal server error.
I must be doing something wrong but i cant see what, can anybody
help ?
Here is the complete code i use :
public void doCreateFeaturesFormap(MapEntry myMap)
throws ServiceException, IOException {
final URL featureEditUrl = myMap.getFeatureFeedUrl();
FeatureEntry featureEntry = new FeatureEntry();
try {
String kmlStr = "<Placemark xmlns=\"http://www.opengis.net/kml/
2.2\">"
+ "<name>Aunt Joanas Ice Cream Shop</name>"
+ "<Point>"
+ "<coordinates>-87.74613826475604,41.90504663195118,0</
coordinates>"
+ "</Point></Placemark>";
XmlBlob kml = new XmlBlob();
kml.setFullText(kmlStr);
featureEntry.setKml(kml);
featureEntry.setTitle(new PlainTextConstruct("Feature Title"));
} catch (NullPointerException e) {
System.out.println("Error: " + e.getClass().getName());
}
FeatureEntry myFeature = (FeatureEntry) service.insert(
featureEditUrl, featureEntry);
}
Thanks in advance,
Vincent.
For future reference, it was an error in their example.
Here's the issue:
http://code.google.com/p/gdata-java-client/issues/detail?id=285
Replace setFullText(KML) with setBlob(KML)

Calling wkhtmltopdf to generate PDF from HTML

I'm attempting to create a PDF file from an HTML file. After looking around a little I've found: wkhtmltopdf to be perfect. I need to call this .exe from the ASP.NET server. I've attempted:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = HttpContext.Current.Server.MapPath("wkhtmltopdf.exe");
p.StartInfo.Arguments = "TestPDF.htm TestPDF.pdf";
p.Start();
p.WaitForExit();
With no success of any files being created on the server. Can anyone give me a pointer in the right direction? I put the wkhtmltopdf.exe file at the top level directory of the site. Is there anywhere else it should be held?
Edit: If anyone has better solutions to dynamically create pdf files from html, please let me know.
Update:
My answer below, creates the pdf file on the disk. I then streamed that file to the users browser as a download. Consider using something like Hath's answer below to get wkhtml2pdf to output to a stream instead and then send that directly to the user - that will bypass lots of issues with file permissions etc.
My original answer:
Make sure you've specified an output path for the PDF that is writeable by the ASP.NET process of IIS running on your server (usually NETWORK_SERVICE I think).
Mine looks like this (and it works):
/// <summary>
/// Convert Html page at a given URL to a PDF file using open-source tool wkhtml2pdf
/// </summary>
/// <param name="Url"></param>
/// <param name="outputFilename"></param>
/// <returns></returns>
public static bool HtmlToPdf(string Url, string outputFilename)
{
// assemble destination PDF file name
string filename = ConfigurationManager.AppSettings["ExportFilePath"] + "\\" + outputFilename + ".pdf";
// get proj no for header
Project project = new Project(int.Parse(outputFilename));
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = ConfigurationManager.AppSettings["HtmlToPdfExePath"];
string switches = "--print-media-type ";
switches += "--margin-top 4mm --margin-bottom 4mm --margin-right 0mm --margin-left 0mm ";
switches += "--page-size A4 ";
switches += "--no-background ";
switches += "--redirect-delay 100";
p.StartInfo.Arguments = switches + " " + Url + " " + filename;
p.StartInfo.UseShellExecute = false; // needs to be false in order to redirect output
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true; // redirect all 3, as it should be all 3 or none
p.StartInfo.WorkingDirectory = StripFilenameFromFullPath(p.StartInfo.FileName);
p.Start();
// read the output here...
string output = p.StandardOutput.ReadToEnd();
// ...then wait n milliseconds for exit (as after exit, it can't read the output)
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
// if 0 or 2, it worked (not sure about other values, I want a better way to confirm this)
return (returnCode == 0 || returnCode == 2);
}
I had the same problem when i tried using msmq with a windows service but it was very slow for some reason. (the process part).
This is what finally worked:
private void DoDownload()
{
var url = Request.Url.GetLeftPart(UriPartial.Authority) + "/CPCDownload.aspx?IsPDF=False?UserID=" + this.CurrentUser.UserID.ToString();
var file = WKHtmlToPdf(url);
if (file != null)
{
Response.ContentType = "Application/pdf";
Response.BinaryWrite(file);
Response.End();
}
}
public byte[] WKHtmlToPdf(string url)
{
var fileName = " - ";
var wkhtmlDir = "C:\\Program Files\\wkhtmltopdf\\";
var wkhtml = "C:\\Program Files\\wkhtmltopdf\\wkhtmltopdf.exe";
var p = new Process();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = wkhtml;
p.StartInfo.WorkingDirectory = wkhtmlDir;
string switches = "";
switches += "--print-media-type ";
switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";
switches += "--page-size Letter ";
p.StartInfo.Arguments = switches + " " + url + " " + fileName;
p.Start();
//read output
byte[] buffer = new byte[32768];
byte[] file;
using(var ms = new MemoryStream())
{
while(true)
{
int read = p.StandardOutput.BaseStream.Read(buffer, 0,buffer.Length);
if(read <=0)
{
break;
}
ms.Write(buffer, 0, read);
}
file = ms.ToArray();
}
// wait or exit
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
return returnCode == 0 ? file : null;
}
Thanks Graham Ambrose and everyone else.
OK, so this is an old question, but an excellent one. And since I did not find a good answer, I made my own :) Also, I've posted this super simple project to GitHub.
Here is some sample code:
var pdfData = HtmlToXConverter.ConvertToPdf("<h1>SOO COOL!</h1>");
Here are some key points:
No P/Invoke
No creating of a new process
No file-system (all in RAM)
Native .NET DLL with intellisense, etc.
Ability to generate a PDF or PNG (HtmlToXConverter.ConvertToPng)
Check out the C# wrapper library (using P/Invoke) for the wkhtmltopdf library: https://github.com/pruiz/WkHtmlToXSharp
There are many reason why this is generally a bad idea. How are you going to control the executables that get spawned off but end up living on in memory if there is a crash? What about denial-of-service attacks, or if something malicious gets into TestPDF.htm?
My understanding is that the ASP.NET user account will not have the rights to logon locally. It also needs to have the correct file permissions to access the executable and to write to the file system. You need to edit the local security policy and let the ASP.NET user account (maybe ASPNET) logon locally (it may be in the deny list by default). Then you need to edit the permissions on the NTFS filesystem for the other files. If you are in a shared hosting environment it may be impossible to apply the configuration you need.
The best way to use an external executable like this is to queue jobs from the ASP.NET code and have some sort of service monitor the queue. If you do this you will protect yourself from all sorts of bad things happening. The maintenance issues with changing the user account are not worth the effort in my opinion, and whilst setting up a service or scheduled job is a pain, its just a better design. The ASP.NET page should poll a result queue for the output and you can present the user with a wait page. This is acceptable in most cases.
You can tell wkhtmltopdf to send it's output to sout by specifying "-" as the output file.
You can then read the output from the process into the response stream and avoid the permissions issues with writing to the file system.
My take on this with 2018 stuff.
I am using async. I am streaming to and from wkhtmltopdf. I created a new StreamWriter because wkhtmltopdf is expecting utf-8 by default but it is set to something else when the process starts.
I didn't include a lot of arguments since those varies from user to user. You can add what you need using additionalArgs.
I removed p.WaitForExit(...) since I wasn't handling if it fails and it would hang anyway on await tStandardOutput. If timeout is needed, then you would have to call Wait(...) on the different tasks with a cancellationtoken or timeout and handle accordingly.
public async Task<byte[]> GeneratePdf(string html, string additionalArgs)
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = #"C:\Program Files\wkhtmltopdf\wkhtmltopdf.exe",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
Arguments = "-q -n " + additionalArgs + " - -";
};
using (var p = Process.Start(psi))
using (var pdfSream = new MemoryStream())
using (var utf8Writer = new StreamWriter(p.StandardInput.BaseStream,
Encoding.UTF8))
{
await utf8Writer.WriteAsync(html);
utf8Writer.Close();
var tStdOut = p.StandardOutput.BaseStream.CopyToAsync(pdfSream);
var tStdError = p.StandardError.ReadToEndAsync();
await tStandardOutput;
string errors = await tStandardError;
if (!string.IsNullOrEmpty(errors)) { /* deal/log with errors */ }
return pdfSream.ToArray();
}
}
Things I haven't included in there but could be useful if you have images, css or other stuff that wkhtmltopdf will have to load when rendering the html page:
you can pass the authentication cookie using --cookie
in the header of the html page, you can set the base tag with href pointing to the server and wkhtmltopdf will use that if need be
Thanks for the question / answer / all the comments above. I came upon this when I was writing my own C# wrapper for WKHTMLtoPDF and it answered a couple of the problems I had. I ended up writing about this in a blog post - which also contains my wrapper (you'll no doubt see the "inspiration" from the entries above seeping into my code...)
Making PDFs from HTML in C# using WKHTMLtoPDF
Thanks again guys!
The ASP .Net process probably doesn't have write access to the directory.
Try telling it to write to %TEMP%, and see if it works.
Also, make your ASP .Net page echo the process's stdout and stderr, and check for error messages.
Generally return code =0 is coming if the pdf file is created properly and correctly.If it's not created then the value is in -ve range.
using System;
using System.Diagnostics;
using System.Web;
public partial class pdftest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void fn_test()
{
try
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
Response.Write(url);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName =
#"C:\PROGRA~1\WKHTML~1\wkhtmltopdf.exe";//"wkhtmltopdf.exe";
startInfo.Arguments = url + #" C:\test"
+ Guid.NewGuid().ToString() + ".pdf";
Process.Start(startInfo);
}
catch (Exception ex)
{
string xx = ex.Message.ToString();
Response.Write("<br>" + xx);
}
}
protected void btn_test_Click(object sender, EventArgs e)
{
fn_test();
}
}