How to import SFB file in runtime from local storage? - local

I would like to render a file(andy.sfb) in ARcore. It is possible to get this file from https:// and file://. Traditionally the file:// is allocated to files in the assets folder , which is packaged with the app. However, the aim is to download the 3D model, and then give the path (URI) from local device storage, this could be something like /storage/emulated/0/Download/andy.sfb.
SFB stands for SceneForm Binary.
My challenge has been to render the model runtime from local device storage.
The issue is presented here in detail
File file = new File("file:///storage/emulated/0/Download/andy.sfb");
Callable callable = () -> {
InputStream inputStream = new FileInputStream(file);
return inputStream;
};
FutureTask task = new FutureTask<>(callable);
new Thread(task).start();
ModelRenderable.builder()
.setSource(this, callable)
.build()
.thenAccept(renderable -> andyRenderable = renderable)
.exceptionally(
throwable -> {
Toast toast =
Toast.makeText(this, "Unable to load andy renderable", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
return null;
});

You can download .sfb file from server to local storage and load that .sfb file.
To load object from local storage use below code:
ModelRenderable.builder()
.setSource(this, Uri.fromFile(new File(path + fileName)))
.build()
.thenAccept(renderable -> {
andyRenderable = renderable;
})
.exceptionally(
throwable -> {
Toast toast =
Toast.makeText(this, "Unable to load andy renderable", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
return null;
});

Related

Downloading Docusign PDF in Grails, file corrupted

Using Groovy 1.8.6 and Grails 2.1.0
Using embedded API, after user signs document, browser is redirected back to my app. Using "Get Envelope Documents and Certificate" API to download document to server. URL format:
"${baseUrl}/envelopes/${envelopeId}/documents/combined"
Code snippet (with minor details removed):
private void getDocument(requestUrl) {
def connection = urlConnect(requestUrl, null, "GET")
if (connection.responseCode == 200) {
savePDF(envelopeId, connection.inputStream)
}
}
private void savePDF(envelopeId, inputStream) {
String filePath = getSavedPDFPath(envelopeId)
def pdfWriter = new File(filePath).newWriter()
pdfWriter << inputStream
pdfWriter.close()
}
What happens is that the resulting file is not 100% correct, Adobe Reader complains that "at least one signature is invalid". Reader at least knows that the file was signed by DocuSign, Inc., and can show details about the certificate.
Per the Question's comment thread, the issue was being caused by the way the file was being saved. Using this code instead, the file saves / opens correctly:
private void savePDF(envelopeId, connection)
{
FileOutputStream fop = null;
File file;
String filePath = getSavedPDFPath(envelopeId);
try {
file = new File(filePath);
fop = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int numRead;
while((numRead = connection.getInputStream().read(buffer)) > 0)
{
fop.write(buffer, 0, numRead);
}
fop.flush();
fop.close();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}

PCLStorage and binary data

I'm just new in this PCL libraries, I'm developing an iPhone app with Xamarin and I can't find the way to save it on the phone. The closest I get is with PCLStorage but he only saves text.
There is another way that I can save binary files with other procedure.
Thank you.
foreach (images element in json_object)
{
//var nameFile = Path.Combine (directoryname, element.name);
try{
IFile file = await folder_new.GetFileAsync(element.name);
}catch(FileNotFoundException ex ){
RestClient _Client = new RestClient(element.root);
RestRequest request_file = new RestRequest("/images/{FileName}");
request_file.AddParameter("FileName", element.name, ParameterType.UrlSegment);
_Client.ExecuteAsync<MemoryStream>(
request_file,
async Response =>
{
if (Response != null)
{
IFolder rootFolder_new = FileSystem.Current.LocalStorage;
IFile file_new = await rootFolder_new.CreateFileAsync(element.name,CreationCollisionOption.ReplaceExisting);
await file_new.WriteAllTextAsync(Response.Data);
}
});
}
}
Use the IFile.OpenAsync method to get a stream which you can use to read/write binary data. Here's how you would read a file:
IFile file = await folder_new.GetFileAsync(element.name);
using (Stream stream = await file.OpenAsync(FileAccess.Read))
{
// Read stream and process binary data from it...
}

Mobile web application: download attachments on iOS

In my mobile web application i have one page within user can view attachments.
The attachment can be any type of file (jpg,png,txt,doc,zip, etc).
The view attachment action is in the form of <a> tag that points to an aspx file that process the request.
HTML:
<a class="attachBtn" href="_layouts/ViewFile.aspx?messageAttachmentInstanceId={some id}"></a>
ViewFile.aspx:
public partial class ViewFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.IO.BinaryWriter bw = null;
System.IO.MemoryStream ms = null;
System.IO.StreamReader sr = null;
try
{
string contentType = string.Empty;
byte[] content = null;
string fileName = string.Empty;
if (!string.IsNullOrEmpty(Request.QueryString["messageAttachmentInstanceId"]) &&
!string.IsNullOrEmpty(Request.QueryString["messageInstanceId"]))
{
int messageInstanceId = Int32.Parse(Request.QueryString["messageInstanceId"]);
Guid attachmentInstanceId;
GuidUtil.TryParse(Request.QueryString["messageAttachmentInstanceId"], out attachmentInstanceId);
MessageInstance messageInstance = WorkflowEngineHttpModule.Engine.GetService<IMessagingService>()
.GetMessageInstance(messageInstanceId);
if (messageInstance != null)
{
MessageAttachmentInstance attachmentInstnace = messageInstance.Attachments[attachmentInstanceId];
contentType = attachmentInstnace.ContentType;
fileName = attachmentInstnace.FileName;
content = attachmentInstnace.Content;
}
}
this.Response.ContentType = contentType;
string headerValue = string.Format("attachment;filename={0}",
this.Server.UrlPathEncode(fileName));
Response.AddHeader("content-disposition", headerValue);
bw = new System.IO.BinaryWriter(this.Response.OutputStream);
bw.Write(content);
}
catch (Exception ex)
{
LogError("ViewFile.aspx, "
+ ex.InnerException, ex);
}
finally
{
if (sr != null)
sr.Close();
if (ms != null)
ms.Close();
if (bw != null)
bw.Close();
}
}
}
The Problem:
in Android devices when user click on attachment the file is downloaded automatically which is the desirable behavior because the user can open the file later with any tool he wants and even if the file type is not supported user can later on download a tool which can open it.
but in iOS devices the file is not downloaded but instead redirects to ViewFile.aspx and tries to open the file within the browser and if the file type is not supported it shows alert: "safari cannot download this file".
even if the file type is supported i want it to be downloaded and not open by default.
How can i achieve this behavior?
AFAIK, you cannot download files on iOS.
Known files that Safari (or any app that has registered a file type, e.g. ZIP) supports will open or show a dialog letting the user choose how to open the file.
You can't control the behavior from your web app/site.

How does one 'read' a file from a Dart VM program?

How does one 'read' a file from a Dart program ?
http://api.dartlang.org/index.html
Dart would be running on the client-side and so taking files as input should be allowed.
You can find a usage of files in Dart's testing framework:
status_file_parser.dart (search for 'File').
In short:
File file = new File(path);
if (!file.existsSync()) <handle missing file>;
InputStream file_stream = file.openInputStream();
StringInputStream lines = new StringInputStream(file_stream);
lines.lineHandler = () {
String line;
while ((line = lines.readLine()) != null) {
...
};
lines.closeHandler = () {
...
};
Note that the API is not yet finalized and could change at any moment.
Edit: API has changed. See Introduction to new IO
Your question implies you want to do this from the client-side, that is, the browser. The dart:io library only works in the stand-alone VM on the command line.
If you do want to read a file from within the VM, there's now an easier way:
import 'dart:io';
main() {
var filename = new Options().script;
var file = new File(filename);
if (!file.existsSync()) {
print("File $filename does not exist");
return;
}
var contents = file.readAsStringSync();
print(contents);
}
If you do not want to block while the whole file is read, you can use the async version of readAsString which returns a Future:
file.readAsString().then((contents) {
print(contents);
});

Accessing the 'Media' directory of a Blackberry within the JDK

Trying to use JSR 75 to access media saved under the '/home/video/' directory on the device. Using Blackbery JDK 4.6.1. Single line of code throws a 'FileSystem IO Error' Exception. Which is, as usual, unhelpful in the extreme.
fconn = (FileConnection)Connector.open("file:///home/user/videos/"+name, Connector.READ);
Has anyone tried to do this? I can open files within my jar, but can't seem to access the media folder. I have the javax.microedition.io.Connector.file.read permission set and my appplication is signed.
There are two kind of filesystems on BlackBerry - SDCard and store. You have to use one of them, defining it in the path. Standard directory on SDCard where video, music etc stored is "file:///SDCard/BlackBerry".
String standardPath = "file:///SDCard/BlackBerry";
String videoDir = System.getProperty("fileconn.dir.videos.name");
String fileName = "video.txt";
String path = standardPath+"/"+videoDir+"/"+fileName;
String content = "";
FileConnection fconn = null;
DataInputStream is = null;
ByteVector bytes = new ByteVector();
try {
fconn = (FileConnection) Connector.open(path, Connector.READ);
is = fconn.openDataInputStream();
int c = is.read();
while(-1 != c)
{
bytes.addElement((byte) (c));
c = is.read();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
content = new String(bytes.toArray());
add(new RichTextField(content));
See also
SUN Dev Network - Getting Started with the FileConnection APIs
RIM Forum - Some questions about FileConnection/JSR 75
Use System.getProperty("fileconn.dir.memorycard") to check if SDCard available
How to save & delete a Bitmap image in Blackberry Storm?

Resources