IBM MobileFirst Java Adapter (Hybrid Application) download huge file - ibm-mobilefirst

I'm trying to pull a 20MB file from MFP server. So, I wrote the following code in my client application.
var resourceRequest = new WLResourceRequest("/adapters/AdapterExample/users/getUpdate",WLResourceRequest.POST);
resourceRequest.send().then(function(result){
Logger("Hello Im here ! : " + result.responseJSON.isSuccessful);
},function(error){
Logger("Im error ! : " + error);
});
Unfortunately, it shows the following error in JSON format:
JSON Result :{"isSuccessful":false,"errors":["Data size exceeds maximum permitted value of 10Mb."]}
Is there any data size limitation for Java adapter which data size cannot more than 10 MB?
Remarks: Code below is my Java Adapter sample code:
#POST
#Path("/getUpdate")
public String getUpdate() throws IOException{
JSONObject obj = new JSONObject();
java.nio.file.Path path = Paths.get("/Users/abc/Documents/example.zip");
byte[] fileData = Files.readAllBytes(path);
obj.put("fileName", path.getFileName().toString());
obj.put("size", Base64.encodeBase64String(fileData).length());
return obj.toString();
}

From MobileFirst-perspective, Java adapters impose no such file size limits. I suggest to consider a network issue, such as some vendor your request is going through that imposes this limitation.

Related

Azure service bus Message deserialize broken in core conversion

So, I've created a new Azure Functions project v3 and am porting over a subset of functions from v1 that was running on 4.6.2, while retiring the rest as obsolete. Unfortunately in the change from BrokeredMessage to Message due to changing from Microsoft.ServiceBus.Messaging to Microsoft.Azure.ServiceBus the following deserialization method is now failing with:
There was an error deserializing the object of type stream. The input source is not correctly formatted.
The problem is right there in the error, but Im not sure what the correct new approach is, its a bit unclear.
Serialize
public static Message CreateBrokeredMessage(object messageObject)
{
var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageObject)))
{
ContentType = "application/json",
Label = messageObject.GetType().Name
};
return message;
}
Deserialize
public static T ParseBrokeredMessage<T>(Message msg)
{
var body = msg.GetBody<Stream>();
var jsonContent = new StreamReader(body, true).ReadToEnd();
T updateMessage = JsonConvert.DeserializeObject<T>(jsonContent);
return updateMessage;
}
Object
var fileuploadmessage = new PlanFileUploadMessage()
{
PlanId = file.Plan_Id.Value,
UploadedAt = uploadTimeStamp,
UploadedBy = uploadUser,
FileHash = uploadedFileName,
FileName = file.Name,
BusinessUnitName = businessUnitName,
UploadedFileId = uploadedFile.Id
};
```
Message.GetBody<T>() is an extension method for messages sent using the legacy Service Bus SDK (WindowsAzure.ServiceBus package) where BrokeredMessage was populated with anything other than Stream. If your sender sends an array of bytes as you've showed, you should access it using Message.Body property.
In case your message is sent as a BrokeredMessage, the receiving code will need to select either of the methods based on some information to indicate how the message was originally sent.

Power App - generate PDF

I got an assignment to see if I can make power app that will generate some PDF file for end user to see.
After through research on this topic I found out that this is not an easy to achieve :)
In order to make power app generate and download/show generated pdf I made these steps:
Created power app with just one button :) to call Azure function from step 2
Created Azure function that will generate and return pdf as StreamContent
Due to power app limitations (or I just could not find the way) there was no way for me to get pdf from response inside power app.
After this, I changed my Azure function to create new blob entry but know I have problem to get URL for that new entry inside Azure function in order to return this to power app and then use inside power app Download function
My Azure function code is below
using System;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using Aspose.Words;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, Stream outputBlob)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
var dataDir = #"D:/home";
var docFile = $"{dataDir}/word-templates/WordAutomationTest.docx";
var uid = Guid.NewGuid().ToString().Replace("-", "");
var pdfFile = $"{dataDir}/pdf-export/WordAutomationTest_{uid}.pdf";
var doc = new Document(docFile);
doc.Save(pdfFile);
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(pdfFile, FileMode.Open);
stream.CopyTo(outputBlob);
// result.Content = new StreamContent(stream);
// result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
// result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(pdfFile);
// result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
// result.Content.Headers.ContentLength = stream.Length;
return result;
}
I left old code (the one that streams pdf back under comments just as reference of what I tried)
Is there any way to get download URL for newly generated blob entry inside Azure function?
Is there any better way to make power app generate and download/show generated PDF?
P.S. I tried to use PDFViewer control inside power app, but this control is completely useless cause U can not set Document value via function
EDIT: Response from #mathewc helped me a lot to finally wrap this up. All details are below.
New Azure function that works as expected
#r "Microsoft.WindowsAzure.Storage"
using System;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using Aspose.Words;
using Microsoft.WindowsAzure.Storage.Blob;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, CloudBlockBlob outputBlob)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
var dataDir = #"D:/home";
var docFile = $"{dataDir}/word-templates/WordAutomationTest.docx";
var uid = Guid.NewGuid().ToString().Replace("-", "");
var pdfFile = $"{dataDir}/pdf-export/WordAutomationTest_{uid}.pdf";
var doc = new Document(docFile);
doc.Save(pdfFile);
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(pdfFile, FileMode.Open);
outputBlob.UploadFromStream(stream);
return req.CreateResponse(HttpStatusCode.OK, outputBlob.Uri);
}
REMARKS:
Wee need to add "WindowsAzure.Storage" : "7.2.1" inside project.json. This package MUST be the same version as one with same name that is in %USERPROFILE%\AppData\Local\Azure.Functions.Cli
If you change your blob output binding type from Stream to CloudBlockBlob you will have access to CloudBlockBlob.Uri which is the blob path you require (documentation here). You can then return that Uri back to your Power App. You can use CloudBlockBlob.UploadFromStreamAsync to upload your PDF Stream to the blob.

Delay in create JSONObject from org.restlet.repsonse

I am facing issue while getting json data from Response and creating JSONobject.
Issue : Getting delay to create JSONObject. [Approx. 1-2 min ]
This is the code I am using to create the JOSNObject.
Representation rep = response.getEntity();
rep.setCharacterSet(CharacterSet.UTF_8); JsonRepresentation
jsonRep = new JsonRepresentation(rep);
JSONObject jsonObj = jsonRep.getJsonObject();
Jar Details : 1.6 (org.restlet.jar)
Please help me.

How to send images through Worklight server without base64 encoding?

I`m trying to find out how to send images to my back-end server using Worklight adapters.
I know that I can send them through Worklight adapters using Base64 encoding but this implies in around 30% more traffic between the servers and some undesired processing overhead.
For now I`m using the Phonegap FileTransfer library as I show below, but this creates a directly connection between the client and the back-end server not going through Worklight server as I want.
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var headers = {"Content-Type": "image/jpeg"};
options.headers = headers;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI(host + "/images"), imageUploadSuccess, imageUploadFail, options);
function imageUploadSuccess(r) {
WL.Logger.debug("Submit success! HTTP Status Code = " + r.responseCode);
WL.Logger.debug("Response = " + r.response);
WL.Logger.debug("Bytes sent = " + r.bytesSent);
$.mobile.changePage('#SuccessPage');
}
function imageUploadFail(error) {
WL.Logger.debug("submit error! source = " + error.source);
WL.Logger.debug("target = " + error.target);
$.mobile.changePage('#FailPage');
}
Is there a way that I can do that?
Thank you in advance.
-- Edit --
Another problem that occurs is that when my backend server receives the file, it seems corrupted and cannot be readed as an image.
At this time, Worklight adapters do not support sending data in binary form.
This means that currently your only option is the one you do not like, which is to base64 encode the image file and store the resulting string in the database and when you need to use it, to base64 decode it.

How to send canvas image large size from silverlight to WCF service

I have a large size byte[] formed from silverlight Canvas using following code
var img = new WriteableBitmap(cnvControlHolder, null);
var outStream = new MemoryStream();
EncodeJpeg(img, outStream);
Now I want to send this to WCF service to form image from this byte array & save it as an image on server side so that I can consume it in SSRS. My problem is as the byte[] is big I get the classic Method not found from WCF service.
I read in few links that WCF streaming would be one option, but could not find any sample on the net. My service method is like this:
public bool Upload(Stream image)
{
FileStream fileStream = null;
BinaryWriter writer = null;
var filePath = HttpContext.Current.Server.MapPath(".") + #"\" +
ConfigurationManager.AppSettings["PictureUploadDirectory"] + #"\Diagram.jpeg";// +image.ImageName;
if (image!=null)
{
//return ByteArrayToFile(filePath, image.Imagestream);
fileStream = File.Open(filePath, FileMode.Create);
writer = new BinaryWriter(fileStream);
writer.Write("Diagram.jpeg");
}
return false;
}
and client call is this :
var img = new WriteableBitmap(canvas1, null);
var outStream = new MemoryStream();
EncodeJpeg(img, outStream); //custom library to compress into jpeg
var client = new Service1Client();
client.UploadCompleted += new EventHandler<UploadCompletedEventArgs>(client_UploadCompleted);
client.UploadAsync(outStream.ToArray());
Can somebody suggest some sample or any other solution to fix my issue.
I recently implemented a very similar solution in Silverlight. The solution involves:
Dividing the large byte[] into n chunks of size that can be sent via a web service call
Making a web call to the service, registering a file upload request for n chunks, and requesting a guid from the service.
Making n web calls to the service and uploading each chunk, supplying the guid and the ordinal of the chunk (the chunks may arrive out of sequence).
Once the server receives all n chunks, it combines the chunks and writes the data into a file.
I hope this can help to get you started.