HMS Drive kit Query and query string - kotlin

I'm a beginner developer just starting with HMS. I'm trying to write a code that finds the "profile.json" file, which was previously uploaded to the cloud into the folder "DebtSorter". My code (Kotlin) for it currently looks like:
var fileList: MutableList<File?> = mutableListOf()
thread {
try {
val drive = buildDrive()
val request = drive.files().list()
var cursor: String?
fileList = ArrayList()
do {
var result = request.setQueryParam("fileName contains 'profile'")
.setOrderBy("fileName")
.setPageSize(10)
.setFields("*")
.execute()
for (file in result.files) {
fileList.add(file)
}
cursor = result.nextCursor
request.cursor = cursor
} while (!StringUtils.isNullOrEmpty(cursor))
} catch (e: java.lang.Exception) {
Toast.makeText(applicationContext, "executeFilesList exception: $e", Toast.LENGTH_LONG)
.show()
}
}
return fileList
However, the returned fileList is always empty, even when I upload the file to the root of the cloud. I think I'm messing something up with the query string, because I can upload files just fine. Can someone tell me the syntax and keywords used in the query string, and possibly help me with the code and how to search in a given folder in HMS Drive kit?

Update:
You can also refer to the demo: https://github.com/HMS-Core/hms-drive-serverdemo In the demo, the thread executes the method of obtaining the file list directly.
Your query parameters is incorrect. You can't define the format of your query string. Please refer to this sample query statement.
(assuming that the ID of folder A is f192358798744098816):
To query all files in folder A, run the following statement: 'f192358798744098816' in parentFolder and mimeType != 'application/vnd.huawei-apps.folder'
To query all folders in the recycle bin, run the following statement: mimeType='application/vnd.huawei-apps.folder' and recycled=true
The query criteria 'fileId' in parentFolder and recycled=true cannot be used together, that is, a user cannot query files or folders in a specified parent folder in the recycle bin.
For more details, see the official guide.

In the end, the problem was with creating the thread. Since the thread is asynchronous and I created the fileList variable before the thread, modified it in the thread and returned it after the thread, the actual modification happened after the method already returned with the empty fileList. I took out the lines with thread and put the method call into a thread. This solved it.

Related

Kotlin: How to save file in a directory? Having errors

Having problems with my code, So I am currently trying to create a new directory and also store a text file within that folder I have created, I looked at a couple of examples but it seems like they only focus on a specific thing like how to create a file or a folder but never how to utilise both. How can I achieve this? I keep hitting exception errors when I try doing different methods, thanks!
val newFile : Int = 1
val fileString = "nameData"
//so we are creating variable to store the directory information
val folderDir = File("G:\\Random Projects\\JVM\\database\\Collection 1")
//we use that variable to create a File class which will create a folder called nameData
//this will also be stored in another variable called f
val f = File(folderDir, "nameData")
//this will create the actual folder based on the variable information
f.mkdir()
//creating file
try {
val fo = FileWriter(fileString, true)
fo.write(a)
fo.close()
} catch (ex:Exception) {
println("Something Went Wrong When Creating File!!")
}
The problem is that you probably don't have the whole folder structure created, that's why you usually use the mkdirs (note the s at the end) function. You can then use the writeBytes function to write the content:
val fileString = "nameData"
val folderDir = File("myfolder")
val f = File(folderDir, "nameData")
f.parentFile.mkdirs()
f.writeBytes(fileString.toByteArray())

Flutter test - verifying assets exist

I have a flutter app which contains a large list of quotes, each with an associated audio file.
I've written a simple test that verifies all the specified audio files are where they're supposed to be, in case of typos etc:
test('specified audio file should exist for all quotes', () {
ALL_QUOTES.forEach((quote) {
final expectedPath = 'assets/${quote.filename}.wav';
final exists = new File(expectedPath).existsSync();
expect(exists, isTrue, reason: '$expectedPath does not exist');
});
});
This passes fine in IntelliJ, however running from the command line using flutter test it fails on the first thing it looks for.
Is there a way of doing this which will work regardless of how it's run? Why does it pass one way but not the other?
Ok so I got to the bottom of this, and it is something you can do in a unit test.
To diagnose, I added the line print(Directory.current); to the test. Running in IntelliJ, I get /home/project_name. From the command line, it's /home/project_name/test. So just a simple file path thing to resolve.
Edited to include Ovidiu's simpler logic for getting the right asset path
void main() {
test('specified audio file should exist for all quotes', () {
ALL_QUOTES.forEach((quote) {
final expectedPath = 'assets/${quote.filename}.wav';
final exists = _getProjectFile(expectedPath).existsSync();
expect(exists, isTrue, reason: '$expectedPath does not exist');
});
});
}
File _getProjectFile(String path) {
final String assetFolderPath = Platform.environment['UNIT_TEST_ASSETS'];
return File('$assetFolderPath/$path');
}

missing blob with jgit

I am trying the following with jgit:
val git = Git.open(File("/path/toMyRepo"))
val diffFormatter = DiffFormatter(DisabledOutputStream.INSTANCE).apply {
setRepository(git.repository)
}
git.diff().call().forEach {
if (it.changeType == DiffEntry.ChangeType.MODIFY) {
diffFormatter.toFileHeader(it).toEditList().forEach {
println(it)
}
}
}
but I am getting a the following exception:
"org.eclipse.jgit.errors.MissingObjectException: Missing blob 9645ba8461cd88af20fd66a3e44055deb24f826e"
Does anyone see what is wrong with the code?
EDIT: full stacktrace with a quite empty repo (only one commit and a change on the only line in the only file):
Exception in thread "main" org.eclipse.jgit.errors.MissingObjectException: Missing blob f7891cbde46bbb6ca96065ecf1900ef6a223f679
at org.eclipse.jgit.internal.storage.file.WindowCursor.open(WindowCursor.java:149)
at org.eclipse.jgit.diff.ContentSource$ObjectReaderSource.open(ContentSource.java:140)
at org.eclipse.jgit.diff.ContentSource$Pair.open(ContentSource.java:276)
at org.eclipse.jgit.diff.DiffFormatter.open(DiffFormatter.java:1020)
at org.eclipse.jgit.diff.DiffFormatter.createFormatResult(DiffFormatter.java:950)
at org.eclipse.jgit.diff.DiffFormatter.toFileHeader(DiffFormatter.java:915)
at MainKt.main(Main.kt:17)
Not sure if this will be helpful, but I lost some time in this issue and if someone falls down this hole in the future: It appears to be some issue in the DiffFormatter class when the latest changes which you are trying to diff are not committed.
My use case was to get the changes of a single file, and to make it work, I made use of the gitDiff interface directly, like so:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String filename = "mafile.java";
Git.open(File("/path/toMyRepo")).diff() // calling diff command
.setPathFilter(PathFilter.create(filename)) //setting to just look for changes in specific file
.setContextLines(0) // just the changes itself, not the bordering lines
.setOutputStream(byteArrayOutputStream) // the outputstream to print the changes
.call();
System.out.println(byteArrayOutputStream.toString(StandardCharsets.UTF_8));

Exception when listing created sub-directory in documents directory

I am using the official API to list a directory I had created for some purpose and have pushed few files into it. Now I want to list them out.
Here's how I am creating first
final Directory extDir = await getApplicationDocumentsDirectory();
// final String dirPath = '${extDir.path}/Movies/flutter_test';
final String dirPath = '${extDir.path}/mydir';
await new Directory(dirPath).create(recursive: true);
Here's what I am doing to read in a different page.
final Directory extDir = await getApplicationDocumentsDirectory();
// final String dirPath = '${extDir.path}/Pictures/flutter_test';
final String dirPath = '${extDir.path}/mydir';
final String thumbDirPath = '$dirPath/thumbs';
final Directory imgDir = Directory.fromUri(Uri.file(dirPath));
dirExists = imgDir.existsSync();
fileCount = 0;
if(dirExists) {
print("my dir exists");
// thumbDir.list(recursive: false, followLinks: false)
fileCount = await imgDir.list(recursive: false).length;
print('mydir images count $fileCount');
if(fileCount > 1) { // we think one is always the directory itself?
try {
imgDir.list(recursive: false, followLinks: false)
.listen((FileSystemEntity entity) {
The code breaks here giving the following exception message
type '() => Null' is not a subtype of type '(Object) => FutureOr<dynamic>'
I have to also tell you this doesn't happen when I am listing the external storage directory. Am I doing something wrong while creating my directory?
EDIT
I have now upgraded flutter to 0.7.3 on my Mac, and have a new problem altogether. The application won't run at all.
Okay, I found a solution myself. Apparently tinkering with the large provider API has given me different way to list the items, which actually told me I was trying to run listeners twice.
fileCount = await imgDir.list(recursive: false).length;
and
imgDir.list(recursive: false, followLinks: false)
.listen((FileSystemEntity entity) {
from original code cannot be written one after the other, as the first one finishes the listener. This I found out by altering my own code and listing directories this way instead.
Stream<FileSystemEntity> files = imgDir.list(recursive: false, followLinks: false);
will add as many events as many files according to API.. and then create a regular generic list
List<FileSystemEntity> entities = await files.toList();
and then you perform usual iteration using iterator or for() loop like
for(FileSystemEntity entity in entities) {
... // every file now is available

Google Drive Android Api Completion Event for Folder Creation

The completion events in Google Drive Android Api (GDAA) seem to be invoked only by contents change (file create, file contents update). Since I need to retrieve a Resource Id of a folder (seen here for a file with contents), referring to this method:
DriveFolder.createFolder(mGAC, meta).setResultCallback(...);
I need a completion event for a folder creation, but I can't find a solution.
Any hints? Thank you.
No, takers for this question, so I assume there is no straightforward solution. Meanwhile, I slammed together a hack until this gets fixed (if ever).
1/ Create a folder, you get the 'preliminary' DriveId that YIELDS NO ResourceId (nothing's commited).
2/ Use this DriveId as a parent of a dummy file with a dummy content and a completion event request attached. The folder creation is now apparently forced by it's child.
3/ In the completion event (as seen here), get the dummy file's DriveId and retrieve it's parent ID:
com.google.android.gms.common.api.GoogleApiClient GAC;
//...
DriveId parentID(DriveId dId) {
MetadataBuffer mdb = null;
DriveApi.MetadataBufferResult mbRslt = dId.asDriveResource().listParents(GAC).await();
if (mbRslt.getStatus().isSuccess()) try {
mdb = mbRslt.getMetadataBuffer();
if (mdb.getCount() > 0)
return mdb.get(0).getDriveId();
} catch (Exception e) { e.printStackTrace();}
finally {
if (mdb != null) mdb.close();
}
return null;
}
('await()' flavor works here since 'DriveEventService' is off-UI)
Now you get folder's 'real' DriveId that can produce a valid ResourceId:
String resourceId = driveId.getResourceId()
4/ zap the dummy file that has served it's lifetime mission
Is there a better solution? Please let me know.