Google drive rest API, Download files from root folder only - java

I am trying to download files in the root directory only. Currently I am not specifying any folders as I do not know how to so it downloads the most recent files that are in other folders that aren't the root. All I would like are the files in the root. The code that is getting the files and the download URLs is below:
public static void startDownload() throws IOException, ParseException {
Drive serv = getDriveService();
FileList result = serv.files().list().setMaxResults(10).execute(); //there are 10 files in the root folder
List<File> listA = result.getItems();
if (listA == null || listA.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:"+lista.size());
for (File file : listA) {
System.out.printf("%s (%s)\n", file.getTitle(), file.getDownloadUrl());
downloadFile(serv, file);
}
}
}
I would like to download all files in the root file only and not in any other folders. Any help would be appreciated.

You need to use the Q parameter to search
q string A query for filtering the file results. See the "Search for
Files" guide for supported syntax.
Sending something like the following will return everything that is not a folder with the parent of root.
mimeType != 'application/vnd.google-apps.folder' and 'root' in parents

There are a number of considerations.
Your line 3 needs to be
String q = "trashed = false and 'root' in parents and mimeType != 'application/vnd.google-apps.folder' "
FileList result = serv.files().list().setFields("*").setQ(q).setMaxResults(10).execute();
You need to be aware that this will return a maximum of 10 results, but even more so, you need to be aware that there is no minimum number of results. This means that if you have 11 files, you might get 10 in the first iteration and 1 in the 2nd. However, you could also get 1 and 10, or 3 and 6 and 2, or 0 and 0 and 1 and 10. You need to keep fetching results until the value of getNextPageToken() == null. So your line
if (listA == null || listA.isEmpty()) {
should be something like
if (result.getNextPageToken() == null) {
I realise that you've copy/pasted from the official documentation, but sadly that documentation is wrong.

Related

problem of associating a data source associated with Word mail merge from a java application (OLE communication)

I'm working on a java application that interacts with Word through an OLE library (org.eclipse.swt.ole.win32) to merge documents (mail merge).
the java method which makes it possible to merge has been working for several years without any particular problem.
but recently the data source can no longer be associated with the merge document.
This problem is random (on some workstations it works and on others it doesn't, yet same system configuration)
I have no explicit error reported on the java side
Here is the method that communicates with Word:
public void mergeDocument(File model, File source) throws Exception {
OleAutomation autoMailMerge = null;
LOGGER.log(new Status(IStatus.INFO, pluginID, "Merge d un document"));
LOGGER.log(new Status(IStatus.INFO, pluginID, "fichier modele: " + model.getCanonicalPath()));
LOGGER.log(new Status(IStatus.INFO, pluginID, "fichier source: " + source.getPath()));
openDocumentReadOnly(model);
autoMailMerge = OLEHelper.getAutomationProperty(autoDocument, "MailMerge");
if ((source != null) && (source.exists()) && (!source.isDirectory())) {
OLEHelper.invoke(autoMailMerge, "OpenDataSource", source.getPath());
} else {
throw new MSWordOleInterfaceException(MSWordOleInterfaceCst.MSG_ERROR_EMPTY_SOURCE_PATH
+ ((source == null) ? "null" : source.getPath()));
}
OLEHelper.invoke(autoMailMerge, "Execute");
OleAutomation autoDocumentMerged = getActiveDocument();
closeDocument(autoDocument);
activateDocument(autoDocumentMerged);
autoDocument = autoDocumentMerged;
autoMailMerge.dispose();
}
Merging by hand from Word (associating the data source and merging) works on workstations where the java application does not work.
thanks to the OLE command I validated that it is the data source which is not passed (on a workstation which works I have a return with the name of the source, on one or it does not work the return is empty)
LOGGER.log(new Status(IStatus.INFO, pluginID, "data source name: "
+ OLEHelper.getVariantProperty(autoDataSource, "Name").getString()));
-a temporary solution has been found, by deleting the registry key related to office:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Word\DocumentTemplateCache
but this is only a temporary solution, the problem comes back.

calculate folder size or file size in jenkins pipeline

We write our jenkins pipeline using groovy script. Is there any way to identify the folder size or file size.
Our goal is to identify size of two zip files and calculate the difference between them.
I tried below code but its not working.
stage('Calculate Opatch size')
{
def sampleDir = new File('${BuildPathPublishRoot}')
def sampleDirSize = sampleDir.directorySize()
echo sampleDirSize
}
Getting below error :-
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.io.File.directorySize() is applicable for argument types: () values: []
Possible solutions: directorySize()
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:154)
Here's what worked for me. Grab all the files in a directory and sum the lengths.
Please note that you'll need to use quotes (") in order for string interpolation to work, i.e. "${BuildPathPublishRoot}" places the value of the BuildPathPublishRoot variable into the string, whereas '${BuildPathPublishRoot}' is taken literally to be the directory name.
workspaceSize = directorySize("${BuildPathPublishRoot}")
/** Computes bytes in the directory*/
public def directorySize(directory){
long bytes = 0
directory = (directory?:'').replace('\\','/')
directory = (directory =='') ? '' : (directory.endsWith('/') ? directory : "${directory}/")
def files=findFiles(glob: "${directory}*.*")
for (file in files) {
if (!file.isDirectory()){
bytes += file.length
}
}
return bytes
}

Spring List all files in static directory

I use Spring with embeded Tomcat and a War file in prodution.
I need to list all files in the "static" directory. It's like 4 days I m on it
This kind of code not working :
Stream.of(new File(dir).listFiles()
It lists the files where the war is located but the static directory is inside the war
With this code I arrive to read a file inside the war :
Thread.currentThread().contextClassLoader?.getResourceAsStream(path)?.bufferedReader()?.use(BufferedReader::readText)
But it's not working with a directory
And now i have no idea how i can list all files inside the static directory
I found a solution
Not sure it's the best and clean but it's worked
I use 2 way to do it, one for developpment and the other when it's package inside war
loadFilesFromDirectory("/static")
fun listFilesFromDirectory(path: String, request: HttpServletRequest? = null): List<String> {
return if (request == null || request.requestURL.contains("localhost")) {
//Don't work on war but work on IDE
Thread.currentThread().contextClassLoader?.getResourceAsStream(path)
?.bufferedReader()?.use(BufferedReader::readText)?.split("\n")
?.filter { it.endsWith(".html") }
?: throw Exception("Non trouvé :$path")
} else {
//Not work on IDE but work on war
val root: URL = request.servletContext.getResource("/WEB-INF/classes/$path")
var rootPath: String = root.path
rootPath = rootPath.substring(rootPath.indexOf("/WEB-INF"), rootPath.length)
return request.servletContext.getResourcePaths(rootPath).map {
it.replace(".*/", "")
}.filter { it.endsWith(".html") }
}
}

Spring inbound channel adapter - how to auto delete folders and files older than 10 days

Integration.xml - this will take all files in the directory
<int-file:inbound-channel-adapter id="delFiles" channel="delFiles"
directory="C:/abc/abc" use-watch-service="true" prevent-duplicates="false" auto-startup="true"
watch-events="CREATE,MODIFY">
<int:poller fixed-delay="1000"/>
<int-file:nio-locker/>
</int-file:inbound-channel-adapter>
I need to delete all files older than 10 days in that folder and sub folder. Can some one pls help?
Listener
#Transformer(inputChannel="delFiles")
public JobLaunchRequest deleteJob(Message<File> message) throws IOException {
Long timeStamp = message.getHeaders().getTimestamp();
return JobHandler.deleteJob(message.getPayload(), jobRepository, fileProcessor, timeStamp);
}
Handler
public static JobLaunchRequest deleteJob(File file, JobRepository jobRepository, Job fileProcessor, Long timeStamp) throws IOException {
//Is there a way in spring integration whether I can check this easily?
//How to check for folder and subfolders?
// This will check for files once it's dropped.
// How to run this job daily to check the file's age and delete?
}
This is not a <int-file:inbound-channel-adapter> responsibility. This one is really about polling files from the directory according filtering setting you provide.
If you are not interested in old files, you can implement a custom FileListFilter to skip files which are really so old.
If you still would like to delete those old files as some application functionality, you need to take a look into some other solution, something like #Scheduled method it iterate through files in that dir and remove them, e.g. once a day let's say at midnight.
You also can just remove processed files in the and of your logic. Since you use prevent-duplicates="false", you are going to poll the same file again and again.
To perform directory clean up you don't need Spring Integration:
public void recursiveDelete(File file) {
if (file != null && file.exists()) {
File[] files = file.listFiles();
if (files != null) {
for (File fyle : files) {
if (fyle.isDirectory()) {
recursiveDelete(fyle);
}
else {
if (fyle.lastModified() > 10 * 24 * 60 * 60 * 1000) {
fyle.delete();
}
}
}
}
}
}
(You might to improve this function a bit: haven't tested...)

What is the proper way to check if a file/folder in a Box account is read-only using the Box Android library (apiV2)?

I am working on an android app used to access a Box account. The problem I am facing is how to determine a folder/file in the user's account is read only (shared with him/her as a Viewer) so that the upload/delete operations can be disabled.
What I currently do is:
1) Get the items in a folder:
BoxCollection itemsCollection = _boxClient.getFoldersManager()
.getFolderItems(folderId, folderContentRequest);
String userMail = ...
ArrayList<BoxTypedObject> result = null;
2) Determine which one is folder, get it's collaborations, check if it's accessible by the logged-in user, and check whether he is an editor:
if (itemsCollection != null) {
result = itemsCollection.getEntries();
for(BoxTypedObject boxObject : result) {
if(boxObject instanceof BoxAndroidFolder) {
BoxAndroidFolder folder = (BoxAndroidFolder)boxObject;
List<BoxCollaboration> folderCollaborations = _boxClient.getFoldersManager().getFolderCollaborations(folder.getId(), null);
for(BoxCollaboration collaboration : folderCollaborations) {
if( userMail.equalsIgnoreCase(collaboration.getAccessibleBy().getLogin()) &&
!BoxCollaborationRole.EDITOR.equalsIgnoreCase(collaboration.getRole()))
System.out.println("" + folder.getName() + " is readonly");
}
}
}
}
So, is there a simpler and faster (fewer requests) way to get that property of a folder with the android SDK?
You can first check the owner of the folder (folder.getOwnedBy()), if it's the current user then you don't need to check collaborations. However if it's not the current user you'll have to check collaborations.

Categories