diff --git a/httpclient_android/.gitignore b/httpclient_android/.gitignore new file mode 100644 index 000000000..603b14077 --- /dev/null +++ b/httpclient_android/.gitignore @@ -0,0 +1,14 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx diff --git a/httpclient_android/README.md b/httpclient_android/README.md new file mode 100644 index 000000000..27b8ad1f0 --- /dev/null +++ b/httpclient_android/README.md @@ -0,0 +1,16 @@ +## Getting Started + + - [Download Android Studio](https://developer.android.com/studio) + + - [Create an AVD](https://developer.android.com/studio/run/managing-avds) + + Android API 26 or higher + + - Open project + + File > Open > Browse to `httpclient_android` folder + + - Sync Project with Gradle: + + + Click Sync Project with Gradle Files to sync your project. \ No newline at end of file diff --git a/httpclient_android/app/.gitignore b/httpclient_android/app/.gitignore new file mode 100644 index 000000000..42afabfd2 --- /dev/null +++ b/httpclient_android/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/httpclient_android/app/build.gradle b/httpclient_android/app/build.gradle new file mode 100644 index 000000000..6ae710553 --- /dev/null +++ b/httpclient_android/app/build.gradle @@ -0,0 +1,33 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 30 + buildToolsVersion "29.0.3" + + defaultConfig { + applicationId "com.backblaze.b2.client.webApiHttpClient.android" + minSdkVersion 26 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: "libs", include: ["*.jar"]) + implementation 'androidx.appcompat:appcompat:1.2.0' + implementation 'androidx.constraintlayout:constraintlayout:2.0.1' + testImplementation 'junit:junit:4.13' + androidTestImplementation 'androidx.test.ext:junit:1.1.2' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' + +} \ No newline at end of file diff --git a/httpclient_android/app/proguard-rules.pro b/httpclient_android/app/proguard-rules.pro new file mode 100644 index 000000000..481bb4348 --- /dev/null +++ b/httpclient_android/app/proguard-rules.pro @@ -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 \ No newline at end of file diff --git a/httpclient_android/app/src/main/AndroidManifest.xml b/httpclient_android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..4fed6f22f --- /dev/null +++ b/httpclient_android/app/src/main/AndroidManifest.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/httpclient_android/app/src/main/java/com/backblaze/b2/client/webApiHttpClient/android/MainActivity.java b/httpclient_android/app/src/main/java/com/backblaze/b2/client/webApiHttpClient/android/MainActivity.java new file mode 100644 index 000000000..2dadba344 --- /dev/null +++ b/httpclient_android/app/src/main/java/com/backblaze/b2/client/webApiHttpClient/android/MainActivity.java @@ -0,0 +1,14 @@ +package com.backblaze.b2.client.webApiHttpClient.android; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +public class MainActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + } +} \ No newline at end of file diff --git a/httpclient_android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/httpclient_android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 000000000..2b068d114 --- /dev/null +++ b/httpclient_android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/httpclient_android/app/src/main/res/drawable/ic_launcher_background.xml b/httpclient_android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 000000000..07d5da9cb --- /dev/null +++ b/httpclient_android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/httpclient_android/app/src/main/res/layout/activity_main.xml b/httpclient_android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 000000000..4fc244418 --- /dev/null +++ b/httpclient_android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/httpclient_android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/httpclient_android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 000000000..eca70cfe5 --- /dev/null +++ b/httpclient_android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/httpclient_android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/httpclient_android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 000000000..eca70cfe5 --- /dev/null +++ b/httpclient_android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/httpclient_android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/httpclient_android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 000000000..a571e6009 Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/httpclient_android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/httpclient_android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 000000000..61da551c5 Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/httpclient_android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/httpclient_android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 000000000..c41dd2853 Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/httpclient_android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/httpclient_android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 000000000..db5080a75 Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/httpclient_android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/httpclient_android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 000000000..6dba46dab Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/httpclient_android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/httpclient_android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 000000000..da31a871c Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/httpclient_android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/httpclient_android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..15ac68172 Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/httpclient_android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/httpclient_android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 000000000..b216f2d31 Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/httpclient_android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/httpclient_android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..f25a41974 Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/httpclient_android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/httpclient_android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 000000000..e96783ccc Binary files /dev/null and b/httpclient_android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/httpclient_android/app/src/main/res/values/colors.xml b/httpclient_android/app/src/main/res/values/colors.xml new file mode 100644 index 000000000..4faecfa80 --- /dev/null +++ b/httpclient_android/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #6200EE + #3700B3 + #03DAC5 + \ No newline at end of file diff --git a/httpclient_android/app/src/main/res/values/strings.xml b/httpclient_android/app/src/main/res/values/strings.xml new file mode 100644 index 000000000..bd4f4f569 --- /dev/null +++ b/httpclient_android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + B2WebApiHttpClientAndroid + \ No newline at end of file diff --git a/httpclient_android/app/src/main/res/values/styles.xml b/httpclient_android/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..fac929168 --- /dev/null +++ b/httpclient_android/app/src/main/res/values/styles.xml @@ -0,0 +1,10 @@ + + + + + \ No newline at end of file diff --git a/httpclient_android/build.gradle b/httpclient_android/build.gradle new file mode 100644 index 000000000..04baf1e78 --- /dev/null +++ b/httpclient_android/build.gradle @@ -0,0 +1,24 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + repositories { + google() + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:4.1.1' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} \ No newline at end of file diff --git a/httpclient_android/gradle.properties b/httpclient_android/gradle.properties new file mode 100644 index 000000000..c52ac9b79 --- /dev/null +++ b/httpclient_android/gradle.properties @@ -0,0 +1,19 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app"s APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Automatically convert third-party libraries to use AndroidX +android.enableJetifier=true \ No newline at end of file diff --git a/httpclient_android/gradle/wrapper/gradle-wrapper.jar b/httpclient_android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..f6b961fd5 Binary files /dev/null and b/httpclient_android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/httpclient_android/gradle/wrapper/gradle-wrapper.properties b/httpclient_android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..707dabd07 --- /dev/null +++ b/httpclient_android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Wed Nov 11 18:00:02 PST 2020 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip diff --git a/httpclient_android/gradlew b/httpclient_android/gradlew new file mode 100755 index 000000000..cccdd3d51 --- /dev/null +++ b/httpclient_android/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/httpclient_android/gradlew.bat b/httpclient_android/gradlew.bat new file mode 100644 index 000000000..e95643d6a --- /dev/null +++ b/httpclient_android/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/httpclient_android/http_client/.gitignore b/httpclient_android/http_client/.gitignore new file mode 100644 index 000000000..42afabfd2 --- /dev/null +++ b/httpclient_android/http_client/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/httpclient_android/http_client/build.gradle b/httpclient_android/http_client/build.gradle new file mode 100644 index 000000000..fc17b16ad --- /dev/null +++ b/httpclient_android/http_client/build.gradle @@ -0,0 +1,36 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion 30 + buildToolsVersion "29.0.3" + + defaultConfig { + minSdkVersion 26 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles "consumer-rules.pro" + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: "libs", include: ["*.aar", "*.jar"]) + implementation 'androidx.appcompat:appcompat:1.2.0' + testImplementation 'junit:junit:4.13' + androidTestImplementation 'androidx.test.ext:junit:1.1.2' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' + implementation 'com.backblaze.b2:b2-sdk-core:3.1.0' +} \ No newline at end of file diff --git a/httpclient_android/http_client/consumer-rules.pro b/httpclient_android/http_client/consumer-rules.pro new file mode 100644 index 000000000..e69de29bb diff --git a/httpclient_android/http_client/proguard-rules.pro b/httpclient_android/http_client/proguard-rules.pro new file mode 100644 index 000000000..481bb4348 --- /dev/null +++ b/httpclient_android/http_client/proguard-rules.pro @@ -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 \ No newline at end of file diff --git a/httpclient_android/http_client/src/main/AndroidManifest.xml b/httpclient_android/http_client/src/main/AndroidManifest.xml new file mode 100644 index 000000000..9ac5c60f1 --- /dev/null +++ b/httpclient_android/http_client/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + \ No newline at end of file diff --git a/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientBuilder.java b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientBuilder.java new file mode 100644 index 000000000..3d73a2579 --- /dev/null +++ b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientBuilder.java @@ -0,0 +1,101 @@ +/* + * Copyright 2020, Backblaze Inc. All Rights Reserved. + * License https://www.backblaze.com/using_b2_code.html + */ +package com.backblaze.b2.client.webApiUrlConnection.android.UrlConnection; + +import com.backblaze.b2.client.B2AccountAuthorizer; +import com.backblaze.b2.client.B2AccountAuthorizerSimpleImpl; +import com.backblaze.b2.client.B2ClientConfig; +import com.backblaze.b2.client.B2DefaultRetryPolicy; +import com.backblaze.b2.client.B2RetryPolicy; +import com.backblaze.b2.client.B2Sdk; +import com.backblaze.b2.client.B2StorageClient; +import com.backblaze.b2.client.B2StorageClientImpl; +import com.backblaze.b2.client.B2StorageClientWebifier; +import com.backblaze.b2.client.B2StorageClientWebifierImpl; +import com.backblaze.b2.client.credentialsSources.B2Credentials; +import com.backblaze.b2.client.credentialsSources.B2CredentialsFromEnvironmentSource; +import com.backblaze.b2.client.exceptions.B2Exception; +import com.backblaze.b2.client.webApiClients.B2WebApiClient; +import com.backblaze.b2.util.B2Preconditions; + +import java.util.function.Supplier; + +public class B2StorageHttpClientBuilder { + + private static final String DEFAULT_MASTER_URL = "https://api.backblazeb2.com/"; + private final B2ClientConfig config; + private B2WebApiClient webApiClient; + private HttpClientFactory httpClientFactory; + private Supplier retryPolicySupplier; + + @SuppressWarnings("WeakerAccess") + public static B2StorageHttpClientBuilder builder(B2ClientConfig config) { + return new B2StorageHttpClientBuilder(config); + } + + // We don't usually have several builder() methods, but this builder + // is used by *everyone*, so i want to make it so that most users don't + // need to worry about making an authorizer. + @SuppressWarnings("WeakerAccess") + public static B2StorageHttpClientBuilder builder(String applicationKeyId, String applicationKey, String userAgent) { + final B2AccountAuthorizer accountAuthorizer = B2AccountAuthorizerSimpleImpl + .builder(applicationKeyId, applicationKey) + .build(); + final B2ClientConfig config = B2ClientConfig + .builder(accountAuthorizer, userAgent) + .build(); + return builder(config); + } + + /** + * @param userAgent the user agent to use when performing http requests. + * @return a storage builder. + */ + public static B2StorageHttpClientBuilder builder(String userAgent) { + final B2Credentials credentials = B2CredentialsFromEnvironmentSource.build().getCredentials(); + return builder(credentials.getApplicationKeyId(), credentials.getApplicationKey(), userAgent); + } + + private B2StorageHttpClientBuilder(B2ClientConfig config) { + this.config = config; + } + + public B2StorageClient build() { + final B2WebApiClient webApiClient = (this.webApiClient != null) ? + this.webApiClient : + B2WebApiHttpClientImpl.builder().setHttpClientFactory(httpClientFactory).build(); + final B2StorageClientWebifier webifier = new B2StorageClientWebifierImpl( + webApiClient, + config.getUserAgent() + " " + B2Sdk.getName() + "/" + B2Sdk.getVersion(), + (config.getMasterUrl() == null) ? DEFAULT_MASTER_URL : config.getMasterUrl(), + config.getTestModeOrNull()); + final Supplier retryPolicySupplier = (this.retryPolicySupplier != null) ? + this.retryPolicySupplier : + B2DefaultRetryPolicy.supplier(); + return new B2StorageClientImpl( + webifier, + config, + retryPolicySupplier); + } + + public B2StorageHttpClientBuilder setHttpClientFactory(HttpClientFactory httpClientFactory) { + B2Preconditions.checkState(webApiClient == null, "httpClientFactory is only used if webApiClient isn't specified, so at most one of them can be non-null!"); + this.httpClientFactory = httpClientFactory; + return this; + } + + @SuppressWarnings("unused") + public B2StorageHttpClientBuilder setWebApiClient(B2WebApiClient webApiClient) { + B2Preconditions.checkState(httpClientFactory == null, "httpClientFactory is only used if webApiClient isn't specified, so at most one of them can be non-null!"); + this.webApiClient = webApiClient; + return this; + } + + @SuppressWarnings("unused") + public B2StorageHttpClientBuilder setRetryPolicySupplier(Supplier retryPolicySupplier) { + this.retryPolicySupplier = retryPolicySupplier; + return this; + } +} diff --git a/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientFactory.java b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientFactory.java new file mode 100644 index 000000000..b8e7d1a4a --- /dev/null +++ b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientFactory.java @@ -0,0 +1,23 @@ +/* + * Copyright 2020, Backblaze Inc. All Rights Reserved. + * License https://www.backblaze.com/using_b2_code.html + */ +package com.backblaze.b2.client.webApiUrlConnection.android.UrlConnection; + +import com.backblaze.b2.client.B2ClientConfig; +import com.backblaze.b2.client.B2StorageClient; +import com.backblaze.b2.client.B2StorageClientFactory; + +/** + * Simple factory for the HttpClient-based B2StorageClient. + * + * THREAD-SAFE. + */ + +public class B2StorageHttpClientFactory implements B2StorageClientFactory { + + @Override + public B2StorageClient create(B2ClientConfig config) { + return B2StorageHttpClientBuilder.builder(config).build(); + } +} diff --git a/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2WebApiHttpClientImpl.java b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2WebApiHttpClientImpl.java new file mode 100644 index 000000000..142daf13b --- /dev/null +++ b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2WebApiHttpClientImpl.java @@ -0,0 +1,398 @@ +/* + * Copyright 2020, Backblaze Inc. All Rights Reserved. + * License https://www.backblaze.com/using_b2_code.html + */ +package com.backblaze.b2.client.webApiUrlConnection.android.UrlConnection; + +import com.backblaze.b2.client.contentHandlers.B2ContentSink; +import com.backblaze.b2.client.contentSources.B2Headers; +import com.backblaze.b2.client.contentSources.B2HeadersImpl; +import com.backblaze.b2.client.exceptions.*; +import com.backblaze.b2.client.structures.B2ErrorStructure; +import com.backblaze.b2.client.webApiClients.B2WebApiClient; +import com.backblaze.b2.json.B2Json; +import com.backblaze.b2.json.B2JsonException; +import com.backblaze.b2.json.B2JsonOptions; +import com.backblaze.b2.util.B2Preconditions; +import com.backblaze.b2.util.B2IoUtils; +import com.backblaze.b2.client.exceptions.B2Exception; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.ConnectException; +import java.net.MalformedURLException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.net.URLConnection; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Scanner; + +import javax.net.ssl.HttpsURLConnection; + +import static com.backblaze.b2.util.B2IoUtils.closeQuietly; + +public class B2WebApiHttpClientImpl implements B2WebApiClient { + private final static String UTF8 = "UTF-8"; + private final HttpClientFactory clientFactory; + + private B2WebApiHttpClientImpl(HttpClientFactory clientFactory) { + this.clientFactory = (clientFactory != null) ? + clientFactory : + HttpClientFactoryImpl.build(); + } + + @SuppressWarnings("WeakerAccess") + public static Builder builder() { + return new Builder(); + } + + + @Override + public ResponseType postJsonReturnJson(String url, + B2Headers headersOrNull, + Object request, + Class responseClass) throws B2Exception { + + final String responseString = postJsonAndReturnString(url, headersOrNull, request); + + try { + final B2Json bzJson = B2Json.get(); + return bzJson.fromJson(responseString, responseClass, B2JsonOptions.DEFAULT_AND_ALLOW_EXTRA_FIELDS); + } catch (B2JsonException e) { + throw new B2LocalException("parsing_failed", "can't convert response from json: " + e.getMessage(), e); + } + } + + @Override + public ResponseType postDataReturnJson(String url, + B2Headers headersOrNull, + InputStream inputStream, + long contentLength, + Class responseClass) throws B2Exception { + try { + final InputStream requestEntity = inputStream.setFixedLengthStreamingMode(contentLength); + final String responseJson = postAndReturnString(url, headersOrNull, requestEntity); + return B2Json.get().fromJson(responseJson, responseClass, B2JsonOptions.DEFAULT_AND_ALLOW_EXTRA_FIELDS); + } catch (B2JsonException e) { + throw new B2LocalException("parsing_failed", "can't convert response from json: " + e.getMessage(), e); + } + } + + + @Override + public void getContent(String url, + B2Headers headersOrNull, + B2ContentSink handler) throws B2Exception { + + final URL clientUrl = new URL(url); + URLConnection client; + if (clientUrl.getProtocol().equals("https")) { + client = (HttpsURLConnection) clientUrl.openConnection(); + } else { + client = (HttpURLConnection) clientUrl.openConnection(); + } + if (headersOrNull != null) { + makeHeaders(headersOrNull).forEach((name, value) -> get.setRequestProperty(name, value)); + } + client.setDoOutput(true); + // Autoclosable lambda used here to all the URLConnection client to close + try (AutoCloseable cxn = () -> client.disconnect()) { + final int statusCode = client.getResponseCode(); + if (200 <= statusCode && statusCode < 300) { + final DataInputStream contentStream = new DataInputStream(client.getInputStream()); + String contentString; + while ((String) contentLine = contentStream.readLine() != null) { + contentString.append(inputLine); + } + final InputStream content = client.getInputStream(); + handler.readContent(makeHeaders(client.getHeaderField()), content); + } else { + final Scanner input = new Scanner(new InputStreamReader(client.getInputStream())); + final StringBuilder response = new StringBuilder(); + String line; + while ((line = input.hasNext())) { + response.append(line); + } + input.close(); + throw extractExceptionFromErrorResponse(client, response.toString()); + } + } catch (IOException e) { + throw translateToB2Exception(e, clientUrl); + } + } + + /** + * HEADSs to a web service that returns content, and returns the headers. + * + * @param url the url to head to + * @param headersOrNull the headers, if any. + * @return the headers of the response. + * @throws B2Exception if there's any trouble + */ + @Override + public B2Headers head(String url, B2Headers headersOrNull) + throws B2Exception { + try { + final URL clientUrl = new URL(url); + URLConnection head; + if (clientUrl.getProtocol().equals("https")) { + head = (HttpsURLConnection) clientUrl.openConnection(); + } else { + head = (HttpURLConnection) clientUrl.openConnection(); + } + if (headersOrNull != null) { + makeHeaders(headersOrNull).forEach((name, value) -> head.setRequestProperty(name, value)); + } + head.setDoOutput(true); + int statusCode = head.getResponseCode(); + if (statusCode >= 200 && statusCode < 300) { + final B2HeadersImpl.Builder builder = B2HeadersImpl.builder(); + Arrays.stream(head.getHeaderFields().entrySet().forEach(header -> builder.set(header.getName(), header.getValue()))); + return builder.build(); + } else { + throw B2Exception.create(null, statusCode, null, ""); + } + } catch (IOException e) { + throw translateToB2Exception(e, url); + } + finally { + closeQuietly(response); + } + } + + @Override + public void close() { + clientFactory.close(); + } + + private String postJsonAndReturnString(String url, + B2Headers headersOrNull, + Object request) throws B2Exception { + String requestString = parseToStringUsingBzJson(request); + return postAndReturnString(url, headersOrNull, requestString); + } + + /** + * POSTs to a web service that returns content, and returns the content + * as a single string. + * + * @param url the url to post to + * @param headersOrNull the headers, if any. + * @param requestString the string to post. + * @return the body of the response. + * @throws B2Exception if there's any trouble + */ + private String postAndReturnString(String url, B2Headers headersOrNull, String requestString) + throws B2Exception { + + try { + final URLConnection post = new URL(url).openConnection(); + if (headersOrNull != null) { + makeHeaders(headersOrNull).forEach((name, value) -> post.setRequestProperty(name, value)); + } + if (requestString != null) { + // Sets the URLConnection client request to send + // https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setDoInput-boolean- + post.setDoOutput(true); + B2IoUtils.copy(requestEntity, post.getOutputStream()); + } + + try (Scanner in = new Scanner(new InputStreamReader(post.getInputStream()))) { + String line; + final StringBuilder responseText = new StringBuilder(); + while ((line = in.hasNext())) { + responseText.append(line); + } + in.close(); + } catch (Error e) { + throw translateToB2Exception(e, url); + } + + final int statusCode = post.getResponseCode(); + if (statusCode >= 200 && statusCode < 300) { + return responseText; + } else { + throw extractExceptionFromErrorResponse(response, responseText); + } + } catch (IOException e) { + throw translateToB2Exception(e, url); + } + finally { + closeQuietly(response); + } + } + + /** + * POSTs to a web service that returns content, and returns the content + * as a single string. + * + * @param url the url to post to + * @param headersOrNull the headers, if any. + * @param requestEntity the entity to post. + * @return the body of the response. + * @throws B2Exception if there's any trouble + */ + private String postAndReturnString(String url, B2Headers headersOrNull, InputStream requestEntity) + throws Exception { + + try { + final URLConnection post = new URL(url).openConnection(); + if (headersOrNull != null) { + makeHeaders(headersOrNull).forEach((name, value) -> post.setRequestProperty(name, value)); + } + if (requestString != null) { + // Sets the URLConnection client request to send + // https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setDoInput-boolean- + post.setDoOutput(true); + B2IoUtils.copy(requestEntity, post.getOutputStream()); + } + + final int statusCode = post.getResponseCode(); + if (statusCode >= 200 && statusCode < 300) { + try (Scanner in = new Scanner(new InputStreamReader(post.getInputStream()))) { + String line; + final StringBuilder responseText = new StringBuilder(); + + while ((line = in.hasNext())) { + responseText.append(line); + } + in.close(); + } catch (Error e) { + throw translateToB2Exception(e, url); + } + } else { + throw new Exception(response, responseText); + } + } catch (IOException e) { + throw translateToB2Exception(e, url); + } + finally { + closeQuietly(response); + } + } + + private B2Exception translateToB2Exception(IOException e, String url) { + if (e instanceof ConnectException) { + // java.net base class for HttpHostConnectException. + return new B2ConnectFailedException("connect_failed", null, "failed to connect for " + url, e); + } + if (e instanceof UnknownHostException) { + return new B2ConnectFailedException("unknown_host", null, "unknown host for " + url, e); + } + if (e instanceof SocketTimeoutException) { + return new B2NetworkTimeoutException("socket_timeout", null, "socket timed out talking to " + url, e); + } + if (e instanceof SocketException) { + return new B2NetworkException("socket_exception", null, "socket exception talking to " + url, e); + } + if (e instanceof MalformedURLException) { + return new B2NotFoundException("malformed_url", null, "malformed for " + url, e); + } + + return new B2NetworkException("io_exception", null, e + " talking to " + url, e); + } + + private B2Exception extractExceptionFromErrorResponse(Class response, + String responseText) { + final int statusCode = response.getResponseCode();; + // Try B2 error structure + try { + final B2ErrorStructure err = B2Json.get().fromJson(responseText, B2ErrorStructure.class); + return B2Exception.create(err.code, err.status, getRetryAfterSecondsOrNull(response), err.message); + } + catch (Throwable t) { + // we can't parse the response as a B2 JSON error structure. + // so use the default. + return new B2Exception("unknown", statusCode, getRetryAfterSecondsOrNull(response), responseText); + } + } + + /** + * If there's a Retry-After header and it has a delay-seconds formatted value, + * this returns it. (to be clear, if there's an HTTP-date value, we ignore it + * and keep looking for one with delay-seconds format.) + * + * @param response the http response. + * @return the delay-seconds from a Retry-After header, if any. otherwise, null. + */ + private Integer getRetryAfterSecondsOrNull(URLConnection response) { + // https://tools.ietf.org/html/rfc7231#section-7.1.3 + for (String header : response.getHeaderFields().get(B2Headers.RETRY_AFTER)) { + try { + return Integer.parseInt(header.getValue(), 10); + } catch (IllegalArgumentException e) { + throw translateToB2Exception(e, url); + } + } + + return null; + } + + private HashMap makeHeaders(B2Headers headersOrNull) { + if (headersOrNull == null) { + return new HashMap<>(); + } + final HashMap headers = new HashMap<>(); + + for (String name : headersOrNull.keySet()) { + headers.set(name, headersOrNull.getValueOrNull(name)); + } + + return headers; + } + + + /** + * Parse Json using our beloved B2Json + * + * @param request the object to be json'ified. + * @return a new ByteArrayEntity with the json representation of request in it. + */ + private static String parseToStringUsingBzJson(Object request) throws B2Exception { + B2Preconditions.checkArgument(request != null); + + try { + final B2Json bzJson = B2Json.get(); + return bzJson.toJson(request); + } catch (B2JsonException e) { + throw new B2LocalException("parsing_failed", "B2Json.toJson(" + request.getClass() + ") failed: " + e.getMessage(), e); + } + } + + /** + * Returns the UTF-8 representation of a string. + */ + private static byte [] getUtf8Bytes(String str) throws B2Exception { + try { + return str.getBytes(UTF8); + } catch (UnsupportedEncodingException e) { + // this is very, very bad and it's not gonna get better by itself. + throw new RuntimeException("No UTF-8 charset", e); + } + } + + /** + * This Builder creates HttpClientFactoryImpls. + * If the httpClientFactory isn't set, a new instance + * of the default implementation will be used. + */ + @SuppressWarnings("WeakerAccess") + public static class Builder { + private HttpClientFactory httpClientFactory; + + public Builder setHttpClientFactory(HttpClientFactory httpClientFactory) { + this.httpClientFactory = httpClientFactory; + return this; + } + + public B2WebApiHttpClientImpl build() { + return new B2WebApiHttpClientImpl(httpClientFactory); + } + } +} diff --git a/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/HttpClientFactory.java b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/HttpClientFactory.java new file mode 100644 index 000000000..46b42c839 --- /dev/null +++ b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/HttpClientFactory.java @@ -0,0 +1,32 @@ +/* + * Copyright 2020, Backblaze Inc. All Rights Reserved. + * License https://www.backblaze.com/using_b2_code.html + */ +package com.backblaze.b2.client.webApiUrlConnection.android.UrlConnection; + +import com.backblaze.b2.client.exceptions.B2Exception; +import java.net.URLConnection; + +public interface HttpClientFactory extends AutoCloseable { + + /** + * This returns a CloseableHttpClient (instead of an HttpClient) because + * the SDK needs to be able to close the responses to allow connections + * to be reused. + * + * Note that even though this returns a CloseableHttpClient, + * the SDK will *not* call close() on it, because doing so + * would close the client's HttpClientConnectionManager. + * + * @return a new httpClient for use by the SDK. + * this will be called often. + * @throws B2Exception if there's any trouble creating the client. + */ + URLConnection create() throws B2Exception; + + /** + * Called to release resources, such as an HttpClientConnectionManager. + */ + @Override + void close(); +} diff --git a/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/HttpClientFactoryImpl.java b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/HttpClientFactoryImpl.java new file mode 100644 index 000000000..e97dc7256 --- /dev/null +++ b/httpclient_android/http_client/src/main/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/HttpClientFactoryImpl.java @@ -0,0 +1,123 @@ +/* + * Copyright 2020, Backblaze Inc. All Rights Reserved. + * License https://www.backblaze.com/using_b2_code.html + */ +package com.backblaze.b2.client.webApiUrlConnection.android.UrlConnection; + +import android.util.Log; +import com.backblaze.b2.client.exceptions.B2Exception; +import com.backblaze.b2.util.B2Preconditions; + +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import javax.net.ssl.HttpsURLConnection; + +/** + * This is the default HttpClientFactory implementation. + * + * Created HttpClients always support 'https' because that's what the + * production B2 servers require. By default, the created HttpClients + * do not support 'http' to ensure we don't send data over http by accident. + * + * If you have a non-https implementation of B2 that you test against, + * you *may* choose to enable 'http' support when creating the factory. + * We really do *not* recommend that in production. + */ +public class HttpClientFactoryImpl implements HttpClientFactory { + private URLConnection connection; + private boolean supportInsecureHttp; + private int connectTimeoutSeconds; + private String url; + private final String TAG = "HTTP_CLIENT"; + + private HttpClientFactoryImpl(boolean supportInsecureHttp, int connectTimeoutSeconds) { + this.supportInsecureHttp = supportInsecureHttp; + this.connectTimeoutSeconds = connectTimeoutSeconds; + } + + @SuppressWarnings("WeakerAccess") + + public static HttpClientFactoryImpl build() { + return builder().build(); + } + + public static Builder builder() { + return new Builder(); + } + + /* + * Returns new HTTPClient instance + * */ + @Override + public URLConnection create() throws B2Exception { + try { + final URL url = new URL(this.url); + if (this.supportInsecureHttp) { + connection = (HttpsURLConnection) url.openConnection(); + } else { + connection = (HttpURLConnection) url.openConnection(); + } + connection.setInstanceFollowRedirects(false); + connection.setConnectTimeout(this.connectTimeoutSeconds); + return connection; + } catch (Error e) { + // Log + } + } + + @Override + public void close() { + try { + connection.disconnect(); + } catch (Error e) { + // restore the interrupt because we're not acting on it here. + if (e.getMessage() != null) { + Log.e(TAG, e.getMessage()); + } + } + } + + /** + * The factory we're building will have close() called on it and when it + * does, it will close its connection manager. Since we don't want to + * close a connection manager out from under another factory, each Builder + * is only allowed to execute build() once. + */ + public static class Builder { + // Defaults + private static final int DEFAULT_CONNECT_TIMEOUT_SECONDS = 5; + private static final boolean DEFAULT_SUPPORT_INSECURE_HTTP = false; + + + // Builder values + private boolean builtOneAlready; + + // should the clients support 'http'? (they always support 'https'.) + // this is off by default, and that's a good way to leave it. + // http is only supported for use with some test environments. + private boolean supportInsecureHttp = DEFAULT_SUPPORT_INSECURE_HTTP; + private int connectTimeoutSeconds = DEFAULT_CONNECT_TIMEOUT_SECONDS; + + public Builder setSupportInsecureHttp(boolean supportInsecureHttp) { + this.supportInsecureHttp = supportInsecureHttp; + return this; + } + + public Builder setConnectionTimeout(int connectTimeoutSeconds) { + this.connectTimeoutSeconds = connectTimeoutSeconds; + return this; + } + + public HttpClientFactoryImpl build() { + B2Preconditions.checkState(!builtOneAlready, "called build() more than once?!"); + builtOneAlready = true; + + return new HttpClientFactoryImpl( + this.supportInsecureHttp, + this.connectTimeoutSeconds + ); + } + } +} \ No newline at end of file diff --git a/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientBuilderTest.java b/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientBuilderTest.java new file mode 100644 index 000000000..94428b07c --- /dev/null +++ b/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientBuilderTest.java @@ -0,0 +1,56 @@ +package com.backblaze.b2.client.webApiUrlConnection.android.UrlConnection; + +import com.backblaze.b2.client.B2RetryPolicy; +import com.backblaze.b2.client.B2StorageClient; +import com.backblaze.b2.client.B2StorageClientImpl; + +import org.junit.Test; + +import java.util.function.Supplier; + +import static org.junit.Assert.*; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class B2StorageHttpClientBuilderTest { + + @Test + public void B2StorageHttpClientBuilder_builder() { + final B2StorageHttpClientBuilder builder = new B2StorageHttpClientBuilder.builder(); + assertNotNull(builder); + } + + @Test + public void B2StorageHttpClientBuilder_build() { + final B2StorageClient factory = new B2StorageHttpClientBuilder.build(); + assertNotNull(factory); + } + + @Test + public void B2StorageHttpClientBuilder_setHttpClientFactory() { + final HttpClientFactory clientFactory = HttpClientFactoryImpl.build(); + final B2StorageClient factory = new B2StorageHttpClientBuilder.build(); + final B2StorageHttpClientBuilder factoryTwo = factory.setHttpClientFactory(clientFactory); + assertNotNull(factoryTwo); + } + + @Test + public void B2StorageHttpClientBuilder_setWebApiClient() { + final B2ClientConfig config = B2ClientConfig.builder("api-key-id", "api-key", "user-agent").build(); + final B2StorageClient client = B2StorageHttpClientBuilder.builder(config).build() + final B2StorageClientImpl factory = B2StorageHttpClientBuilder.build(); + final B2StorageHttpClientBuilder factoryTwo = factory.setWebApiClient(client); + assertNotNull(factory); + } + + @Test + public void B2StorageHttpClientBuilder_setRetryPolicySupplier() { + final Supplier supplier = B2DefaultRetryPolicy.supplier(); + final B2StorageClient factory = new B2StorageHttpClientBuilder.build(); + final B2StorageHttpClientBuilder factoryTwo = factory.setRetryPolicySupplier(supplier); + assertNotNull(factoryTwo); + } +} diff --git a/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientFactoryTest.java b/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientFactoryTest.java new file mode 100644 index 000000000..2fee1fa64 --- /dev/null +++ b/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2StorageHttpClientFactoryTest.java @@ -0,0 +1,31 @@ +/* + * Copyright 2020, Backblaze Inc. All Rights Reserved. + * License https://www.backblaze.com/using_b2_code.html + */ +package com.backblaze.b2.client.webApiUrlConnection.android.http_client; + +import com.backblaze.b2.client.B2StorageClientFactory; +import com.backblaze.b2.client.B2StorageClientFactoryPathBasedImpl; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class B2StorageHttpClientFactoryTest { + + @Test + public void testCreate() { + // this is mostly to keep B2StorageHttpClientFactory from being unused. + final B2StorageHttpClientFactory factory = new B2StorageHttpClientFactory(); + assertNotNull(factory); + } + + // Same as B2StorageClientFactory#create test + @Test + public void testDefaultFactory_succeedsBecauseTestEnvironmentIncludesHttpClientJars() { + final B2StorageClientFactory factory = B2StorageClientFactory.createDefaultFactory(); + assertTrue(factory instanceof B2StorageClientFactoryPathBasedImpl); + + assertNotNull(factory.create("appKeyId", "appKey", "userAgent")); + } +} diff --git a/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2WebApiHttpClientImplTest.java b/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2WebApiHttpClientImplTest.java new file mode 100644 index 000000000..83a6442ba --- /dev/null +++ b/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/B2WebApiHttpClientImplTest.java @@ -0,0 +1,26 @@ +package com.backblaze.b2.client.webApiUrlConnection.android.UrlConnection; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class B2WebApiHttpClientImplTest { + + @Test + public void B2WebApiHttpClientImpl_build() { + final B2StorageHttpClientBuilder factory = B2WebApiHttpClientImpl.build(); + assertNotNull(factory); + } + + @Test + public void B2WebApiHttpClientImpl_builder() { + final B2WebApiHttpClientImpl.Builder builder = B2WebApiHttpClientImpl.builder(); + assertNotNull(builder); + } + +} diff --git a/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/HttpClientFactoryImplTest.java b/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/HttpClientFactoryImplTest.java new file mode 100644 index 000000000..10fdeffea --- /dev/null +++ b/httpclient_android/http_client/src/test/java/com/backblaze/b2/client/webapiurlconnection/android/UrlConnection/HttpClientFactoryImplTest.java @@ -0,0 +1,47 @@ +package com.backblaze.b2.client.webApiUrlConnection.android.http_client; + +import android.util.Log; + +import androidx.annotation.Nullable; + +import com.backblaze.b2.client.exceptions.B2Exception; + +import org.junit.Test; + +import java.io.IOException; +import java.net.URLConnection; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.*; + +/** + * + */ +public class HttpClientFactoryImplTest { + + @Test + public void HttpClientFactoryImpl_build() { + final HttpClientFactoryImpl factory = HttpClientFactoryImpl.build(); + assertNotNull(factory); + } + + @Test + public void HttpClientFactoryImpl_builder() { + final HttpClientFactoryImpl.Builder builder = HttpClientFactoryImpl.builder(); + assertNotNull(builder); + } + + @Test + public void HttpClientFactoryImpl_create() throws B2Exception, IOException { + final HttpClientFactoryImpl factory = HttpClientFactoryImpl.build(); + final URLConnection cxn = factory.create(); + assertNotNull(cxn); + } + + @Test + public void HttpClientFactoryImpl_close() { + final HttpClientFactoryImpl factory = HttpClientFactoryImpl.build(); + final URLConnection cxn = factory.create(); + cxn.close(); + } +} diff --git a/httpclient_android/settings.gradle b/httpclient_android/settings.gradle new file mode 100644 index 000000000..34d139d99 --- /dev/null +++ b/httpclient_android/settings.gradle @@ -0,0 +1,3 @@ +include ':http_client' +include ':app' +rootProject.name = "B2WebApiHttpClientAndroid" \ No newline at end of file