How can I display servlet's ServletOutputStream in Adobe Air wondow? - actionscript-3

I have a very difficult situation, nothing is helping.
I have a servlet running in glassfish server.
protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
String filename = request.getParameter( "file" );
try {
ServletOutputStream printStream = response.getOutputStream();
File aFile = new File( filename );
try {
printStream.print( getContents( aFile ) );
aFile.delete();
} catch ( IOException e ) {
printStream.print( printWarning() );
}
} catch ( Exception e ) {
logger.error( e.getMessage(), e );
}
}
I am invoking this servlet from Adobe Air application and want to display the content of the file (passed as a parameter) into a Adobe Air window. If I use navigateToURL() method, then Adobe Air application is opening an internet browser window and successfully displaying the content. But if I use the following A3 code -
var service:HTTPService = new HTTPService();
service.resultFormat = "xml";
service.url="http://server.com/..../servletUrl";
service.method = URLRequestMethod.GET;
var params:Object = new Object();
params["file"] = "/tmp/xyz.html";
service.addEventListener(Event.COMPLETE, pageLoadComplete);
service.send(params);
public function pageLoadComplete(event:Event):void
{
log.debug("Received event");
var result:String = URLLoader(event.currentTarget).data.toString();
log.debug("Result =" , result);
}
Then I am not getting any Result! This is obvious because the servlet is only printing the content and nothing else.
I cannot change the servlet code, I can only change the Adobe Air framework so that it can work with any backend code.
So what is causing the demarcation that servlet response is being printed on the browser (Chrome) window and not on Adobe Air window? And how to fix it?
Thanks in advance...

Related

How to use SocketChannel to connect to remote webserver

I am trying to get the response sent by the web server through Java NIO socketChannel. The read call of SocketChannel is not returning anything when it is in non-blocking
clientSocket.configureBlocking(false);
When specified true, means blocking mode, then it is returning response. Someone saying that we should use Selector when non-blocking mode enabled. But I didn't find a way to implement this.
FYI, Following is the code snippet I am trying.
public static void main(String[] args) throws IOException, InterruptedException
{
URL u = new URL("http://www.google.com");
InetSocketAddress addr = new InetSocketAddress("www.google.com", 80);
SocketChannel clientSocket = SocketChannel.open(addr);
clientSocket.configureBlocking(false);
byte[] message = new String("GET " + u.getFile() + " HTTP/1.0\r\n").getBytes();
ByteBuffer writeBuff = ByteBuffer.wrap(message);
clientSocket.write(writeBuff);
ByteBuffer readBuff = MappedByteBuffer.allocate(1500);
clientSocket.read(readBuff);
while(clientSocket.read(readBuff) > 0)
{
System.out.println(new String(readBuff.array()).trim());
}
clientSocket.close();
}
Thanks in advance.
You should use loops to read() and write() till the buffer has no remaining bytes when non-blocking mode.
There two problems in your code:
the http request body is wrong. it needs additional "\r\n".
the readBuff need to cleared each time after reading.
below code is a working version:
static void working() throws Exception {
URL u = new URL("http://www.baidu.com");
InetSocketAddress addr = new InetSocketAddress("www.baidu.com", 80);
SocketChannel clientSocket = SocketChannel.open(addr);
clientSocket.configureBlocking(false);
byte[] message = new String("GET / HTTP/1.0\r\n\r\n").getBytes();
ByteBuffer writeBuff = ByteBuffer.wrap(message);
clientSocket.write(writeBuff);
ByteBuffer readBuff = MappedByteBuffer.allocate(1500);
while (clientSocket.read(readBuff) != -1) {
System.out.println("Entring...");
System.out.println(new String(readBuff.array()).trim());
readBuff.clear();
}
clientSocket.close();
}
}
Notice, if it's http version 1.1, it will not break too. because it has a keeplive.

Exception When Rendering an Image Using Lumia Imaging SDK

In my WP8.1 app, I'm trying to crop an image using the Lumia (formerly Nokia) Imaging SDK. the image is retrieved using FileOpenPicker:
public async void ContinueFileOpenPicker(Windows.ApplicationModel.Activation.FileOpenPickerContinuationEventArgs args) {
if (args.Files.Count > 0) {
_stream = await args.Files[0].OpenAsync(Windows.Storage.FileAccessMode.Read);
_bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await _bitmapImage.SetSourceAsync(_stream);
SelectedImage.Source = _bitmapImage;
}
else {
Debug.WriteLine("Operation cancelled.");
}
}
Then the filter applied in a button handler (after the user selected a cropping area; dimensions just for testing purposes):
private async void GetImageAcceptButton_Click(object sender, RoutedEventArgs e) {
await GetCroppedBitmapAsync();
}
async public Task GetCroppedBitmapAsync() {
using (var source = new RandomAccessStreamImageSource(_stream)) {
using (var filterEffect = new FilterEffect(source)) {
var filter = new CropFilter(new Windows.Foundation.Rect(0, 0, 100, 100));
filterEffect.Filters = new IFilter[] { filter };
var target = new WriteableBitmap(50, 50);
using (var renderer = new WriteableBitmapRenderer(filterEffect, target)) {
await renderer.RenderAsync();
SelectedImage.Source = target;
}
}
}
}
The RenderAsync() call throws an exception:
System.Runtime.InteropServices.COMException occurred
HResult=-2147467259
Message=Error HRESULT E_FAIL has been returned from a call to a COM component.
Source=mscorlib
ErrorCode=-2147467259
Applying the filters seems rather straightforward. Why does it fail here?
You should enable native debugging and look at the Output window. You're currently missing the real exception message (which tries to be more specific). Exception message strings are "smuggled" across the WinRT call border, only an HRESULT is officially passed (here, E_FAIL).
Is this Silverlight 8.1 or a Universal App btw?
My guess at an answer might be that you need to seek/rewind the stream back. It could be that the position is at the end.

How to convert .aspx to Image in asp.net with forms authentication

I have tried this code
public System.Drawing.Bitmap CaptureWebPage(string URL)
{
// create a hidden web browser, which will navigate to the page
System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
// we don't want scrollbars on our image
web.ScrollBarsEnabled = false;
// don't let any errors shine through
web.ScriptErrorsSuppressed = true;
// let's load up that page!
web.Navigate(URL);
// wait until the page is fully loaded
while (web.ReadyState != WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(1500); // allow time for page scripts to update
// the appearance of the page
// set the size of our web browser to be the same size as the page
int width = web.Document.Body.ScrollRectangle.Width;
int height = web.Document.Body.ScrollRectangle.Height;
web.Width = width;
web.Height = height;
// a bitmap that we will draw to
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
// draw the web browser to the bitmap
web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height));
return bmp; // return the bitmap for processing
}
protected void btnConvert_Click(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(CaptureWebPage(txtUrl.Text));
Response.ContentType = "image/jpeg";
bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
bitmap.Dispose();
bitmap.Dispose();
Response.End();
}
I am able to capture google.com,but not able to capture images of our web site since it contains form authentication so it redirects me to login page and login page is captured.Please help to pass through authentication.Can we use sessions,cookies or anything with the WebBrowser to valid it Or something.Please suggest.
Try on the intended page on your website :
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter sw = new System.IO.StringWriter(sb);
Page.RenderControl(new HtmlTextWriter(sw));
and then use the HTML in the string builder to render the page like the example below (Reference : Convert HTML string to image) :
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
var source = #"
<!DOCTYPE html>
<html>
<body>
<p>An image from W3Schools:</p>
<img
src=""http://www.w3schools.com/images/w3schools_green.jpg""
alt=""W3Schools.com""
width=""104""
height=""142"">
</body>
</html>";
StartBrowser(source);
Console.ReadLine();
}
private static void StartBrowser(string source)
{
var th = new Thread(() =>
{
var webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.DocumentCompleted +=
webBrowser_DocumentCompleted;
webBrowser.DocumentText = source;
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
static void
webBrowser_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e)
{
var webBrowser = (WebBrowser)sender;
using (Bitmap bitmap =
new Bitmap(
webBrowser.Width,
webBrowser.Height))
{
webBrowser
.DrawToBitmap(
bitmap,
new System.Drawing
.Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(#"filename.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}

How to Capture the Web Exception in windows phone 8?

I am using the Wamp Server for back end and C# for front end. For Cheeking purpose i turn off the server. And run the program. It throw the following error in output window.
'TaskHost.exe' (CLR C:\windows\system32\coreclr.dll: Silverlight AppDomain): Loaded
'C:\windows\system32\System.Core.ni.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
My Aim is Capture that Web exception into on message box. Is it possible.
I am already use the try, catch statement for capture that exception. But it's not working.
My Code
private void Login_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(this.username.Text) || string.IsNullOrWhiteSpace(this.password.Password))
{
MessageBox.Show("Please Enter the Username and Password");
this.username.Text = "";
this.password.Password = "";
}
else
{
string url = ob.localhost + "login_validate.php";
Uri uri = new Uri(url, UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "username", HttpUtility.UrlEncode(this.username.Text));// txtUsername.Text));
postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode(this.password.Password.ToString()));
try
{
WebClient client = default(WebClient);
client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
client.UploadStringCompleted += client_UploadStringCompleted;
//client.UploadProgressChanged += client_UploadProgressChanged;
client.UploadStringAsync(uri, "POST", postData.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Data.ToString());
MessageBox.Show(ex.GetBaseException().ToString());
}
}
prog = new ProgressIndicator();
prog.IsIndeterminate = true;
prog.IsVisible = true;
prog.Text = "Loading....";
SystemTray.SetProgressIndicator(this, prog);
}
Please help me. Thanks in advance.
try using:
catch(Webexception ex)
{
Messagebox.Show(ex.innerexception.tostring());
}

Webservices object reference not set to an instance of an object error

I have to make a call to the web service (JSON) to authenticate the user who is trying to login to the app. I have the following xml provided
<summary>
http://geniewebsvc.cloudapp.net/Member.svc/Authenticate
</summary>
<param name="payload">
{"UserName":"testuser#somedomain.com","Password":"p#$$w0rd"}
</param>
<requiredHeaders>
Content-Type: application/json;charset=UTF-8
</requiredHeaders>
<returns></returns>
[OperationContract]
[WebInvoke(UriTemplate = "/Authenticate", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
AuthenticateResponse Authenticate(AuthCredentials usernamePassword);
There is similar one to check if the userid is already registered and that is a Get method. That works fine and i receive the right response for both successful and unsuccessful cases. But all the post methods are the ones which are giving me trouble. and i noticed that there is one more difference in these xmls.. i.e., the .. the isregistered webservice param tag goes something like this..
<param name="emailAddress"></param>
and here is my get() and post() please let me know whats my mistake...
public void Post()
{
RequestState myRequestState = new RequestState();
try
{
System.Uri uri = new Uri(url);
HttpWebRequest myHttpWebGetRequest;
Logger.log(TAG, "Create a HttpWebrequest object to the URL", url);
myHttpWebGetRequest = (HttpWebRequest)WebRequest.Create(uri);
_mHttpWebRequest = myHttpWebGetRequest;
myRequestState.conn = this;
myRequestState.request = myHttpWebGetRequest;
myRequestState.request.ContentType = "application/json;charset=UTF-8";
myRequestState.request.Method = "POST";
myRequestState.request.AllowReadStreamBuffering = false;
myRequestState.request.Headers["UserName"] = "rick.labarbera#gmail.com";
myRequestState.request.Headers["Password"] = "125124514";
// myRequestState.request.Headers["MemberId"] = "UdE8IwmTbxEjmzmMo2nBpg==";
IAsyncResult result = (IAsyncResult)myHttpWebGetRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}
catch (Exception e)
{
close(myRequestState);
if (this.listener != null)
{
Logger.log(TAG, "post()", e.Message);
}
}
}
public void Get()
{
RequestState myRequestState = new RequestState();
try
{
System.Uri uri = new Uri(url);
HttpWebRequest myHttpWebPostRequest;
Logger.log(TAG, "Create a HttpWebrequest object to the URL", url);
myHttpWebPostRequest = (HttpWebRequest)WebRequest.Create(uri);
_mHttpWebRequest = myHttpWebPostRequest;
myRequestState.conn = this;
myRequestState.request = myHttpWebPostRequest;
myRequestState.request.Method = "GET";
myRequestState.request.AllowReadStreamBuffering = false;
IAsyncResult result = (IAsyncResult)myHttpWebPostRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}
catch (Exception e)
{
close(myRequestState);
if (this.listener != null)
{
Logger.log(TAG, "get()", e.Message);
}
}
}
Am i doing something wrong???All these things are very very new to me.. I need help badly..
Thanks :)
I have played a bit with your code, but couldn't make it :(
What are the URL's you are using for the POST() method and for GET() methods.?
By the way, There is another way around to invoke your service. Follow these steps:
-- Create a new project.
-- Right-click on the Project name and click on "Add Service Reference"... Then provide address as "http://geniewebsvc.cloudapp.net/Member.svc" and click Go.
-- Once service information is downloaded, provide Namespace something like "MyMemberService" and click Ok.
Then Goto your MainPage.xaml.cs and write the following code.
MemberServiceClient client = new MemberServiceClient();
client.AuthenticateCompleted += new EventHandler<AuthenticateCompletedEventArgs>(client_AuthenticateCompleted);
client.AuthenticateAsync(new AuthCredentials() { UserName = "rick.labarbera#gmail.com", Password = "125124514" });
And the AuthenticateCompleted handler is
void client_AuthenticateCompleted(object sender, AuthenticateCompletedEventArgs e)
{
MessageBox.Show(e.Result.Successful.ToString());
}
This way you can simply call any service in the MemberService with just 2 or 3 lines of code. This is how a soap client is invoked in a Visual Studio project.
But again, there are some "Endpoint configuration" issues in this which you need to solve. And if you can do that you can save atleast 30 to 40 % of your development time.
Good luck.