AWS Download function issue with file path - java

I have implemented a function to download aws s3 files using the following code:
public void credentialsProvider()
{
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(), "us-east-2:xxxxxx-xxxxx-xxxxx-xxxx-xxxxxxx", Regions.US_EAST_2
);
setAmazonS3Client(credentialsProvider);
System.out.println("setAmazonS3Client done");
}
public void setAmazonS3Client( CognitoCachingCredentialsProvider credentialsProvider)
{
s3 = new AmazonS3Client(credentialsProvider);
s3.setRegion(Region.getRegion(Regions.US_EAST_2));
}
public void setTransferUtility()
{
transferUtility = new TransferUtility(s3, getApplicationContext());
System.out.println("setTransferUtility done");
}
public void setFileDownload()
{
final String path = this.getFilesDir().getAbsolutePath();
File myFile = new File(path);
TransferObserver transferObserver = transferUtility.download("sample-bucket-001", "images-4.jpeg", myFile);
transferObserverListener(transferObserver);
}
public void transferObserverListener(TransferObserver transferObserver)
{
transferObserver.setTransferListener(new TransferListener() {
#Override
public void onStateChanged(int id, TransferState state) {
System.out.println("onStateChanged: "+ state);
if(state == TransferState.FAILED || state == TransferState.WAITING_FOR_NETWORK){
}
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
int percentage = (int)(bytesCurrent/bytesTotal * 100);
System.out.println("percentage: "+ percentage);
}
#Override
public void onError(int id, Exception ex) {
System.out.println("Error faced: "+ ex.toString());
}
});
}
As I try to execute the following code I get the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxxx.xxxxxxxx/com.xxxxxx.xxxxxxxx.Activity}: java.lang.IllegalArgumentException: Invalid file: /data/user/0/com.xxxxxx.xxxxxxxx/files/
I cannot save the file on external storage as I prefer to have them hidden and protected, and deleted in case the app got deleted. I used to use the path to save files on it, that are directly loaded from the internet and no problem there.
Kindly advise on the matter.

The file path supplied to TransferUtility needs to include a file name, e.g.:
final String path = this.getFilesDir().getAbsolutePath() + "images-4.jpeg";

I have finally found the solution to the question asked, which simple using a path that is totally new, unused previously, so it can create the folder that where it will store the downloaded picture or file.
final String path = this.getFilesDir().getAbsolutePath()+"/zip";
I wish Amazon's feedback could be a bit more specific than just 'invalid file'.

Related

how to get file path from content uri in android?

So my problem is that I want to get file path from content uri, I had googled but I didn't get any of the solutions, please help me out of this problem.
here is my code what I have tried
Intent getPdf = getIntent();
String action = getPdf.getAction();
String type = getPdf.getType();
Log.d("sdsfgsdfsdf",""+type);
if (Intent.ACTION_SEND.equals(action) ||Intent.ACTION_VIEW.equals(action) || type != null){
if (type.startsWith("application/pdf")){
viewPdf(getPdf,action);
}
}
private void viewPdf(Intent getPdf, String action) {
Uri uri = Uri.parse(getPdf.getData().toString());
if (uri != null) {
File file = new File(String.valueOf(uri.getPath()));
name = file.getName();
path = String.valueOf(uri);
Log.d("sdsfgsdfsdf",""+name);
}else {
// Toast.makeText(this, ""+ uri.toString(), Toast.LENGTH_SHORT).show();
}
}
This is the output
content://com.android.externalstorage.documents/document/primary%3AWhatsApp%2FMedia%2FWhatsApp%20Documents%2FAJAX_And_PHP_Building_Responsive_Web_Applications-(2006).pdf
but I want to get file:// path instead of content uri
It is unclear where you got that uri that content scheme from.
You should have started with that
Further it makes no sense trying to get a path for it as mostly you will not have read access then.
Further you did not tell why you want a path
Use the uri! Use the content scheme.
You can use PickiT library for get path from URI.
Sample code for how to use it.
PickiT pickiT = new PickiT(this, new PickiTCallbacks() {
#Override
public void PickiTonUriReturned() {
}
#Override
public void PickiTonStartListener() {
}
#Override
public void PickiTonProgressUpdate(int progress) {
}
#Override
public void PickiTonCompleteListener(String filePath, boolean wasDriveFile, boolean wasUnknownProvider, boolean wasSuccessful, String Reason) {
if (wasSuccessful) {
// Use file path
}
}
#Override
public void PickiTonMultipleCompleteListener(ArrayList<String> paths, boolean wasSuccessful, String Reason) {
}
}, this);
pickiT.getPath(uri, Build.VERSION.SDK_INT);

Uploading a file from android phone that contains a space in its path

I'm having a hard time passing files with spaces in their names into Twilio chat.
Forgetting about the fact that I'm using Twilio, and just concentrating that I'm trying to upload a file from within the Android phone. I have an image on my android phone which I found its path as /Internal storage/Download/4893079.jpg
Below is the full code:
public void testing() {
Messages messagesObject = channel.getMessages();
try {
messagesObject.sendMessage(
Message.options()
.withMedia(new FileInputStream("/Internal%20storage/Download/4893079.jpg"), "image/jpeg")
.withMediaFileName("4893079.jpg")
.withMediaProgressListener(new ProgressListener() {
#Override
public void onStarted() {
System.out.println("Upload started");
}
#Override
public void onProgress(long bytes) {
System.out.println("Uploaded " + bytes + " bytes");
}
#Override
public void onCompleted(String mediaSid) {
System.out.println("Upload completed");
}
}),
new CallbackListener<Message>() {
#Override
public void onSuccess(Message msg) {
System.out.println("Successfully sent MEDIA message");
}
#Override
public void onError(ErrorInfo error) {
System.out.println("Error sending MEDIA message");
}
});
} catch (FileNotFoundException e) {
System.out.println("FAILED HORRIBLY");
System.out.println(e);
e.printStackTrace();
}
}
However running the app I end up with the error,
java.io.FileNotFoundException: /Internal%20storage/Download/4893079.jpg (No such file or directory)
As shown I've tried replacing space with %20, but that didn't work. I've also tried \ , \\ . However non of them worked. I've looked at Opening a local Android File with spaces, Save file in Android with spaces in file name.
How should I be replacing the space?
You need to get the actual path programmatically. So the real path is
Environment.getExternalStorageDirectory().toString() + "/Download/4893079.jpg"
Internal storage is just something the user sees, but not a real path on the machine.

Download multiple concurrent files

I need download multiple files in one time (About 100 files)
It does not matter whether the download is synchronized
And the important thing is that all files be downloaded.
My code for getting urls and file names:
for (int i = 0; i < AssetData.size(); i++){
String item = AssetData.get(i).toString();
String name[] = item.split("/");
String Url = setting.Main_Domain+"/"+item;// Url for downloading
String fname =name[name.length-1] ;// File name like: test.txt
File file2 = new File(getFilesDir(),item.replace(fname,"")); // Parent File like: data/user/0/com.test.app/data/
if(!file2.exists()){file2.mkdir();}
}
The size of the files is small and all together is about 3 megabytes.
You can implement your code with using this library. You can download multiple files concurrent or you can start next download after one is completed.
https://github.com/MindorksOpenSource/PRDownloader
This is how your code will look
int downloadId = PRDownloader.download(url, dirPath, fileName)
.build()
.setOnStartOrResumeListener(new OnStartOrResumeListener() {
#Override
public void onStartOrResume() {
}
})
.setOnPauseListener(new OnPauseListener() {
#Override
public void onPause() {
}
})
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel() {
}
})
.setOnProgressListener(new OnProgressListener() {
#Override
public void onProgress(Progress progress) {
}
})
.start(new OnDownloadListener() {
#Override
public void onDownloadComplete() {
}
#Override
public void onError(Error error) {
}
});
Isn't this simple. :)
This seems to me ion is a pretty elegant solution for you. It's easy to use and has many futures like connection pooling and reuse via HTTP Connection...

Opening file geodatabase using ESRI android API

for some time I am trying to open file godatabase on android using ESRI api in version 10.2.
I have a file godatabase made with Arccatalog 10.1. It contains one layer. I can open it in Arcmap so everything looks fine here.
The geodatabase is in folder named android.gdb
I copied it to microSD card and tried to open it using this code:
new com.esri.core.gdb.Geodatabase("/mnt/sdcard2/android.gdb");
The "/mnt/sdcard2/android.gdb" file exists and is a folder and I have read and write permissions.
I get a RuntimeException with the message that the goedatabase file could not be opened.
Anyone had similiar issues with that ?
The ESRI runtime api for android wont be able to open that kind of database. It uses a proprietary version of a geodatabase built in SQLLite. You will need to publish a service in ArcGisOnline or ArcServer 10.2 and call the GeodatabaseSyncTask object in order to get a version of your database in the right format onto the device. On your published feature service you will need to make sure Sync is enabled. Then you can utilize this code to call your feature service and store it locally. This code is based on this ESRI sample -- https://developers.arcgis.com/android/sample-code/offline-editor/
public void LoadGdb(UserCredentials credentials, Polygon extent, SpatialReference spatRef){
mapExtent = extent;
mapSpatialRef = spatRef;
String replicaUrl = callingActivity.getResources().getString(R.string.feature_service_url);
gdbTask = new GeodatabaseSyncTask(replicaUrl, credentials);
gdbTask.fetchFeatureServiceInfo(new CallbackListener<FeatureServiceInfo>() {
#Override
public void onError(Throwable e) {
Log.e(TAG, "", e);
}
#Override
public void onCallback(FeatureServiceInfo objs) {
if (objs.isSyncEnabled()) {
requestGdbInOneMethod(gdbTask, mapExtent, mapSpatialRef);
}
}
});
}
protected void requestGdbInOneMethod(GeodatabaseSyncTask geodatabaseSyncTask, Polygon extent, SpatialReference spatRef) {
GenerateGeodatabaseParameters params = new GenerateGeodatabaseParameters({0, 1}, extent,
spatRef, true, SyncModel.LAYER, spatRef);
CallbackListener<String> gdbResponseCallback = new CallbackListener<String>() {
#Override
public void onCallback(String obj) {
try {
// This onCallback gets called after the generateGeodatabase
// function on the GeodatabaseSyncTask is called.
// You can store a reference to this database or you can load it
// with your code and point it to the gdbFileName location
Geodatabase myGeodatabase = (Geodatabase)obj;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void onError(Throwable e) {
Log.e(TAG, "", e);
}
};
GeodatabaseStatusCallback statusCallback = new GeodatabaseStatusCallback() {
#Override
public void statusUpdated(GeodatabaseStatusInfo status) {
showMessage(callingActivity, status.getStatus().toString());
}
};
// !! THE gdbFileName is a string of the path and filename
// where the geodatabse will be stored.
geodatabaseSyncTask.generateGeodatabase(params, gdbFileName, false, statusCallback, gdbResponseCallback);
}
To load a local file you need to use ArcGIS Desktop 10.2.1 or higher to generate a Runtime Geodatabase file with a *.geodatabase file extension. See the instructions here: http://resources.arcgis.com/en/help/main/10.2/index.html#//00660000045q000000

Not able to get the right file path after uploading

I am able to upload a picture in my webapp with the struts2 framework, but i am not able to understand the path.
how to get the path of the image as a URL, so that i can use it for further processing in <img src="url"/>.
This is my action class source code and i have mentioned the URL returned in comments, but the URL does not make any sense to me. How can i decrypt it to actual URL ?
public class AddItemAction extends ActionSupport implements
ServletContextAware {
#Override
public void setServletContext(ServletContext arg0) {
// TODO Auto-generated method stub
}
File pic;
String picContentType;
String picFileName;
public File getPic() {
return pic;
}
public void setPic(File pic) {
this.pic = pic;
}
public String getPicContentType() {
return picContentType;
}
void setPicContentType(String picContentType) {
System.out.println("Setting conteent tuype" + picContentType);
this.picContentType = picContentType;
}
public void setPicFileName(String picFileName) {
this.picFileName = picFileName;
}
public String getPicFileName() {
return picFileName;
}
public String execute() {
File file = getPic();
String strFinalFullPathFileName = file.getAbsolutePath() + File.separator + picFileName;
System.out.println(strFinalFullPathFileName);
// This is the path returned
/*
* /Users/..../Catalina/localhost/.../upload_584d2719_13d5fdf593d__8000_00000000.tmp/IMG_20120526_083438.jpg
*
*
*/
return SUCCESS;
}
}
Uploaded artifacts should be stored outside the web app structure.
In addition, by default, the file upload interceptor deletes the temporary files created during the upload process. That should either be turned off, or the file should be copied to a known location so they can be either (a) streamed back via an action, or (b) served directly if you set up your container to serve static assets outside of the normal web structure.
seems like you are uploading your file to a temp folder, what you should do is move this file to a folder inside your web app
you case use request.getServletContext().getRealPath(YOUR_PATH) to get a path where to move the file
YOUR_PATH being something like "/uploadimage/img.png" => uploadimage being a folder directly in you webapp

Categories

Resources