How to cast Representation to FileRepresentation in Restlet - file

I am using Restlet framework. I create one web service that returns a file to the client.
On the server side, I first create a FileRepresentation object, instantiate it correctly, and return it to the client as Representation.
On the client side, I want to extract the content of the Representation, how can I cast the Representation object to FileRepresentation?
Thanks in advance!!

In fact, the FileRepresentation class is provided in order to fill request / response from a file but can't be used to extract content of a response.
To have access to your response content on the client side, it depends on the file type. If you receive an ascii content, you can do something like that:
Representation representation = resource.get();
String fileContent = representation.getText();
If it's a binary file, you need to work with a stream, as described below:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
resource.get().write(outputStream);
byte[] fileContent = outputStream.toByteArray();
Hope it helps you,
Thierry

Related

Initiate file download from byte stream in Flex

I have a situation in a Flex web app where we use a PHP webservice to lookup, read the contents and then send the Base64 encoded data back to the Flex app as part of an XML document.The Flex app must then extract, Base64 decode the byte stream and then send it DIRECTLY to the browser user (for download) without writing the file to disk.
This all must occur on the click of a "DOWNLOAD NOW" button for example.
I have been searching but all I have been finding are examples of either downloading from a URL or actually writing the byte stream to disk, which i don't want.
I need to get the stream pushed directly to the browser. This way i can keep the files on the server protected by being outside the webspace as opposed to publicly accessible.
Can anyone help?
You can pop a ByteArray into a Loader then use FileReference to initiate the download dialog.
var file:FileReference = new FileReference();
var loader:Loader = new Loader();
//put loader in binary mode
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, loader_completeHandler);
//I will assume you are getting an appropriate ByteArray from your stream
var data:ByteArray = new ByteArray();
loader.loadBytes(data);
private function loader_completeHandler(evt:Event):void {
//now pop a save window
file.save(loader.data,"default_file_name.png")
}
edit
I will also assume you are doing this to stream a file through a non standard protocol, such as AMF, otherwise you would simply output the file over HTTP and let the browser handle the rest.

Silverlight convert byte[] to string for Image

In my silvelright application, I have an image that is stored in a byte[]. I want to save the image to Azure Blobl Storage using REST services, but it only accepts Strings (UploadStringTaskAsync)
I have tried many ways to convert my byte[] to a valid String but without success :
Encoding.UTF8.GetString(data, 0, data.Length)
Encoding.Unicode.GetString(data, 0, data.Length)
Even with a custom function (at least that function gives me the right String length)
var sb = new StringBuilder();
foreach(byte b in data)
sb.Append((char)b);
return sb.ToString();
But the image is always corrupted and/or unreadable on the other side. What am I doing wrong?
Thanks
Use Convert.FromToBase64String method on client. Then decode it on server with Convert.FromBase64String.
Update:
You can also use WebClient.OpenWriteAsync method.

WPF : Invalid URI: The format of the URI could not be determined

i want to get the you tube video info. So I prepared the url and call it as following
String YouTubeVideoInfo = "www.youtube.com/get_video_info?video_id=" + FinalVideoId;
**WebRequest HttpWReq = (WebRequest)WebRequest.Create(YouTubeVideoInfo);**
WebResponse HttpWResp = (WebResponse)HttpWReq.GetResponse();
Stream stream = HttpWResp.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string contents = reader.ReadToEnd();
but above code give the error. So i just want to know whether there are any way to call this url without adding protocol (http, https)
No, you cannot. How would WebRequest know about the protocol if you don't give it a URI? As it stands it's definitely missing the protocol part and as such you cannot pass it as URI to anything that expects one.

Converting byte[] of a PDF file original source to MemoryStream for loading into PDF viewer? (component one)

I'm working with a ComponentOne (C1) silverlight PDF viewer control.
It has a "LoadDocument" method that accepts a "Stream".
I'm making an HTTP get call from my client app to get a PDF document.
This document, on the server side, has been streamed in through File.ReadAllBytes(), then converted to a base64 string using Convert.ToBase64String().
This string is sent across the wire back to my silverlight app where it's then reversely converted back into a byte array with Convert.FromBase64String(val).
Then I'm creating a MemoryStream with that byte array and passing "LoadDocument()" that memory stream.
The viewer is rendering nothing. It shows the toolbar and scrollbars, but the contents are blank and the save button is grayed out, suggesting that no document loaded.
I know for certain the file made it across because the byte array size on the client matches teh byte array pre-conversion on the server side.
Here's my code: (in the interest of time/space, i've truncated, removing validation, etc.)
SERVERSIDE
string sendingToClient = Convert.ToBase64String(File.ReadAllBytes(filePath))
CLIENTSIDE
byte[] image = null;
image = Convert.FromBase64String(stringFromServerCall);
MemoryStream stream = new MemoryStream(image);
docViewer.LoadDocument(stream);
edit As a potential workaround, I attempted to save the file into isolated storage with a ".pdf" extension. Then I use the IsolatedStorageFileStream to send to LoadDocument().
I've come to an actual error, it now says "PdfParserException was unhandled by user code: invalid file format (missing pdf header)"
Can anyone shed some light on this PDF header?
Here is an experiment I would conduct.
Add a button to your Xaml and on click use OpenFileDialog to get a FileInfo. From that FileInfo use its Open method to get a stream and pass that to docViewer.LoadDocument.
Now run it, click the button and select the same PDF document you are trying to send from the server.
If that succeeds you need to continue investigating your server streaming strategy. On the other hand if you still have the same problem, well it doesn't get more raw than that. Try other PDF files and start investigating the PDF component. Have you ever actually used it successfully, if so how does this current usage differ.
you should get the stream pointer back to 0 ,so this should do the trick
byte[] image = null;
image = Convert.FromBase64String(stringFromServerCall);
MemoryStream stream = new MemoryStream(image);
stream.Position = 0;
docViewer.LoadDocument(stream);

web service - mobile application (j2me) file transfer

What i'm trying to do is transfer an image from the web service to the mobile client. In order to do this i've created a web service operation that returns a byte[] variable. In this method i create an .png image from a chart. After this i get the bytes from the image and provide them as a return value for the operation. this is the server code:
public byte[] getBytes() throws IOException {
BufferedImage chartImage = chart.createBufferedImage(230, 260);
//I get the image from a chart component.
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
ImageIO.write( chartImage, "png",baos );
baos.flush();
byte[] bytesImage = baos.toByteArray();
baos.close();
return bytesImage;
}
Now in the mobile application all i do is assign a byte[] variable the return value of the web service operation.
byte[] imageBytes = Stub.getBytes().
Maybe i'm missing something but this is not working as i get this runtime error:
java.rmi.MarshalException: Expected Byte, received: iVBORw0KGgoAAAANSUhEU.... (very long line).
have any ideas why this happends? Or maybe you can suggest any other way to send the data to the mobile client.
If the service is only delivering an image as a byte array, the overhead induces by wrapping this in a SOAP response and XML/SOAP parsing on the client side seem rather unnecessary. Why don't you implement the chart generation in a servlet and let the client retrieve the image from a 'non-SOAP' server URL?
Instead of returning bytesImage from a WebService method like you do, you could instead write the byte array to the servlet's response object:
response.setContentType("image/png");
response.setContentLength(bytesImage.length);
OutputStream os = response.getOutputStream();
os.write(bytesImage);
os.close();
On the J2ME client, you would read the response from the URL, to which the servlet is bound and create an image from the data:
HttpConnection conn = (HttpConnection)Connector.open("http://<servlet-url>");
DataInputStream dis = conn.openDataInputStream();
byte[] buffer = new byte[conn.getLength()];
dis.readFully(buffer);
Image image = Image.createImage(buffer, 0, buffer.length);
Hope this helps!

Resources