Download Revision history files from Google Drive - java

I am using the following code to get all the revisions on a particular file uploaded in Google Drive. I am able to get the link and download the versions but when any other user access the application he is not able to download the file from the provided link.
To get all Revision of File:
private static List<Revision> retrieveRevisions() {
try {
String fileId="0BylJDrKIrQebRkpnNEFmZVF3Q3c";
Drive service= GoogleDriveUtil.getDrive();
System.out.println(service+"Drive is Here");
RevisionList revisions = service.revisions().list(fileId).execute();
List<Revision> revisionList = revisions.getItems();
for(Revision revision: revisionList){
System.out.println("Revision "+revision.getOriginalFilename()+" "+revision.getId()+"revision.getDownloadUrl()");
}
return revisionList;
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}
return null;
}
Suggestions will be appreciated

Related

File not being renamed in Android 10

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

Android Studio NoSuchFileException

I've finished an app and have been attempting to have that app log some data in a text file. I have a few questions about creating files and file paths with Android Studio. I'm not well versed in the editor so perhaps my questions are simple. I'm logging the data in an activity that extends MainActivity, declared as LoggerActivity.
public class LoggerActvitivty extends MainActivity{
public boolean bNewUser = true;
public String sFileName;
public void writeToFile(HashMap hmSaleToSave) {
if (bNewUser) {
System.out.println(hmSaleToSave);
sFileName = Environment.DIRECTORY_DOWNLOADS + "/Sales-" + LocalDateTime.now() + ".txt";
try {
if(!Files.exists(Paths.get(sFileName))) {
Files.createFile(Paths.get(sFileName));
Files.write(Paths.get(sFileName), sFileName.getBytes(StandardCharsets.UTF_8));
}
System.out.println("FILE WRITE EXECUTED");
System.out.println("Location" + sFileName);
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
}
}
Nothing crash's, but I believe I'm providing a null directory resulting in this logcat error
W/System.err: java.nio.file.NoSuchFileException: Download/Sales-2021-08-16T07:44:36.321.txt
I would like the logs to go to my tablets download directory. My first question is should I be using a different method to get my directory rather than through Enviornment.DIRECTORY_DOWNLOADS? Additionally if the path doesn't exist Files.createFile(....) should create the path too? Or does that just create the file at the specified path (sFileName)?

Load Dropbox files into JList Maven Java NetBeans?

I have created a Maven NetBeans project for Dropbox and I need to call up the files in a folder from Dropox and display them in a JList on the interface.
I am able to print them out in the output using (System.out.println()) the following:
public void GetFiles()
{
try
{
MainEmpOperations MEMPops = new MainEmpOperations();
// Get files and folder metadata from Dropbox root directory
ListFolderResult result = client.files().listFolder("/Employees");
while (true) {
for (Metadata metadata : result.getEntries()) {
System.out.println(metadata.getPathLower());
}
if (!result.getHasMore()) {
break;
}
result = client.files().listFolderContinue(result.getCursor());
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
The coding that I have tried to use for loading the files into the JList is similar to the above coding where I will be using DefaultListModel.
Here is the coding that I have done so far but it does not list the files in the JList.
public void GetFiles()
{
try
{
MainEmpOperations MEMPops = new MainEmpOperations();
// Get files and folder metadata from Dropbox root directory
ListFolderResult result = client.files().listFolder("/Employees");
DefaultListModel modelListFiles = new DefaultListModel();
while (true) {
for (Metadata metadata : result.getEntries()) {
modelListFiles.addElement(metadata.getPathLower());
}
if (!result.getHasMore()) {
break;
}
result = client.files().listFolderContinue(result.getCursor());
MEMPops.List_CloudFiles.setModel(modelListFiles);
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Please could someone please help me out, and help me load the files names of the file into the JList.
Much appreciated
I managed to figure it out.
The way in which it needs to work is that the adding of the element and the setting of the model will need to be done straight after each other. placing the set model after the if statement results in the model being cleared or it becomes empty.
Therefore the following coding will work for listing of the files in a JList.
PLEASE NOTE: the rest of the other coding needed for connection and management from dropbox is on dropbox developers website.
CODING THAT WORKS:
public void GetFiles()
{
try
{
// Get files and folder metadata from Dropbox root directory
//please note the employees is a folder that is on dropbox
ListFolderResult result = client.files().listFolder("/Employees");
DefaultListModel modelListFiles = new DefaultListModel();
while (true) {
for (Metadata metadata : result.getEntries()) {
//get name just returns the name of the file and getPathLower() is used for getting the directory and the filename together.
modelListFiles.addElement(metadata.getName());
List_CloudFiles.setModel(modelListFiles);
}
if (!result.getHasMore()) {
break;
}
result = client.files().listFolderContinue(result.getCursor());
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Like (upvote or mark as helpful) if this answer that I posted to my own question helps you out as well.

Google Drive for Android SDK Doesn't List Files

I've got a really odd problem with the Google Drive Android SDK. I've been using it for several months now, and until last week it performed perfectly. However, there is now a really odd error, which doesn't occur all the time but does 9 out of 10 times.
I'm trying to list the user's files and folders stored in a particular Google Drive folder. When I'm trying to use the method Drive.files().list().execute(), 9 out of 10 times literally nothing happens. The method just hangs, and even if I leave it for an hour, it just remains doing... nothing.
The code I'm using is below - all of this being run within the doInBackground of an AsyncTask. I've checked credentials - they are all fine, as is the app's certificate's SHA1 hash. No exceptions are thrown. Google searches have yielded nothing. Here is the particular bit of code that's bothering me:
try {
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
SettingsActivity.this, Arrays.asList(DriveScopes.DRIVE));
if (googleAccountName != null && googleAccountName.length() > 0) {
credential.setSelectedAccountName(googleAccountName);
Drive service = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
service.files().list().execute(); // Google Drive fails here
} else {
// ...
}
} catch (final UserRecoverableAuthIOException e) {
// Authorisation Needed
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
startActivityForResult(e.getIntent(), REQUEST_AUTHORISE_GDRIVE);
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account due to Exception after trying to show the Google Drive authroise request intent, as the UserRecoverableIOException was originally thrown. Error message:\n" + e.getMessage());
}
}
});
Log.d("SettingsActivity: Google Drive", "UserRecoverableAuthIOException when trying to add Google Drive account. This is normal if this is the first time the user has tried to use Google Drive. Error message:\n" + e.getMessage());
return;
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account. Error message:\n" + e.getMessage());
return;
}
I'm using Drive API v2. Thanks everyone!
Edit
Having played around a bit more, it turns out this isn't for just listing files. Trying to interact with any file on Google Drive behaves the same way - deleting, downloading, creating... Anything! I have also noticed that putting the device in aeroplane mode so it has not internet access makes no difference either: Google Drive doesn't throw an exception, or even return, it just freezes the thread it's on.
I've updated to the very latest Drive API lib but that hasn't helped. I remembered that the error happened soon after I added the JSch SSH library to the project, so I removed that, but it made no difference. Removing and re-adding the Drive API v2 has made no difference either, and nor has cleaning the project.
Edit 2
I've found something which may be significant. On the Google Developer console, I had some Drive errors recorded as follows:
TOP ERRORS:
Requests % Requests Methods Error codes
18 38.30% drive.files.list 400
14 29.79% drive.files.insert 500
11 23.40% drive.files.update 500
4 8.51% drive.files.get 400
Do you reckon these are the errors? How could I fix them? Thanks
This is my code and it's work
new AsyncTask<Void, Void, List<File>>() {
#Override
protected List<File> doInBackground(Void... params) {
List<File> result = new ArrayList<File>();
try {
com.google.api.services.drive.Drive.Files.List list = service.files().list();
list.setQ("'" + sourcePath + "' in parents");
FileList fileList = list.execute();
result = fileList.getItems();
if(result != null) {
return result;
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(List<File> result) {
//This is List file from Google Drive
};
}.execute();
I've come up with a solution which does work, and thought I'd post it so others could see it if they happen to come across the problem.
Luckily, I had backed up all of the previous versions of the app. So I restored the whole project to how it was two weeks ago, copied and pasted all changes from the newer version which had been made since then, and it worked. I don't see why this should work, since the end result is the same project, but it does!
Google Drive List Files
This might help you.. Try to display it in ListView u will see all fetched folders
public void if_db_updated(Drive service)
{
try {
Files.List request = service.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'");
FileList files = request.execute();
for(File file : files.getItems())
{
String title = file.getTitle();
showToast(title);
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});

Accessing a PDF in Jar

I'm creating a Java application using Netbeans. From the 'Help' Menu item, I'm required to open a PDF file. When I run the application via Netbeans, the document opens, but on opening via the jar file, it isn't opening. Is there anything that can be done?
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
URL link2=getClass().getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
System.out.println(link2);
String link3="E:/new/build/classes/newpkg/Documentation.pdf";
try {
Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link3);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
The two outputs are as follows:
E:/new/build/classes/newpkg/Documentation.pdf
file:/E:/new/build/classes/newpkg/Documentation.pdf
Consider the above code snippet. On printing 'link',we can see that it is exactly same as the hard coded 'link3'. On using the hard coded 'link3' , the PDF file gets opened from jar application. But when we use link, though it is exactly same as 'link3', the PDF doesn't open.
This is most likely related to the incorrect PDF resource loading. In the IDE you have the PDF file either as part of the project structure or with a directly specified relative path. When a packaged application is running it does not see the resource.
EDIT:
Your code reveals the problem as I have described. The following method could be used to properly identify resource path.
public static URL getURL(final String pathAndFileName) {
return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}
Pls refer to this question, which might provide additional information.
Try out this:
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
File file=new File(link);
System.out.println(file);
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});

Categories