8000 chore: draft at using new API to replace java.io.File by farfromrefug · Pull Request #9661 · NativeScript/NativeScript · GitHub
[go: up one dir, main page]

Skip to content

chore: draft at using new API to replace java.io.File #9661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 14 additions & 48 deletions packages/core/file-system/file-system-access.android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,23 @@ function getApplicationContext() {
return applicationContext;
}

let Utils: typeof org.nativescript.widgets.Utils;
function getUtils() {
if (!Utils) {
Utils = org.nativescript.widgets.Utils;
}
return Utils;
}

export class FileSystemAccess {
private _pathSeparator = '/';

public getLastModified(path: string): Date {
const javaFile = new java.io.File(path);

return new Date(javaFile.lastModified());
return new Date(getUtils().getFileLastModified(getApplicationContext(), path));
}

public getFileSize(path: string): number {
const javaFile = new java.io.File(path);

return javaFile.length();
return getUtils().getFileLength(getApplicationContext(), path);
}

public getParent(path: string, onError?: (error: any) => any): { path: string; name: string } {
Expand Down Expand Up @@ -253,13 +257,7 @@ export class FileSystemAccess {

public readSync(path: string, onError?: (error: any) => any) {
try {
const javaFile = new java.io.File(path);
const stream = new java.io.FileInputStream(javaFile);
const bytes = (<any>Array).create('byte', javaFile.length());
const dataInputStream = new java.io.DataInputStream(stream);
dataInputStream.readFully(bytes);

return bytes;
return getUtils().getBytes(getApplicationContext(), path);
} catch (exception) {
if (onError) {
onError(exception);
Expand Down Expand Up @@ -329,7 +327,7 @@ export class FileSystemAccess {
reject(new Error(err));
},
}),
null
getApplicationContext()
);
} catch (ex) {
reject(ex);
Expand All @@ -339,43 +337,11 @@ export class FileSystemAccess {

public readTextSync(path: string, onError?: (error: any) => any, encoding?: any) {
try {
const javaFile = new java.io.File(path);
const stream = new java.io.FileInputStream(javaFile);

let actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
const reader = new java.io.InputStreamReader(stream, actualEncoding);
const bufferedReader = new java.io.BufferedReader(reader);

// TODO: We will need to read the entire file to a CharBuffer instead of reading it line by line
// TODO: bufferedReader.read(CharBuffer) does not currently work
let line = undefined;
let result = '';
while (true) {
line = bufferedReader.readLine();
if (line === null) {
break;
}

if (result.length > 0) {
// add the new line manually to the result
// TODO: Try with CharBuffer at a later stage, when the Bridge allows it
result += '\n';
}

result += line;
}

if (actualEncoding === textModule.encoding.UTF_8) {
// Remove UTF8 BOM if present. http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html
result = FileSystemAccess._removeUtf8Bom(result);
}

bufferedReader.close();

return result;
return getUtils().getText(getApplicationContext(), path, actualEncoding);
} catch (exception) {
if (onError) {
onError(exception);
Expand Down Expand Up @@ -414,7 +380,7 @@ export class FileSystemAccess {
reject(new Error(err));
},
}),
null
getApplicationContext()
);
} catch (ex) {
reject(ex);
Expand Down
F438
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,10 @@ declare module org {
public static saveToFileAsync(param0: globalAndroid.graphics.Bitmap, param1: string, param2: string, param3: number, param4: org.nativescript.widgets.Utils.AsyncImageCallback): void;
public static toBase64StringAsync(param0: globalAndroid.graphics.Bitmap, param1: string, param2: number, param3: org.nativescript.widgets.Utils.AsyncImageCallback): void;
public static resizeAsync(param0: globalAndroid.graphics.Bitmap, param1: number, param2: string, param3: org.nativescript.widgets.Utils.AsyncImageCallback): void;
public static getFileInputStream( param0: android.content.Context, param1: string): java.io.FileInputStream;
public static getFileOutputStream( param0: android.content.Context, param1: string): java.io.FileOutputStream;
public static getBytes(param0: android.content.Context, param1: string): any;
public static getText(param0: android.content.Context, param1: string, param2: string): string;
public constructor();
}
export module Utils {
Expand Down
1 change: 1 addition & 0 deletions packages/ui-mobile-base/android/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
41 changes: 41 additions & 0 deletions packages/ui-mobile-base/android/app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
plugins {
id 'com.android.application'
}

android {
namespace 'com.nativescript.widgetstestapp'
compileSdk 30

defaultConfig {
applicationId "com.nativescript.widgetstestapp"
minSdk 19
targetSdk 30
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {

implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation project(':widgets')
implementation "androidx.documentfile:documentfile:1.0.1"
}
21 changes: 21 additions & 0 deletions packages/ui-mobile-base/android/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package com.nativescript.widgetstestapp;

import android.content.Context;
import android.os.Build;
import android.util.Log;

import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.nativescript.widgets.File;
import org.nativescript.widgets.Utils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;

import static org.junit.Assert.*;

/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ExampleInstrumentedTest {
private Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();

private String getFilePath() throws IOException {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return appContext.getFilesDir().getCanonicalPath() + "/test2.txt";
}
else {
return appContext.getFilesDir().getCanonicalPath() + "/test2.txt";

}
}

@Test
public void a_useAppContext() {
// Context of the app under test.
assertEquals("com.nativescript.widgetstestapp", appContext.getPackageName());
}

@Test
public void b_assetsExists() throws IOException {
assertNotEquals(null, getFilePath());
}
@Test
public void c_readAndWriteFile() throws Exception {
String filePath = getFilePath();
String content = "Hello I am new!";
File.ensureFileExists(appContext,filePath, false);
File.writeText(appContext,filePath, content, "UTF-8");
assertEquals(content, Utils.getText(appContext, filePath, "UTF-8"));
}

@Test
public void d_fileExists() throws IOException {
assertEquals(true, File.fileExists(appContext, getFilePath()));
}
@Test
public void d_fileLength() throws IOException {
assertEquals(15, File.fileLength(appContext, getFilePath()));
}
}
32 changes: 32 additions & 0 deletions packages/ui-mobile-base/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WidgetsTestApp">
<activity
android:name="com.nativescript.widgetstestapp.MainActivity"
android:exported="true"
tools:node="merge">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>
</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello2
429F
Loading
0