So using Google Drive's API, I am trying to download a file from my drive account. I have followed Google's quickstart guide (https://developers.google.com/drive/web/quickstart/java) and used Google's DriveQuickStart.java to initialize the Drive object.
Everything with the object works correctly (i.e acquiring all the files from my google drive account and displaying their IDs and titles); however, when I tried downloading a file through the input stream of the function Google developed, I keep getting a null exception error.
Here is the code that I am using:
private static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
The problem is that when the method calls file.getDownloadURL(), it returns a null value. According to the documentation, it should return a null value if the file I am trying to download is a native Google Drive file; however, the file that I am downloading is simply a jar file, so it can't be because of the file extension (I also tried it on other formats too).
Why is it returning a null value, and what can I do to resolve this issue? Thank you!
Figured it out.
For anyone else who struggled with this, the answer is really simple:
In the DriveQuickStart.java code, pay attention to this part:
/** Global instance of the scopes required by this quickstart. */
private static final List<String> SCOPES =
Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
And make sure you set it to:
/** Global instance of the scopes required by this quickstart. */
private static final List<String> SCOPES =
Arrays.asList(DriveScopes.DRIVE);
So the only reason why it didn't work was because program did not have the appropriate permission to do so.
Related
I wrote a solution for renaming files, but nothing happens in Android 10, although in 11 and above it is renamed normally.
public class PathDiv {
public static String dev(String path){
return path.replaceAll("^(.*)/.*?$","$1");
}
public static void renameFilesInDir(String path, String dirIn, String ext) {
File checkFile = new File(path);
if (checkFile.isFile()) {
try {
checkFile.renameTo(new File(dirIn, ext));
} catch (Exception e) {
e.printStackTrace();
}
}
}
path: /storage/emulated/0/Music/04. Kasger - Highland.mp3 dirIn: /storage/emulated/0/Music ext: Highland.mp3
PathDiv.renameFilesInDir(songItem.realUri,PathDiv.dev(songItem.realUri),newName.toString())
What's the problem?
In Android 10 and Higher Version of android, you can't Rename or Delete directly.
For Rename or Delete a media file you want to send a request.
Here Read Android Official Document how to create a request
For your information, to Delete a media file Dependency Available here you can use it easily it's created by me
checkFile.renameTo(new File(dirIn, ext)); It Also Works for this you want to add ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION permission in your app but before using this permission please refer to Google Play Police Update
I am using dropbox core api.
// Get files and folder metadata from Dropbox root directory
public static ListFolderResult listFiles(DbxClientV2 client) throws DbxException {
ListFolderResult result = client.files().listFolder("");
while (true) {
for (Metadata metadata : result.getEntries()) {
System.out.println(metadata.getPathLower());
}
if (!result.getHasMore()) {
break;
}
result = client.files().listFolderContinue(result.getCursor());
}
return result;
}
Now the user should be able to list all folders on localhost via /list. How can I do that?
You need first to autheticate the user to dropbox using the dropbox java api
Please look at this, here is everything described clearly Dropbox JAVA API
I am battling with trying to download files using the google drive API. I'm just writing code that should download files from my drive onto my computer. I've finally got to a stage where I am authenticated and can view the file metadata. For some reason, I'm still unable to download files. The downLoadURL I get looks like:
https://doc-04-as-docs.googleusercontent.com/docs/securesc/XXXXXXXXXXXXXX/0B4dSSlLzQCbOXzAxNGxuRUhVNEE?e=download&gd=true
This URl isn't downloading anything when I run my code or when I copy and paste it in a browser. But, in the browser, when i remove the "&gd=true" part of the URL it downloads the file.
My download method is straight out of the google drive API documentation:
public static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
System.out.println("Downloading: "+ file.getTitle());
return service.files().get(file.getId()).executeMediaAsInputStream();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
Anyone know whats going on here?
Thanks in advance.
Since you're using Drive v2, a different approach (also on the documentation) is for you to get the InputStream thru the HttpRequest object.
/**
* Download a file's content.
*
* #param service Drive API service instance.
* #param file Drive File instance.
* #return InputStream containing the file's content if successful,
* {#code null} otherwise.
*/
private static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
I am developing an app to serve as a learning and I'm using Parse (parse.com) as a data source.
I am conducting download all objects of my classes in the parse and saving to a local store that has Parse. The following code snippet that performs one of downloads:
public void noticia_getOrUpdate(boolean isUpdate) throws ParseException {
ParseQuery<Noticia> query = new ParseQuery(Noticia.class);
query.orderByDescending("createdAt");
List<Noticia> lNoticias = null;
try {
if (isUpdate) {
lNoticias = query.whereGreaterThan("updatedAt", this.sPref.ultimaAtualizacao_noticia()).find();
if (!lNoticias.isEmpty())
ParseObject.pinAllInBackground(lNoticias);
} else {
query.whereEqualTo("ativo", true);
lNoticias = query.find();
for (Noticia noticia : lNoticias) {
if (noticia.getUpdatedAt().getTime() > this.sPref.ultimaAtualizacao_noticia().getTime())
this.sPref.atualiza_noticia(noticia.getUpdatedAt());
}
ParseObject.pinAllInBackground(lNoticias);
this.sPref.atualiza_isUpdate(true);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
The problem is I'm downloading all my classes, one is the File type, is a file that works as an image for my news ("Noticia"). I can download and store all on-site data storage, but can not recover using the following code:
public static byte[] NoticiaMidiaRelation(Noticia noticia) {
try {
ParseRelation<Midia> relation = noticia.getImagem();
Midia midia = relation.getQuery().fromLocalDatastore.whereEqualTo("ativo", true).getFirst();
if (midia != null && midia.getFileData() != null)
return midia.getFileData();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
If retreat the "fromLocalDatastore" the query, he seeks the server and brings the file correctly, but do not want to pursue it again, because as said, already have the same image stored in the local data store.
Another way to do would be to get the relationship the media Id, after that perform a search for comparing ObjectId within the local store, but I think there's no way the property "parent". But if any, can be used as a solution.
You can't according to the documentation:
By default, when fetching an obj
ect, related ParseObjects are not fetched
There are work arounds but they might not be practical because by what I understand, you only have one image in your relation per ParseObject in your "Notica" class as you call getFirst(). In this case, using a Pointer would be a better decision but those aren't fetched by default either BUT they are cached to the LocalDatastore. You'll need to add the following code to your query to fetch the Pointer object.
query.include("your_column_key");
I'm using Apache Tapestry v5.3.7 and I already use the normal Tapestry upload component in a form. For a better user experience I try now to integrate Dropzone.js in a normal Tapestry page without any form. The JavaScript integration works fine. The uploaded file data are transferred to my server with a post request and I can access the request with all of its parameters.
My question is now how can I access the binary data of the uploaded file (maybe as InputStream) to save them in my system? I already injected the http request but getInputStream returns a empty stream.
Thanks for any suggestions
/** Code snippet of page java part */
...
#Inject
protected HttpServletRequest _request;
public void onActivate (String rowId) {
String fileName=_request.getParameter("file");
try {
InputStream is=_request.getInputStream();
// if I do read from is it returns -1
// :-(
doSomeSaveStuff(is); // dummy code
}
catch(Exception e) {
e.printStackTrace();
}
}
...
Here's one way to do it:
In template:
<t:form t:id="testForm" class="dropzone">
</t:form>
In page.java
#Inject
MultipartDecoder multipartDecoder;
#Component(id = "testForm")
private Form testForm;
#Inject
RequestGlobals requestGlobals;
void onSubmitFromTestForm() throws ManagerException {
System.out.println("test form invoked");
HttpServletRequest r = requestGlobals.getHTTPServletRequest();
UploadedFile u = multipartDecoder.getFileUpload("file");
The uploaded file contains what you uploaded and you can work with it the way you want.
Note: the HttpServletRequest::getParameterMap() , told me that the handle to to the file is called file which is how I know that passing file to getFileUpload makes the decoder correctly parse the multipart/post