How to send binary content to a servlet in Action Script - java

I have an action script function in a file which sends a pdf file as binary content to a servlet as shown below.
private function savePDF(pdfBinary:ByteArray, urlString:String):void{
try{
Alert.show("in savePDF urlString" +urlString);
//result comes back as binary, create a new URL request and pass it back to the server
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var sendRequest:URLRequest = new URLRequest(urlString);
sendRequest.requestHeaders.push(header);
sendRequest.method = URLRequestMethod.POST;
sendRequest.data = pdfBinary;
Alert.show("in savePDF calling sendToURL");
sendToURL(sendRequest);
}catch(error:*){
Alert.show("in savePDF err" +error);
trace(error);
}
}
This code works fine in flashplayers versions like 10,11,13
But fails in flashplayers of higher versions like 14.0.0.126 or above.
I get the following error
SecurityError: Error #3769: Security sandbox violation: Only simple headers can be used with navigateToUrl() or sendToUrl().
Any suggestions on how to resolve this ?

You could try using a URLLoader instead of sendToURL()
Alert.show("in savePDF urlString" +urlString);
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var sendRequest:URLRequest = new URLRequest(urlString);
sendRequest.requestHeaders.push(header);
sendRequest.method = URLRequestMethod.POST;
sendRequest.data = pdfBinary;
Alert.show("in savePDF calling URLLoader");
var loader:URLLoader = new URLLoader();
loader.load(sendRequest);

Related

how to show download progress on file download?

I have an api to download file. It is able to download file but showing only after download completes. there is no download progress.
I want when user hit that url it will show download progress in chrome, currently it is showing after completion.
I am using spring boot.
public responseEntity<Resource>getFile(String fileName){
byte[] data=null;
File file=new File(fileName);
InputStream inputStream=new FileInputStream(file);
data=IOUtils.toByteArray(inputStream);
ByteArrayResource fileToDownload = new ByteArrayResource(data);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header("Content-Disposition", "filename=" + fileName)
.body(fileToDownload);
}
Use JavaScript in your webpage. This has nothing to do with how the server sends the file, and must be displayed client-side -- well, the server could output somewhere how far it is along sending the file, but that is not what you want to show - you are interested in showing how much you have received, and showing it in the client; so any answer will have to rely on JS+html to an extent. Why not solve it entirely in the client side?
In this answer they use the following code:
function saveOrOpenBlob(url, blobName) {
var blob;
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET', url, true);
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e) {
blob = new Blob([this.response]);
};
xmlHTTP.onprogress = function(pr) {
//pr.loaded - current state
//pr.total - max
};
xmlHTTP.onloadend = function(e){
var fileName = blobName;
var tempEl = document.createElement("a");
document.body.appendChild(tempEl);
tempEl.style = "display: none";
url = window.URL.createObjectURL(blob);
tempEl.href = url;
tempEl.download = fileName;
tempEl.click();
window.URL.revokeObjectURL(url);
}
xmlHTTP.send();
}
Note that you are missing part where you display the progress somewhere. For example, you could implement it as follows:
xmlHTTP.onprogress = function(pr) {
//pr.loaded - current state
//pr.total - max
let percentage = (pr.loaded / pr.total) / 100;
document.getElementById("progress").textContent = "" + percentage + "% complete";
};
This assumes that there is something like
<span id="progress">downloading...</span>
in your html

Word to PDF to Notes Document using the POI4Xpages api

I have created a PDF from a word document using POI4XPages api.
here is the code:
var template = poiBean.buildResourceTemplateSource(null,"purchaseorder.docx");
var result = poiBean.processDocument2Stream(template, lst);
var is:java.io.InputStream = new java.io.ByteArrayInputStream(result.toByteArray());
var os:java.io.OutputStream = poiBean.buildPDFFromDocX(is)
As you can see the result of my code is an OutputStream, The next step for me is to convert the stream to an attachment and attach it to a notesdocument but don't know how to do that. It doesn't really matter if I first need to attach it to disc or if it written to a body field immediately.
The poiBean is described here
https://github.com/OpenNTF/POI4Xpages/blob/master/biz.webgate.dominoext.poi/src/biz/webgate/dominoext/poi/beans/PoiBean.java
I am using SSJS here but I guess a java solution would work as well.
thanks
Thomas
Some copying and pasting but this is how you stream it into an richtext field but you need to convert os to an inputstream and assign this to a variable called is2
var stream:NotesStream = session.createStream();
session.setConvertMIME(false);
var doc:NotesDocument = database.createDocument();
var body:NotesMIMEEntity = doc.createMIMEEntity();
stream.setContents(is2); // is an inputstream
body.setContentFromBytes(stream, "application/octet-stream",NotesMIMEEntity.ENC_IDENTITY_BINARY);
stream.close();
doc.save(true, true);
session.setConvertMIME(true);
This is what I based the example on
https://openntf.org/XSnippets.nsf/snippet.xsp?id=create-html-mails-in-ssjs-using-mime

WOPI Editing Document

I have implemented the putFile endpoint for WOPI client (i.e. Office Online)
When clicking the edit document button, what should be the first request go to WOPI client?
I have called following URL on edit link:
POST https://word-edit.officeapps-df.live.com/we/wordviewerframe.aspx?WOPISrc=https://domain/WOPI_IntegrationDemo/wopi/files/Sample_application_content3.docx/
But document says that it'll perform a lock request first. What does it mean exactly?
From your question I understand that you're implementing a WOPI host. The URL looks pretty much ok - just make sure the WOPISrc parameter is escaped and that you include access_token parameter.
When you click the URL you instruct the WOPI client (OO/OWA) to load a field defined by WOPISrc from WOPI host.
The WOPI client usually tries to acquire a lock (exclusive write access) from WOPI host first. For those purposes you should implement the LOCK operation in your WOPI host according to the documentation.
First you must Add Access token for this
then you try to word edit it call to
1.get file info. Get [Route("files/{name}/")]
2.post file. Post [Route("files/{name}/")]
in hear you have to implement response for Lock files Cobalt Request
var response = new HttpResponseMessage(HttpStatusCode.OK);
if (xWopiOverride == "LOCK" || string.Equals(xWopiOverride, "UNLOCK"))
{
//for docx, xlsx and pptx
response = new HttpResponseMessage(HttpStatusCode.OK);
}
else if (string.Equals(xWopiOverride, "COBALT"))
{
//cobalt, for docx and pptx
EditSession editSession = EditSessionManager.Instance.GetSession(access_token);
if (editSession == null)
{
editSession = new FileSession(access_token, fileInfo, matterInfo, dpsUserName, databaseInfo, string.Empty, string.Empty, string.Empty, false);
EditSessionManager.Instance.AddSession(editSession);
}
var memoryStream = new MemoryStream();
HttpContext.Current.Request.InputStream.CopyTo(memoryStream);
var atomFromByteArray = new AtomFromByteArray(memoryStream.ToArray());
ProtocolVersion protocolVersion;
object context;
var requestBatch = new RequestBatch();
requestBatch.DeserializeInputFromProtocol(atomFromByteArray, out context, out protocolVersion);
editSession.ExecuteRequestBatch(requestBatch);
foreach (var request in requestBatch.Requests)
{
if (request.GetType() == typeof(PutChangesRequest) && request.PartitionId == FilePartitionId.Content)
{
editSession.Save();
break;
}
}
var responseContent = requestBatch.SerializeOutputToProtocol(protocolVersion, context);
var correlationId = Request.Headers.GetValues("X-WOPI-CorrelationID").First();
response.Headers.Add("X-WOPI-CorrelationID", correlationId);
response.Headers.Add("request-id", correlationId);
var pushStreamContent = new PushStreamContent((outputStream, httpContext, transportContent) =>
{
responseContent.CopyTo(outputStream);
outputStream.Close();
});
response.Content = pushStreamContent;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = responseContent.Length;
}
return response;

how to get file url from kaltura by entryid

I have to get video url uploaded on kaltura by entryId. I have seen kaltura api, but didn't get proper solution for that.I got something in php code:
$ks = $client->session->start($secret, $userId, KalturaSessionType::ADMIN, $partnerId, 86400, 'disableentitlement');
$client->setKs($ks);
$client->startMultiRequest();
$entryId = '1_u7aj9kasw'; //replace this with your entry Id
$client->flavorAsset->getwebplayablebyentryid($entryId);
$req1ResultFlavorId = '{1:result:0:id}'; //get the first flavor from the result of getwebplayablebyentryid
$client->flavorAsset->geturl($req1ResultFlavorId); //this action will return a valid download URL
$multiRequestResults = $client->doMultiRequest();
$downloadUrl = $multiRequestResults[1];
echo 'The entry download URL is: '.$downloadUrl;
but i have to do it with java ,what i have tried like :
KalturaConfiguration config = new KalturaConfiguration();
config.setEndpoint(envConfiguration.getKalturaUrl());
KalturaClient client = new KalturaClient(config);
String ks = client.generateSession(envConfiguration.getKalturaSecretKey(), "TestUploader",
KalturaSessionType.ADMIN, 101);
client.setKs(ks);
client.startMultiRequest();
String url = client.getFlavorAssetService().getUrl("entryid");
log.debug("url is::::::"+ url);
but i am getting url null .Please help.
Thanks in advance !!!

Java byte[] to Flex BitmapImage source

I have flex mobile client, and it takes java server byte[] as flash.utils.ByteArray, but when I want to use as a source of my bitmapImage compiler says that unknown type:
private function onResult3(event:ResultEvent,token:Object):void
{
if(event.result!=null)
{
var Lder:Loader=new Loader();
var ba:ByteArray=event.result as ByteArray;
Lder.loadBytes(ba);// exception is thrown here
doktorResim.bitmapData.draw(Lder);
}
}
Any help, suggestion?
If Java is reading and sending bytes properly, then you need to wait for flex to load all bytes for thats use event complete of LoaderInfo see also Loader Class
var url:String = "http://www.helpexamples.com/flash/images/image2.jpg";
var urlRequest:URLRequest = new URLRequest(url);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete);
loader.load(urlRequest);
addChild(loader);
function loader_complete(evt:Event):void {
var target_mc:Loader = evt.currentTarget.loader as Loader;
target_mc.x = (stage.stageWidth - target_mc.width) / 2;
target_mc.y = (stage.stageHeight - target_mc.height) / 2;
}
Hopes that helps

Categories

Resources