diff --git a/src/client/Java/.gitignore b/src/client/Java/.gitignore deleted file mode 100644 index f1c8123eca4b5..0000000000000 --- a/src/client/Java/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -build -*.class -target -gen - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ -tmp - -# Package Files # -*.jar -*.war -*.ear -*.MF -.gitrevision -.gradle - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# ide -.idea -*.iml diff --git a/src/client/Java/.travis.yml b/src/client/Java/.travis.yml deleted file mode 100644 index 05c26fa53735e..0000000000000 --- a/src/client/Java/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: android -android: - components: - - build-tools-23.0.1 - - android-23 - - platform-tools - - extra-android-support - - extra-google-m2repository - - extra-android-m2repository -sudo: false -script: - - mvn clean install - - mvn checkstyle:check - - cd ./azure-android-client-authentication && ./gradlew check diff --git a/src/client/Java/LICENSE b/src/client/Java/LICENSE deleted file mode 100644 index 4918d653ba68b..0000000000000 --- a/src/client/Java/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Microsoft Azure - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/src/client/Java/README.md b/src/client/Java/README.md deleted file mode 100644 index dfa96fbf28cbf..0000000000000 --- a/src/client/Java/README.md +++ /dev/null @@ -1,22 +0,0 @@ -[![Build Status](https://travis-ci.org/Azure/autorest-clientruntime-for-java.svg?branch=javavnext)](https://travis-ci.org/Azure/autorest-clientruntime-for-java) - -# AutoRest Client Runtimes for Java -The runtime libraries for AutoRest generated Java clients. - -## Repository structure - -### client-runtime -This is the generic runtime. You will need this for AutoRest generated library using Java code generator. - -### azure-client-runtime -This is the runtime with Azure specific customizations. You will need this for AutoRest generated library using Azure.Java code generator. - -### azure-client-authentication -This package provides access to Active Directory authentication on JDK using OrgId or application ID / secret combinations. Multi-factor-auth is currently not supported. - -### azure-android-client-authentication -This package provides access to Active Directory authentication on Android. You can login with Microsoft accounts, OrgId, with or without multi-factor-auth. - -## Build -To build this repository, you will need maven 2.0+ and gradle 1.6+. -Maven is used for [Java SDK](https://github.com/Azure/azure-sdk-for-java) when it's used as a submodule in there. Gradle is used for [AutoRest](https://github.com/Azure/autorest) when it's used as a submodule in there. diff --git a/src/client/Java/azure-android-client-authentication/build.gradle b/src/client/Java/azure-android-client-authentication/build.gradle deleted file mode 100644 index 2651d8389383e..0000000000000 --- a/src/client/Java/azure-android-client-authentication/build.gradle +++ /dev/null @@ -1,117 +0,0 @@ -buildscript { - repositories { - mavenCentral() - } - dependencies { - classpath 'com.android.tools.build:gradle:1.3.0' - } -} - -apply plugin: 'com.android.library' -apply plugin: 'maven' - -android { - compileSdkVersion 23 - buildToolsVersion "23.0.1" - - defaultConfig { - minSdkVersion 15 - targetSdkVersion 23 - versionCode 1 - versionName "1.0.0-SNAPSHOT" - } - - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - } - - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - lintOptions { - abortOnError false - } -} - -configurations { - deployerJars -} - -repositories { - mavenCentral() - maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } -} - -dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) - compile 'com.android.support:appcompat-v7:23.0.1' - compile 'com.microsoft.aad:adal:1.1.11' - compile 'com.microsoft.azure:azure-client-runtime:1.0.0-SNAPSHOT' - testCompile 'junit:junit:4.12' - testCompile 'junit:junit-dep:4.11' - deployerJars "org.apache.maven.wagon:wagon-ftp:2.10" -} - -uploadArchives { - repositories { - mavenDeployer { - configuration = configurations.deployerJars - snapshotRepository(url: "ftp://waws-prod-bay-005.ftp.azurewebsites.windows.net/site/wwwroot/") { - authentication(userName: username, password: password) - } - repository(url: "file://$buildDir/repository") - pom.setArtifactId "azure-android-client-authentication" - pom.project { - name 'Microsoft Azure AutoRest Authentication Library for Java' - description 'This is the authentication library for AutoRest generated Azure Java clients.' - url 'https://github.com/Azure/autorest' - - scm { - url 'scm:git:https://github.com/Azure/AutoRest' - connection 'scm:git:git://github.com/Azure/AutoRest.git' - } - - licenses { - license { - name 'The MIT License (MIT)' - url 'http://opensource.org/licenses/MIT' - distribution 'repo' - } - } - - developers { - developer { - id 'microsoft' - name 'Microsoft' - } - } - } - } - } -} - -task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' -} - -task javadoc(type: Javadoc) { - source = android.sourceSets.main.java.srcDirs - classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) - options.encoding = 'UTF-8' -} - -task javadocJar(type: Jar, dependsOn: [javadoc]) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -artifacts { - archives sourcesJar - archives javadocJar -} diff --git a/src/client/Java/azure-android-client-authentication/gradle.properties b/src/client/Java/azure-android-client-authentication/gradle.properties deleted file mode 100644 index 7311d1b56e3bb..0000000000000 --- a/src/client/Java/azure-android-client-authentication/gradle.properties +++ /dev/null @@ -1,2 +0,0 @@ -username = fake -password = fake \ No newline at end of file diff --git a/src/client/Java/azure-android-client-authentication/gradle/wrapper/gradle-wrapper.jar b/src/client/Java/azure-android-client-authentication/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 05ef575b0cd01..0000000000000 Binary files a/src/client/Java/azure-android-client-authentication/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/src/client/Java/azure-android-client-authentication/gradle/wrapper/gradle-wrapper.properties b/src/client/Java/azure-android-client-authentication/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 3ae0abbd2b66d..0000000000000 --- a/src/client/Java/azure-android-client-authentication/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Wed Nov 11 13:21:00 PST 2015 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-bin.zip diff --git a/src/client/Java/azure-android-client-authentication/gradlew b/src/client/Java/azure-android-client-authentication/gradlew deleted file mode 100755 index 9d82f78915133..0000000000000 --- a/src/client/Java/azure-android-client-authentication/gradlew +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# 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 -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; -esac - -# 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 - -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" ] ; 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 - -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/src/client/Java/azure-android-client-authentication/gradlew.bat b/src/client/Java/azure-android-client-authentication/gradlew.bat deleted file mode 100644 index 8a0b282aa6885..0000000000000 --- a/src/client/Java/azure-android-client-authentication/gradlew.bat +++ /dev/null @@ -1,90 +0,0 @@ -@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 - -@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= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@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 Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_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=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -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/src/client/Java/azure-android-client-authentication/proguard-rules.pro b/src/client/Java/azure-android-client-authentication/proguard-rules.pro deleted file mode 100644 index 51508f487ebc5..0000000000000 --- a/src/client/Java/azure-android-client-authentication/proguard-rules.pro +++ /dev/null @@ -1,17 +0,0 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in E:\Users\jianghlu\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# 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 *; -#} diff --git a/src/client/Java/azure-android-client-authentication/src/main/AndroidManifest.xml b/src/client/Java/azure-android-client-authentication/src/main/AndroidManifest.xml deleted file mode 100644 index 281c2ce4932ba..0000000000000 --- a/src/client/Java/azure-android-client-authentication/src/main/AndroidManifest.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - diff --git a/src/client/Java/azure-android-client-authentication/src/main/java/com/microsoft/azure/credentials/AzureEnvironment.java b/src/client/Java/azure-android-client-authentication/src/main/java/com/microsoft/azure/credentials/AzureEnvironment.java deleted file mode 100644 index dd8a1a2dc9de9..0000000000000 --- a/src/client/Java/azure-android-client-authentication/src/main/java/com/microsoft/azure/credentials/AzureEnvironment.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure.credentials; - -/** - * An instance of this class describes an environment in Azure. - */ -public final class AzureEnvironment { - /** - * ActiveDirectory Endpoint for the Azure Environment. - */ - private String authenticationEndpoint; - /** - * Token audience for an endpoint. - */ - private String tokenAudience; - /** - * Determines whether the authentication endpoint should - * be validated with Azure AD. Default value is true. - */ - private boolean validateAuthority; - - /** - * Initializes an instance of AzureEnvironment class. - * - * @param authenticationEndpoint ActiveDirectory Endpoint for the Azure Environment. - * @param tokenAudience token audience for an endpoint. - * @param validateAuthority whether the authentication endpoint should - * be validated with Azure AD. - */ - public AzureEnvironment(String authenticationEndpoint, String tokenAudience, boolean validateAuthority) { - this.authenticationEndpoint = authenticationEndpoint; - this.tokenAudience = tokenAudience; - this.validateAuthority = validateAuthority; - } - - /** - * Provides the settings for authentication with Azure. - */ - public static final AzureEnvironment AZURE = new AzureEnvironment( - "https://login.windows.net/", - "https://management.core.windows.net/", - true); - - /** - * Provides the settings for authentication with Azure China. - */ - public static final AzureEnvironment AZURE_CHINA = new AzureEnvironment( - "https://login.chinacloudapi.cn/", - "https://management.core.chinacloudapi.cn/", - true); - - /** - * Gets the ActiveDirectory Endpoint for the Azure Environment. - * - * @return the ActiveDirectory Endpoint for the Azure Environment. - */ - public String getAuthenticationEndpoint() { - return authenticationEndpoint; - } - - /** - * Gets the token audience for an endpoint. - * - * @return the token audience for an endpoint. - */ - public String getTokenAudience() { - return tokenAudience; - } - - /** - * Gets whether the authentication endpoint should - * be validated with Azure AD. - * - * @return true if the authentication endpoint should be validated with - * Azure AD, false otherwise. - */ - public boolean isValidateAuthority() { - return validateAuthority; - } -} diff --git a/src/client/Java/azure-android-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java b/src/client/Java/azure-android-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java deleted file mode 100644 index f52654e78db53..0000000000000 --- a/src/client/Java/azure-android-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java +++ /dev/null @@ -1,190 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure.credentials; - -import android.app.Activity; - -import com.microsoft.aad.adal.AuthenticationCallback; -import com.microsoft.aad.adal.AuthenticationContext; -import com.microsoft.aad.adal.AuthenticationResult; -import com.microsoft.aad.adal.DefaultTokenCacheStore; -import com.microsoft.aad.adal.PromptBehavior; -import com.microsoft.rest.credentials.TokenCredentials; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.util.concurrent.CountDownLatch; - -import javax.crypto.NoSuchPaddingException; - -/** - * Token based credentials for use with a REST Service Client. - */ -public class UserTokenCredentials extends TokenCredentials { - /** The Active Directory application client id. */ - private String clientId; - /** The domain or tenant id containing this application. */ - private String domain; - /** The Uri where the user will be redirected after authenticating with AD. */ - private String clientRedirectUri; - /** The Azure environment to authenticate with. */ - private AzureEnvironment environment; - /** The caller activity. */ - private Activity activity; - /** The count down latch to synchronize token acquisition. */ - private CountDownLatch signal = new CountDownLatch(1); - /** The static token cache. */ - private static DefaultTokenCacheStore tokenCacheStore; - /** The behavior of when to prompt a login. */ - private PromptBehavior promptBehavior; - - /** - * Initializes a new instance of the UserTokenCredentials. - * - * @param activity The caller activity. - * @param clientId the active directory application client id. - * @param domain the domain or tenant id containing this application. - * @param clientRedirectUri the Uri where the user will be redirected after authenticating with AD. - */ - public UserTokenCredentials( - Activity activity, - String clientId, - String domain, - String clientRedirectUri) { - this(activity, clientId, domain, clientRedirectUri, PromptBehavior.Auto, AzureEnvironment.AZURE); - } - - /** - * Initializes a new instance of the UserTokenCredentials. - * - * @param activity The caller activity. - * @param clientId the active directory application client id. - * @param domain the domain or tenant id containing this application. - * @param clientRedirectUri the Uri where the user will be redirected after authenticating with AD. - * @param promptBehavior the behavior of when to prompt a login. - * @param environment the Azure environment to authenticate with. - * If null is provided, AzureEnvironment.AZURE will be used. - */ - public UserTokenCredentials( - Activity activity, - String clientId, - String domain, - String clientRedirectUri, - PromptBehavior promptBehavior, - AzureEnvironment environment) { - super(null, null); // defer token acquisition - this.clientId = clientId; - this.domain = domain; - this.clientRedirectUri = clientRedirectUri; - this.activity = activity; - this.promptBehavior = promptBehavior; - this.environment = environment; - if (tokenCacheStore == null) { - try { - tokenCacheStore = new DefaultTokenCacheStore(activity); - } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { - tokenCacheStore = null; - } - } - } - - /** - * Clear the items stored in token cache. - */ - public static void clearTokenCache() { - tokenCacheStore.removeAll(); - } - - /** - * Gets the active directory application client id. - * - * @return the active directory application client id. - */ - public String getClientId() { - return clientId; - } - - /** - * Gets the tenant or domain containing the application. - * - * @return the tenant or domain containing the application. - */ - public String getDomain() { - return domain; - } - - /** - * Sets the tenant of domain containing the application. - * - * @param domain the tenant or domain containing the application. - */ - public void setDomain(String domain) { - this.domain = domain; - } - - /** - * Gets the Uri where the user will be redirected after authenticating with AD. - * - * @return the redirecting Uri. - */ - public String getClientRedirectUri() { - return clientRedirectUri; - } - - /** - * Gets the Azure environment to authenticate with. - * - * @return the Azure environment to authenticate with. - */ - public AzureEnvironment getEnvironment() { - return environment; - } - - @Override - public String getToken() throws IOException { - refreshToken(); - return token; - } - - @Override - public void refreshToken() throws IOException { - acquireAccessToken(); - } - - private void acquireAccessToken() throws IOException { - final String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); - AuthenticationContext context = new AuthenticationContext(activity, authorityUrl, true, tokenCacheStore); - final UserTokenCredentials self = this; - context.acquireToken( - this.getEnvironment().getTokenAudience(), - this.getClientId(), - this.getClientRedirectUri(), - null, - promptBehavior, - null, - new AuthenticationCallback() { - @Override - public void onSuccess(AuthenticationResult authenticationResult) { - if (authenticationResult != null && authenticationResult.getAccessToken() != null) { - self.setToken(authenticationResult.getAccessToken()); - signal.countDown(); - } else { - onError(new IOException("Failed to acquire access token")); - } - } - - @Override - public void onError(Exception e) { - signal.countDown(); - } - }); - try { - signal.await(); - } catch (InterruptedException e) { /* Ignore */ } - } -} diff --git a/src/client/Java/azure-android-client-authentication/src/main/java/com/microsoft/azure/credentials/package-info.java b/src/client/Java/azure-android-client-authentication/src/main/java/com/microsoft/azure/credentials/package-info.java deleted file mode 100644 index 2f23671d5be16..0000000000000 --- a/src/client/Java/azure-android-client-authentication/src/main/java/com/microsoft/azure/credentials/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * The package provides 2 credential classes that work with AutoRest - * generated Azure clients for authentication purposes through Azure. - */ -package com.microsoft.azure.credentials; \ No newline at end of file diff --git a/src/client/Java/azure-android-client-authentication/src/main/res/values/strings.xml b/src/client/Java/azure-android-client-authentication/src/main/res/values/strings.xml deleted file mode 100644 index e2639a86a6c96..0000000000000 --- a/src/client/Java/azure-android-client-authentication/src/main/res/values/strings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - azure-android-client-authentication - diff --git a/src/client/Java/azure-client-authentication/build.gradle b/src/client/Java/azure-client-authentication/build.gradle deleted file mode 100644 index 65c1c86a20a36..0000000000000 --- a/src/client/Java/azure-client-authentication/build.gradle +++ /dev/null @@ -1,98 +0,0 @@ -buildscript { - repositories { - jcenter() - } - dependencies { - classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.2' - } -} - -apply plugin: 'java' -apply plugin: 'checkstyle' - -version = '1.0.0-SNAPSHOT' - -checkstyle { - toolVersion = "6.18" - configFile = new File("$rootDir/src/client/Java/build-tools/src/main/resources/checkstyle.xml") - configProperties = [samedir: "$rootDir/src/client/Java/build-tools/src/main/resources"] - reportsDir = new File("$rootDir/src/client/Java/build-tools/reports") -} - -dependencies { - compile 'com.microsoft.azure:adal4j:1.1.2' - compile 'com.microsoft.azure:azure-client-runtime:1.0.0-SNAPSHOT' - testCompile 'junit:junit:4.12' - testCompile 'junit:junit-dep:4.11' - deployerJars "org.apache.maven.wagon:wagon-ftp:2.10" -} - -uploadArchives { - repositories { - mavenDeployer { - configuration = configurations.deployerJars - snapshotRepository(url: "ftp://waws-prod-bay-005.ftp.azurewebsites.windows.net/site/wwwroot/") { - authentication(userName: username, password: password) - } - repository(url: "file://$buildDir/repository") - pom.setArtifactId "azure-client-authentication" - pom.project { - name 'Microsoft Azure AutoRest Authentication Library for Java' - description 'This is the authentication library for AutoRest generated Azure Java clients.' - url 'https://github.com/Azure/autorest' - - scm { - url 'scm:git:https://github.com/Azure/AutoRest' - connection 'scm:git:git://github.com/Azure/AutoRest.git' - } - - licenses { - license { - name 'The MIT License (MIT)' - url 'http://opensource.org/licenses/MIT' - distribution 'repo' - } - } - - developers { - developer { - id 'microsoft' - name 'Microsoft' - } - } - } - } - } -} - -test { - testLogging { - events "passed", "skipped", "failed", "standardError" - } -} - -javadoc { - options.encoding = 'UTF-8' -} - -task sourcesJar(type: Jar, dependsOn:classes) { - classifier = 'sources' - from sourceSets.main.allSource -} - -task javadocJar(type: Jar, dependsOn: [javadoc]) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -artifacts { - archives sourcesJar - archives javadocJar -} - -test { - reports.getHtml() - reports.html.destination = file("$rootDir/TestResults/JavaAzureRuntime") -} - -tasks.compileJava.dependsOn 'clean' diff --git a/src/client/Java/azure-client-authentication/pom.xml b/src/client/Java/azure-client-authentication/pom.xml deleted file mode 100644 index 47582ca1eaa87..0000000000000 --- a/src/client/Java/azure-client-authentication/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - 4.0.0 - - com.microsoft.azure - autorest-clientruntime-for-java - 1.0.0-SNAPSHOT - ../pom.xml - - - azure-client-authentication - jar - - Azure Java Client Authentication Library for AutoRest - This package contains the authentication connectors to Active Directory for JDK. - https://github.com/Azure/autorest-clientruntime-for-java - - - - The MIT License (MIT) - http://opensource.org/licenses/MIT - repo - - - - - scm:git:https://github.com/Azure/autorest-clientruntime-for-java - scm:git:git@github.com:Azure/autorest-clientruntime-for-java.git - HEAD - - - - UTF-8 - - - - - - microsoft - Microsoft - - - - - - com.microsoft.azure - azure-client-runtime - 1.0.0-SNAPSHOT - - - com.microsoft.azure - adal4j - - - junit - junit - test - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.7 - 1.7 - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - - org.codehaus.mojo - build-helper-maven-plugin - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage - /** -
* Copyright (c) Microsoft Corporation. All rights reserved. -
* Licensed under the MIT License. See License.txt in the project root for -
* license information. -
*/]]>
-
-
- -
-
-
diff --git a/src/client/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java b/src/client/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java deleted file mode 100644 index 384ab3f7671af..0000000000000 --- a/src/client/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java +++ /dev/null @@ -1,224 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure.credentials; - -import com.microsoft.aad.adal4j.AuthenticationContext; -import com.microsoft.aad.adal4j.AuthenticationResult; -import com.microsoft.aad.adal4j.ClientCredential; -import com.microsoft.azure.AzureEnvironment; -import com.microsoft.rest.credentials.TokenCredentials; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Token based credentials for use with a REST Service Client. - */ -public class ApplicationTokenCredentials extends TokenCredentials { - /** The active directory application client id. */ - private String clientId; - /** The tenant or domain the containing the application. */ - private String domain; - /** The authentication secret for the application. */ - private String secret; - /** The Azure environment to authenticate with. */ - private AzureEnvironment environment; - /** The current authentication result. */ - private AuthenticationResult authenticationResult; - /** The default subscription to use, if any. */ - private String defaultSubscription; - - /** - * Initializes a new instance of the UserTokenCredentials. - * - * @param clientId the active directory application client id. - * @param domain the domain or tenant id containing this application. - * @param secret the authentication secret for the application. - * @param environment the Azure environment to authenticate with. - * If null is provided, AzureEnvironment.AZURE will be used. - */ - public ApplicationTokenCredentials(String clientId, String domain, String secret, AzureEnvironment environment) { - super(null, null); // defer token acquisition - this.clientId = clientId; - this.domain = domain; - this.secret = secret; - if (environment == null) { - this.environment = AzureEnvironment.AZURE; - } else { - this.environment = environment; - } - } - - /** - * Contains the keys of the settings in a Properties file to read credentials from. - */ - private enum CredentialSettings { - /** The subscription GUID. */ - SUBSCRIPTION_ID("subscription"), - /** The tenant GUID or domain. */ - TENANT_ID("tenant"), - /** The client id for the client application. */ - CLIENT_ID("client"), - /** The client secret for the service principal. */ - CLIENT_KEY("key"), - /** The management endpoint. */ - MANAGEMENT_URI("managementURI"), - /** The base URL to the current Azure environment. */ - BASE_URL("baseURL"), - /** The URL to Active Directory authentication. */ - AUTH_URL("authURL"); - - /** The name of the key in the properties file. */ - private final String name; - - CredentialSettings(String name) { - this.name = name; - } - - @Override - public String toString() { - return this.name; - } - } - - /** - * @return The default subscription ID, if any - */ - public String defaultSubscriptionId() { - return defaultSubscription; - } - - /** - * Set default subscription ID. - * - * @param subscriptionId the default subscription ID. - * @return the credentials object itself. - */ - public ApplicationTokenCredentials withDefaultSubscriptionId(String subscriptionId) { - this.defaultSubscription = subscriptionId; - return this; - } - - /** - * Initializes the credentials based on the provided credentials file. - * - * @param credentialsFile A file with credentials, using the standard Java properties format. - * and the following keys: - * subscription=<subscription-id> - * tenant=<tenant-id> - * client=<client-id> - * key=<client-key> - * managementURI=<management-URI> - * baseURL=<base-URL> - * authURL=<authentication-URL> - * - * @return The credentials based on the file. - * @throws IOException exception thrown from file access errors. - */ - public static ApplicationTokenCredentials fromFile(File credentialsFile) throws IOException { - // Set defaults - Properties authSettings = new Properties(); - authSettings.put(CredentialSettings.AUTH_URL.toString(), AzureEnvironment.AZURE.getAuthenticationEndpoint()); - authSettings.put(CredentialSettings.BASE_URL.toString(), AzureEnvironment.AZURE.getBaseUrl()); - authSettings.put(CredentialSettings.MANAGEMENT_URI.toString(), AzureEnvironment.AZURE.getTokenAudience()); - - // Load the credentials from the file - FileInputStream credentialsFileStream = new FileInputStream(credentialsFile); - authSettings.load(credentialsFileStream); - credentialsFileStream.close(); - - final String clientId = authSettings.getProperty(CredentialSettings.CLIENT_ID.toString()); - final String tenantId = authSettings.getProperty(CredentialSettings.TENANT_ID.toString()); - final String clientKey = authSettings.getProperty(CredentialSettings.CLIENT_KEY.toString()); - final String mgmtUri = authSettings.getProperty(CredentialSettings.MANAGEMENT_URI.toString()); - final String authUrl = authSettings.getProperty(CredentialSettings.AUTH_URL.toString()); - final String baseUrl = authSettings.getProperty(CredentialSettings.BASE_URL.toString()); - final String defaultSubscriptionId = authSettings.getProperty(CredentialSettings.SUBSCRIPTION_ID.toString()); - - return new ApplicationTokenCredentials( - clientId, - tenantId, - clientKey, - new AzureEnvironment( - authUrl, - mgmtUri, - true, - baseUrl) - ).withDefaultSubscriptionId(defaultSubscriptionId); - } - - /** - * Gets the active directory application client id. - * - * @return the active directory application client id. - */ - public String getClientId() { - return clientId; - } - - /** - * Gets the tenant or domain the containing the application. - * - * @return the tenant or domain the containing the application. - */ - public String getDomain() { - return domain; - } - - /** - * Gets the authentication secret for the application. - * - * @return the authentication secret for the application. - */ - public String getSecret() { - return secret; - } - - /** - * Gets the Azure environment to authenticate with. - * - * @return the Azure environment to authenticate with. - */ - public AzureEnvironment getEnvironment() { - return environment; - } - - @Override - public String getToken() throws IOException { - if (authenticationResult == null - || authenticationResult.getAccessToken() == null) { - acquireAccessToken(); - } - return authenticationResult.getAccessToken(); - } - - @Override - public void refreshToken() throws IOException { - acquireAccessToken(); - } - - private void acquireAccessToken() throws IOException { - String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); - ExecutorService executor = Executors.newSingleThreadExecutor(); - AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), executor); - try { - authenticationResult = context.acquireToken( - this.getEnvironment().getTokenAudience(), - new ClientCredential(this.getClientId(), this.getSecret()), - null).get(); - } catch (Exception e) { - throw new IOException(e.getMessage(), e); - } finally { - executor.shutdown(); - } - } -} diff --git a/src/client/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java b/src/client/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java deleted file mode 100644 index 60d6bdb3c0a58..0000000000000 --- a/src/client/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure.credentials; - -import com.microsoft.aad.adal4j.AuthenticationContext; -import com.microsoft.aad.adal4j.AuthenticationResult; -import com.microsoft.azure.AzureEnvironment; -import com.microsoft.rest.credentials.TokenCredentials; - -import java.io.IOException; -import java.util.Date; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Token based credentials for use with a REST Service Client. - */ -public class UserTokenCredentials extends TokenCredentials { - /** The Active Directory application client id. */ - private String clientId; - /** The domain or tenant id containing this application. */ - private String domain; - /** The user name for the Organization Id account. */ - private String username; - /** The password for the Organization Id account. */ - private String password; - /** The Uri where the user will be redirected after authenticating with AD. */ - private String clientRedirectUri; - /** The Azure environment to authenticate with. */ - private AzureEnvironment environment; - /** The current authentication result. */ - private AuthenticationResult authenticationResult; - - /** - * Initializes a new instance of the UserTokenCredentials. - * - * @param clientId the active directory application client id. - * @param domain the domain or tenant id containing this application. - * @param username the user name for the Organization Id account. - * @param password the password for the Organization Id account. - * @param clientRedirectUri the Uri where the user will be redirected after authenticating with AD. - * @param environment the Azure environment to authenticate with. - * If null is provided, AzureEnvironment.AZURE will be used. - */ - public UserTokenCredentials(String clientId, String domain, String username, String password, String clientRedirectUri, AzureEnvironment environment) { - super(null, null); // defer token acquisition - this.clientId = clientId; - this.domain = domain; - this.username = username; - this.password = password; - this.clientRedirectUri = clientRedirectUri; - if (environment == null) { - this.environment = AzureEnvironment.AZURE; - } else { - this.environment = environment; - } - } - - /** - * Gets the active directory application client id. - * - * @return the active directory application client id. - */ - public String getClientId() { - return clientId; - } - - /** - * Gets the tenant or domain the containing the application. - * - * @return the tenant or domain the containing the application. - */ - public String getDomain() { - return domain; - } - - /** - * Gets the user name for the Organization Id account. - * - * @return the user name. - */ - public String getUsername() { - return username; - } - - /** - * Gets the password for the Organization Id account. - * - * @return the password. - */ - public String getPassword() { - return password; - } - - /** - * Gets the Uri where the user will be redirected after authenticating with AD. - * - * @return the redirecting Uri. - */ - public String getClientRedirectUri() { - return clientRedirectUri; - } - - /** - * Gets the Azure environment to authenticate with. - * - * @return the Azure environment to authenticate with. - */ - public AzureEnvironment getEnvironment() { - return environment; - } - - @Override - public String getToken() throws IOException { - if (authenticationResult != null - && authenticationResult.getExpiresOnDate().before(new Date())) { - acquireAccessTokenFromRefreshToken(); - } else { - acquireAccessToken(); - } - return authenticationResult.getAccessToken(); - } - - @Override - public void refreshToken() throws IOException { - acquireAccessToken(); - } - - private void acquireAccessToken() throws IOException { - String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); - AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), Executors.newSingleThreadExecutor()); - try { - authenticationResult = context.acquireToken( - this.getEnvironment().getTokenAudience(), - this.getClientId(), - this.getUsername(), - this.getPassword(), - null).get(); - } catch (Exception e) { - throw new IOException(e.getMessage(), e); - } - } - - private void acquireAccessTokenFromRefreshToken() throws IOException { - String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); - ExecutorService executor = Executors.newSingleThreadExecutor(); - AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), executor); - try { - authenticationResult = context.acquireTokenByRefreshToken( - authenticationResult.getRefreshToken(), - this.getClientId(), - null, null).get(); - } catch (Exception e) { - throw new IOException(e.getMessage(), e); - } finally { - executor.shutdown(); - } - } -} diff --git a/src/client/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/package-info.java b/src/client/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/package-info.java deleted file mode 100644 index 2f23671d5be16..0000000000000 --- a/src/client/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * The package provides 2 credential classes that work with AutoRest - * generated Azure clients for authentication purposes through Azure. - */ -package com.microsoft.azure.credentials; \ No newline at end of file diff --git a/src/client/Java/azure-client-authentication/src/test/java/com/microsoft/azure/credentials/UserTokenCredentialsTests.java b/src/client/Java/azure-client-authentication/src/test/java/com/microsoft/azure/credentials/UserTokenCredentialsTests.java deleted file mode 100644 index 7905ba7e7b21e..0000000000000 --- a/src/client/Java/azure-client-authentication/src/test/java/com/microsoft/azure/credentials/UserTokenCredentialsTests.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure.credentials; - -import com.microsoft.aad.adal4j.AuthenticationResult; -import com.microsoft.azure.AzureEnvironment; -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; -import java.util.Date; - -public class UserTokenCredentialsTests { - private static MockUserTokenCredentials credentials = new MockUserTokenCredentials( - "clientId", - "domain", - "username", - "password", - "redirect", - AzureEnvironment.AZURE - ); - - @Test - public void testAcquireToken() throws Exception { - credentials.refreshToken(); - Assert.assertEquals("token1", credentials.getToken()); - Thread.sleep(1500); - Assert.assertEquals("token2", credentials.getToken()); - } - - public static class MockUserTokenCredentials extends UserTokenCredentials { - private AuthenticationResult authenticationResult; - - public MockUserTokenCredentials(String clientId, String domain, String username, String password, String clientRedirectUri, AzureEnvironment environment) { - super(clientId, domain, username, password, clientRedirectUri, environment); - } - - @Override - public String getToken() throws IOException { - if (authenticationResult != null - && authenticationResult.getExpiresOnDate().before(new Date())) { - acquireAccessTokenFromRefreshToken(); - } else { - acquireAccessToken(); - } - return authenticationResult.getAccessToken(); - } - - @Override - public void refreshToken() throws IOException { - acquireAccessToken(); - } - - private void acquireAccessToken() throws IOException { - this.authenticationResult = new AuthenticationResult( - null, - "token1", - "refresh", - 1, - null, - null, - false); - } - - private void acquireAccessTokenFromRefreshToken() throws IOException { - this.authenticationResult = new AuthenticationResult( - null, - "token2", - "refresh", - 1, - null, - null, - false); - } - } -} diff --git a/src/client/Java/azure-client-runtime/build.gradle b/src/client/Java/azure-client-runtime/build.gradle deleted file mode 100644 index db64fd0b46abd..0000000000000 --- a/src/client/Java/azure-client-runtime/build.gradle +++ /dev/null @@ -1,96 +0,0 @@ -buildscript { - repositories { - jcenter() - } - dependencies { - classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.2' - } -} - -apply plugin: 'java' -apply plugin: 'checkstyle' - -version = '1.0.0-SNAPSHOT' - -checkstyle { - toolVersion = "6.18" - configFile = new File("$rootDir/src/client/Java/build-tools/src/main/resources/checkstyle.xml") - configProperties = [samedir: "$rootDir/src/client/Java/build-tools/src/main/resources"] - reportsDir = new File("$rootDir/src/client/Java/build-tools/reports") -} - -dependencies { - compile 'com.microsoft.rest:client-runtime:1.0.0-SNAPSHOT' - testCompile 'junit:junit:4.12' - testCompile 'junit:junit-dep:4.11' - deployerJars "org.apache.maven.wagon:wagon-ftp:2.10" -} - -uploadArchives { - repositories { - mavenDeployer { - configuration = configurations.deployerJars - snapshotRepository(url: "ftp://waws-prod-bay-005.ftp.azurewebsites.windows.net/site/wwwroot/") { - authentication(userName: username, password: password) - } - pom.setArtifactId "azure-client-runtime" - pom.project { - name 'Microsoft Azure AutoRest Runtime for Java' - description 'This is the client runtime for AutoRest generated Azure Java clients.' - url 'https://github.com/Azure/autorest' - - scm { - url 'scm:git:https://github.com/Azure/AutoRest' - connection 'scm:git:git://github.com/Azure/AutoRest.git' - } - - licenses { - license { - name 'The MIT License (MIT)' - url 'http://opensource.org/licenses/MIT' - distribution 'repo' - } - } - - developers { - developer { - id 'microsoft' - name 'Microsoft' - } - } - } - } - } -} - -test { - testLogging { - events "passed", "skipped", "failed", "standardError" - } -} - -javadoc { - options.encoding = 'UTF-8' -} - -task sourcesJar(type: Jar, dependsOn:classes) { - classifier = 'sources' - from sourceSets.main.allSource -} - -task javadocJar(type: Jar, dependsOn: [javadoc]) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -artifacts { - archives sourcesJar - archives javadocJar -} - -test { - reports.getHtml() - reports.html.destination = file("$rootDir/TestResults/JavaAzureRuntime") -} - -tasks.compileJava.dependsOn 'clean' diff --git a/src/client/Java/azure-client-runtime/pom.xml b/src/client/Java/azure-client-runtime/pom.xml deleted file mode 100644 index 98d91b43e802e..0000000000000 --- a/src/client/Java/azure-client-runtime/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - - com.microsoft.azure - autorest-clientruntime-for-java - 1.0.0-SNAPSHOT - ../pom.xml - - - azure-client-runtime - jar - - Azure Java Client Runtime for AutoRest - This package contains the basic runtime for AutoRest generated Azure Java clients. - https://github.com/Azure/autorest-clientruntime-for-java - - - - The MIT License (MIT) - http://opensource.org/licenses/MIT - repo - - - - - scm:git:https://github.com/Azure/autorest-clientruntime-for-java - scm:git:git@github.com:Azure/autorest-clientruntime-for-java.git - HEAD - - - - UTF-8 - - - - - - microsoft - Microsoft - - - - - - com.microsoft.rest - client-runtime - ${parent.version} - - - junit - junit - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.7 - 1.7 - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - - org.codehaus.mojo - build-helper-maven-plugin - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage - /** -
* Copyright (c) Microsoft Corporation. All rights reserved. -
* Licensed under the MIT License. See License.txt in the project root for -
* license information. -
*/]]>
-
-
- -
-
-
diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureAsyncOperation.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureAsyncOperation.java deleted file mode 100644 index 18f56454e9144..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureAsyncOperation.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import java.util.Arrays; -import java.util.List; - -/** - * The response body contains the status of the specified - * asynchronous operation, indicating whether it has succeeded, is in - * progress, or has failed. Note that this status is distinct from the - * HTTP status code returned for the Get Operation Status operation - * itself. If the asynchronous operation succeeded, the response body - * includes the HTTP status code for the successful request. If the - * asynchronous operation failed, the response body includes the HTTP - * status code for the failed request, and also includes error - * information regarding the failure. - */ -public class AzureAsyncOperation { - /** - * Default delay in seconds for long running operations. - */ - static final int DEFAULT_DELAY = 30; - - /** - * Successful status for long running operations. - */ - static final String SUCCESS_STATUS = "Succeeded"; - - /** - * In progress status for long running operations. - */ - static final String IN_PROGRESS_STATUS = "InProgress"; - - /** - * Failed status for long running operations. - */ - static final String FAILED_STATUS = "Failed"; - - /** - * Canceled status for long running operations. - */ - static final String CANCELED_STATUS = "Canceled"; - - /** - * Gets failed terminal statuses for long running operations. - * - * @return a list of statuses indicating a failed operation. - */ - public static List getFailedStatuses() { - return Arrays.asList(FAILED_STATUS, CANCELED_STATUS); - } - - /** - * Gets terminal statuses for long running operations. - * - * @return a list of terminal statuses. - */ - public static List getTerminalStatuses() { - return Arrays.asList(FAILED_STATUS, CANCELED_STATUS, SUCCESS_STATUS); - } - - /** - * The status of the asynchronous request. - */ - private String status; - - /** - * Gets the status of the asynchronous request. - * - * @return the status of the asynchronous request. - */ - public String getStatus() { - return this.status; - } - - /** - * Sets the status of the asynchronous request. - * - * @param status the status of the asynchronous request. - */ - public void setStatus(String status) { - this.status = status; - } - - /** - * If the asynchronous operation failed, the response body includes - * the HTTP status code for the failed request, and also includes - * error information regarding the failure. - */ - private CloudError error; - - /** - * Gets the cloud error. - * - * @return the cloud error. - */ - public CloudError getError() { - return this.error; - } - - /** - * Sets the cloud error. - * - * @param error the cloud error. - */ - public void setError(CloudError error) { - this.error = error; - } - - /** - * The delay in seconds that should be used when checking - * for the status of the operation. - */ - private int retryAfter; - - /** - * Gets the delay in seconds. - * - * @return the delay in seconds. - */ - public int getRetryAfter() { - return this.retryAfter; - } - - /** - * Sets the delay in seconds. - * - * @param retryAfter the delay in seconds. - */ - public void setRetryAfter(int retryAfter) { - this.retryAfter = retryAfter; - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java deleted file mode 100644 index 62a760acb4a0d..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java +++ /dev/null @@ -1,876 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.ServiceCall; -import com.microsoft.rest.ServiceCallback; -import com.microsoft.rest.ServiceException; -import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseCallback; -import com.microsoft.rest.ServiceResponseWithHeaders; -import okhttp3.ResponseBody; -import retrofit2.Call; -import retrofit2.Response; -import retrofit2.http.GET; -import retrofit2.http.Header; -import retrofit2.http.Url; - -import java.io.IOException; -import java.lang.reflect.Type; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -/** - * An instance of this class defines a ServiceClient that handles polling and - * retrying for long running operations when accessing Azure resources. - */ -public class AzureClient extends AzureServiceClient { - /** - * The interval time between two long running operation polls. Default is - * used if null. - */ - private Integer longRunningOperationRetryTimeout; - /** - * The executor for asynchronous requests. - */ - private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - - /** - * The user agent from the service client that owns this Azure Client. - */ - private final String serviceClientUserAgent; - - /** - * Initializes an instance of this class with customized client metadata. - * - * @param serviceClient the caller client that initiates the asynchronous request. - */ - public AzureClient(AzureServiceClient serviceClient) { - super(serviceClient.restClient()); - this.serviceClientUserAgent = serviceClient.userAgent(); - } - - /** - * Handles an initial response from a PUT or PATCH operation response by polling - * the status of the operation until the long running operation terminates. - * - * @param response the initial response from the PUT or PATCH operation. - * @param the return type of the caller - * @param resourceType the type of the resource - * @return the terminal response for the operation. - * @throws CloudException REST exception - * @throws InterruptedException interrupted exception - * @throws IOException thrown by deserialization - */ - public ServiceResponse getPutOrPatchResult(Response response, Type resourceType) throws CloudException, InterruptedException, IOException { - if (response == null) { - throw new CloudException("response is null."); - } - - int statusCode = response.code(); - ResponseBody responseBody; - if (response.isSuccessful()) { - responseBody = response.body(); - } else { - responseBody = response.errorBody(); - } - if (statusCode != 200 && statusCode != 201 && statusCode != 202) { - CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); - exception.setResponse(response); - if (responseBody != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(responseBody.string(), CloudError.class)); - responseBody.close(); - } - throw exception; - } - - PollingState pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(), resourceType, restClient().mapperAdapter()); - String url = response.raw().request().url().toString(); - - // Check provisioning state - while (!AzureAsyncOperation.getTerminalStatuses().contains(pollingState.getStatus())) { - Thread.sleep(pollingState.getDelayInMilliseconds()); - - if (pollingState.getAzureAsyncOperationHeaderLink() != null - && !pollingState.getAzureAsyncOperationHeaderLink().isEmpty()) { - updateStateFromAzureAsyncOperationHeader(pollingState); - } else if (pollingState.getLocationHeaderLink() != null - && !pollingState.getLocationHeaderLink().isEmpty()) { - updateStateFromLocationHeaderOnPut(pollingState); - } else { - updateStateFromGetResourceOperation(pollingState, url); - } - } - - if (AzureAsyncOperation.SUCCESS_STATUS.equals(pollingState.getStatus()) && pollingState.getResource() == null) { - updateStateFromGetResourceOperation(pollingState, url); - } - - if (AzureAsyncOperation.getFailedStatuses().contains(pollingState.getStatus())) { - throw new CloudException("Async operation failed"); - } - - return new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse()); - } - - /** - * Handles an initial response from a PUT or PATCH operation response by polling - * the status of the operation until the long running operation terminates. - * - * @param response the initial response from the PUT or PATCH operation. - * @param resourceType the type of the resource - * @param headerType the type of the response header - * @param the return type of the caller - * @param the type of the response header - * @return the terminal response for the operation. - * @throws CloudException REST exception - * @throws InterruptedException interrupted exception - * @throws IOException thrown by deserialization - */ - public ServiceResponseWithHeaders getPutOrPatchResultWithHeaders(Response response, Type resourceType, Class headerType) throws CloudException, InterruptedException, IOException { - ServiceResponse bodyResponse = getPutOrPatchResult(response, resourceType); - return new ServiceResponseWithHeaders<>( - bodyResponse.getBody(), - restClient().mapperAdapter().deserialize(restClient().mapperAdapter().serialize(bodyResponse.getResponse().headers()), headerType), - bodyResponse.getResponse() - ); - } - - /** - * Handles an initial response from a PUT or PATCH operation response by polling - * the status of the operation asynchronously, calling the user provided callback - * when the operation terminates. - * - * @param response the initial response from the PUT or PATCH operation. - * @param the return type of the caller. - * @param resourceType the type of the resource. - * @param serviceCall the ServiceCall object tracking Retrofit calls. - * @param callback the user callback to call when operation terminates. - * @return the task describing the asynchronous polling. - */ - public AsyncPollingTask getPutOrPatchResultAsync(Response response, Type resourceType, ServiceCall serviceCall, ServiceCallback callback) { - if (response == null) { - callback.failure(new ServiceException("response is null.")); - return null; - } - - int statusCode = response.code(); - ResponseBody responseBody; - if (response.isSuccessful()) { - responseBody = response.body(); - } else { - responseBody = response.errorBody(); - } - if (statusCode != 200 && statusCode != 201 && statusCode != 202) { - CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); - exception.setResponse(response); - try { - if (responseBody != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(responseBody.string(), CloudError.class)); - responseBody.close(); - } - } catch (Exception e) { /* ignore serialization errors on top of service errors */ } - callback.failure(exception); - return null; - } - - PollingState pollingState; - try { - pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(), resourceType, restClient().mapperAdapter()); - } catch (IOException e) { - callback.failure(e); - return null; - } - String url = response.raw().request().url().toString(); - - // Task runner will take it from here - PutPatchPollingTask task = new PutPatchPollingTask<>(pollingState, url, serviceCall, callback); - executor.schedule(task, pollingState.getDelayInMilliseconds(), TimeUnit.MILLISECONDS); - return task; - } - - /** - * Handles an initial response from a PUT or PATCH operation response by polling - * the status of the operation asynchronously, calling the user provided callback - * when the operation terminates. - * - * @param response the initial response from the PUT or PATCH operation. - * @param the return type of the caller - * @param the type of the response header - * @param resourceType the type of the resource. - * @param headerType the type of the response header - * @param serviceCall the ServiceCall object tracking Retrofit calls. - * @param callback the user callback to call when operation terminates. - * @return the task describing the asynchronous polling. - */ - public AsyncPollingTask getPutOrPatchResultWithHeadersAsync(Response response, Type resourceType, final Class headerType, final ServiceCall serviceCall, final ServiceCallback callback) { - return this.getPutOrPatchResultAsync(response, resourceType, serviceCall, new ServiceCallback() { - @Override - public void failure(Throwable t) { - callback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - try { - callback.success(new ServiceResponseWithHeaders<>( - result.getBody(), - restClient().mapperAdapter().deserialize(restClient().mapperAdapter().serialize(result.getResponse().headers()), headerType), - result.getResponse() - )); - } catch (IOException e) { - failure(e); - } - } - }); - } - - /** - * Handles an initial response from a POST or DELETE operation response by polling - * the status of the operation until the long running operation terminates. - * - * @param response the initial response from the POST or DELETE operation. - * @param the return type of the caller - * @param resourceType the type of the resource - * @return the terminal response for the operation. - * @throws CloudException REST exception - * @throws InterruptedException interrupted exception - * @throws IOException thrown by deserialization - */ - public ServiceResponse getPostOrDeleteResult(Response response, Type resourceType) throws CloudException, InterruptedException, IOException { - if (response == null) { - throw new CloudException("response is null."); - } - - int statusCode = response.code(); - ResponseBody responseBody; - if (response.isSuccessful()) { - responseBody = response.body(); - } else { - responseBody = response.errorBody(); - } - if (statusCode != 200 && statusCode != 202 && statusCode != 204) { - CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); - exception.setResponse(response); - if (responseBody != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(responseBody.string(), CloudError.class)); - responseBody.close(); - } - throw exception; - } - - PollingState pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(), resourceType, restClient().mapperAdapter()); - - // Check provisioning state - while (!AzureAsyncOperation.getTerminalStatuses().contains(pollingState.getStatus())) { - Thread.sleep(pollingState.getDelayInMilliseconds()); - - if (pollingState.getAzureAsyncOperationHeaderLink() != null - && !pollingState.getAzureAsyncOperationHeaderLink().isEmpty()) { - updateStateFromAzureAsyncOperationHeader(pollingState); - } else if (pollingState.getLocationHeaderLink() != null - && !pollingState.getLocationHeaderLink().isEmpty()) { - updateStateFromLocationHeaderOnPostOrDelete(pollingState); - } else { - CloudException exception = new CloudException("No header in response"); - exception.setResponse(response); - throw exception; - } - } - - // Check if operation failed - if (AzureAsyncOperation.getFailedStatuses().contains(pollingState.getStatus())) { - throw new CloudException("Async operation failed"); - } - - return new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse()); - } - - /** - * Handles an initial response from a POST or DELETE operation response by polling - * the status of the operation until the long running operation terminates. - * - * @param response the initial response from the POST or DELETE operation. - * @param resourceType the type of the resource - * @param headerType the type of the response header - * @param the return type of the caller - * @param the type of the response header - * @return the terminal response for the operation. - * @throws CloudException REST exception - * @throws InterruptedException interrupted exception - * @throws IOException thrown by deserialization - */ - public ServiceResponseWithHeaders getPostOrDeleteResultWithHeaders(Response response, Type resourceType, Class headerType) throws CloudException, InterruptedException, IOException { - ServiceResponse bodyResponse = getPostOrDeleteResult(response, resourceType); - return new ServiceResponseWithHeaders<>( - bodyResponse.getBody(), - restClient().mapperAdapter().deserialize(restClient().mapperAdapter().serialize(bodyResponse.getResponse().headers()), headerType), - bodyResponse.getResponse() - ); - } - - /** - * Handles an initial response from a POST or DELETE operation response by polling - * the status of the operation asynchronously, calling the user provided callback - * when the operation terminates. - * - * @param response the initial response from the POST or DELETE operation. - * @param the return type of the caller. - * @param resourceType the type of the resource. - * @param serviceCall the ServiceCall object tracking Retrofit calls. - * @param callback the user callback to call when operation terminates. - * @return the task describing the asynchronous polling. - */ - public AsyncPollingTask getPostOrDeleteResultAsync(Response response, Type resourceType, ServiceCall serviceCall, ServiceCallback callback) { - if (response == null) { - callback.failure(new ServiceException("response is null.")); - return null; - } - - int statusCode = response.code(); - ResponseBody responseBody; - if (response.isSuccessful()) { - responseBody = response.body(); - } else { - responseBody = response.errorBody(); - } - if (statusCode != 200 && statusCode != 202 && statusCode != 204) { - CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); - exception.setResponse(response); - try { - if (responseBody != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(responseBody.string(), CloudError.class)); - responseBody.close(); - } - } catch (Exception e) { /* ignore serialization errors on top of service errors */ } - callback.failure(exception); - return null; - } - - PollingState pollingState; - try { - pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(), resourceType, restClient().mapperAdapter()); - } catch (IOException e) { - callback.failure(e); - return null; - } - - // Task runner will take it from here - PostDeletePollingTask task = new PostDeletePollingTask<>(pollingState, serviceCall, callback); - executor.schedule(task, pollingState.getDelayInMilliseconds(), TimeUnit.MILLISECONDS); - return task; - } - - /** - * Handles an initial response from a POST or DELETE operation response by polling - * the status of the operation asynchronously, calling the user provided callback - * when the operation terminates. - * - * @param response the initial response from the POST or DELETE operation. - * @param the return type of the caller - * @param the type of the response header - * @param resourceType the type of the resource. - * @param headerType the type of the response header - * @param serviceCall the ServiceCall object tracking Retrofit calls. - * @param callback the user callback to call when operation terminates. - * @return the task describing the asynchronous polling. - */ - public AsyncPollingTask getPostOrDeleteResultWithHeadersAsync(Response response, Type resourceType, final Class headerType, final ServiceCall serviceCall, final ServiceCallback callback) { - return this.getPostOrDeleteResultAsync(response, resourceType, serviceCall, new ServiceCallback() { - @Override - public void failure(Throwable t) { - callback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - try { - callback.success(new ServiceResponseWithHeaders<>( - result.getBody(), - restClient().mapperAdapter().deserialize(restClient().mapperAdapter().serialize(result.getResponse().headers()), headerType), - result.getResponse() - )); - } catch (IOException e) { - failure(e); - } - } - }); - } - - /** - * Polls from the location header and updates the polling state with the - * polling response for a PUT operation. - * - * @param pollingState the polling state for the current operation. - * @param the return type of the caller. - * @throws CloudException REST exception - * @throws IOException thrown by deserialization - */ - private void updateStateFromLocationHeaderOnPut(PollingState pollingState) throws CloudException, IOException { - Response response = poll(pollingState.getLocationHeaderLink()); - int statusCode = response.code(); - if (statusCode == 202) { - pollingState.setResponse(response); - pollingState.setStatus(AzureAsyncOperation.IN_PROGRESS_STATUS); - } else if (statusCode == 200 || statusCode == 201) { - pollingState.updateFromResponseOnPutPatch(response); - } - } - - /** - * Polls from the location header and updates the polling state with the - * polling response for a PUT operation. - * - * @param pollingState the polling state for the current operation. - * @param callback the user callback to call when operation terminates. - * @param the return type of the caller. - * @return the task describing the asynchronous polling. - */ - private Call updateStateFromLocationHeaderOnPutAsync(final PollingState pollingState, final ServiceCallback callback) { - return pollAsync(pollingState.getLocationHeaderLink(), new ServiceCallback() { - @Override - public void failure(Throwable t) { - callback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - try { - int statusCode = result.getResponse().code(); - if (statusCode == 202) { - pollingState.setResponse(result.getResponse()); - pollingState.setStatus(AzureAsyncOperation.IN_PROGRESS_STATUS); - } else if (statusCode == 200 || statusCode == 201) { - pollingState.updateFromResponseOnPutPatch(result.getResponse()); - } - callback.success(new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse())); - } catch (Throwable t) { - failure(t); - } - } - }); - } - - /** - * Polls from the location header and updates the polling state with the - * polling response for a POST or DELETE operation. - * - * @param pollingState the polling state for the current operation. - * @param the return type of the caller. - * @throws CloudException service exception - * @throws IOException thrown by deserialization - */ - private void updateStateFromLocationHeaderOnPostOrDelete(PollingState pollingState) throws CloudException, IOException { - Response response = poll(pollingState.getLocationHeaderLink()); - int statusCode = response.code(); - if (statusCode == 202) { - pollingState.setResponse(response); - pollingState.setStatus(AzureAsyncOperation.IN_PROGRESS_STATUS); - } else if (statusCode == 200 || statusCode == 201 || statusCode == 204) { - pollingState.updateFromResponseOnDeletePost(response); - } - } - - /** - * Polls from the location header and updates the polling state with the - * polling response for a POST or DELETE operation. - * - * @param pollingState the polling state for the current operation. - * @param callback the user callback to call when operation terminates. - * @param the return type of the caller. - * @return the task describing the asynchronous polling. - */ - private Call updateStateFromLocationHeaderOnPostOrDeleteAsync(final PollingState pollingState, final ServiceCallback callback) { - return pollAsync(pollingState.getLocationHeaderLink(), new ServiceCallback() { - @Override - public void failure(Throwable t) { - callback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - try { - int statusCode = result.getResponse().code(); - if (statusCode == 202) { - pollingState.setResponse(result.getResponse()); - pollingState.setStatus(AzureAsyncOperation.IN_PROGRESS_STATUS); - } else if (statusCode == 200 || statusCode == 201 || statusCode == 204) { - pollingState.updateFromResponseOnDeletePost(result.getResponse()); - } - callback.success(new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse())); - } catch (Throwable t) { - failure(t); - } - } - }); - } - - /** - * Polls from the provided URL and updates the polling state with the - * polling response. - * - * @param pollingState the polling state for the current operation. - * @param url the url to poll from - * @param the return type of the caller. - * @throws CloudException service exception - * @throws IOException thrown by deserialization - */ - private void updateStateFromGetResourceOperation(PollingState pollingState, String url) throws CloudException, IOException { - Response response = poll(url); - pollingState.updateFromResponseOnPutPatch(response); - } - - /** - * Polls from the provided URL and updates the polling state with the - * polling response. - * - * @param pollingState the polling state for the current operation. - * @param url the url to poll from - * @param callback the user callback to call when operation terminates. - * @param the return type of the caller. - * @return the task describing the asynchronous polling. - */ - private Call updateStateFromGetResourceOperationAsync(final PollingState pollingState, String url, final ServiceCallback callback) { - return pollAsync(url, new ServiceCallback() { - @Override - public void failure(Throwable t) { - callback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - try { - pollingState.updateFromResponseOnPutPatch(result.getResponse()); - callback.success(new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse())); - } catch (Throwable t) { - failure(t); - } - } - }); - } - - /** - * Polls from the 'Azure-AsyncOperation' header and updates the polling - * state with the polling response. - * - * @param pollingState the polling state for the current operation. - * @param the return type of the caller. - * @throws CloudException service exception - * @throws IOException thrown by deserialization - */ - private void updateStateFromAzureAsyncOperationHeader(PollingState pollingState) throws CloudException, IOException { - Response response = poll(pollingState.getAzureAsyncOperationHeaderLink()); - - AzureAsyncOperation body = null; - if (response.body() != null) { - body = restClient().mapperAdapter().deserialize(response.body().string(), AzureAsyncOperation.class); - response.body().close(); - } - - if (body == null || body.getStatus() == null) { - CloudException exception = new CloudException("no body"); - exception.setResponse(response); - if (response.errorBody() != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(response.errorBody().string(), CloudError.class)); - response.errorBody().close(); - } - throw exception; - } - - pollingState.setStatus(body.getStatus()); - pollingState.setResponse(response); - pollingState.setResource(null); - } - - /** - * Polls from the 'Azure-AsyncOperation' header and updates the polling - * state with the polling response. - * - * @param pollingState the polling state for the current operation. - * @param callback the user callback to call when operation terminates. - * @param the return type of the caller. - * @return the task describing the asynchronous polling. - */ - private Call updateStateFromAzureAsyncOperationHeaderAsync(final PollingState pollingState, final ServiceCallback callback) { - return pollAsync(pollingState.getAzureAsyncOperationHeaderLink(), new ServiceCallback() { - @Override - public void failure(Throwable t) { - callback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - try { - AzureAsyncOperation body = null; - if (result.getBody() != null) { - body = restClient().mapperAdapter().deserialize(result.getBody().string(), AzureAsyncOperation.class); - result.getBody().close(); - } - if (body == null || body.getStatus() == null) { - CloudException exception = new CloudException("no body"); - exception.setResponse(result.getResponse()); - if (result.getResponse().errorBody() != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(result.getResponse().errorBody().string(), CloudError.class)); - result.getResponse().errorBody().close(); - } - failure(exception); - } else { - pollingState.setStatus(body.getStatus()); - pollingState.setResponse(result.getResponse()); - pollingState.setResource(null); - callback.success(new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse())); - } - } catch (IOException ex) { - failure(ex); - } - } - }); - } - - /** - * Polls from the URL provided. - * - * @param url the URL to poll from. - * @return the raw response. - * @throws CloudException REST exception - * @throws IOException thrown by deserialization - */ - private Response poll(String url) throws CloudException, IOException { - URL endpoint; - endpoint = new URL(url); - int port = endpoint.getPort(); - if (port == -1) { - port = endpoint.getDefaultPort(); - } - AsyncService service = restClient().retrofit().create(AsyncService.class); - Response response = service.get(endpoint.getFile(), serviceClientUserAgent).execute(); - int statusCode = response.code(); - if (statusCode != 200 && statusCode != 201 && statusCode != 202 && statusCode != 204) { - CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); - exception.setResponse(response); - if (response.body() != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(response.body().string(), CloudError.class)); - response.body().close(); - } else if (response.errorBody() != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(response.errorBody().string(), CloudError.class)); - response.errorBody().close(); - } - throw exception; - } - return response; - } - - /** - * Polls asynchronously from the URL provided. - * - * @param url the URL to poll from. - * @param callback the user callback to call when operation terminates. - * @return the {@link Call} object from Retrofit. - */ - private Call pollAsync(String url, final ServiceCallback callback) { - URL endpoint; - try { - endpoint = new URL(url); - } catch (MalformedURLException e) { - callback.failure(e); - return null; - } - int port = endpoint.getPort(); - if (port == -1) { - port = endpoint.getDefaultPort(); - } - AsyncService service = restClient().retrofit().create(AsyncService.class); - Call call = service.get(endpoint.getFile(), serviceClientUserAgent); - call.enqueue(new ServiceResponseCallback(callback) { - @Override - public void onResponse(Call call, Response response) { - try { - int statusCode = response.code(); - if (statusCode != 200 && statusCode != 201 && statusCode != 202 && statusCode != 204) { - CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); - exception.setResponse(response); - if (response.body() != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(response.body().string(), CloudError.class)); - response.body().close(); - } else if (response.errorBody() != null) { - exception.setBody((CloudError) restClient().mapperAdapter().deserialize(response.errorBody().string(), CloudError.class)); - response.errorBody().close(); - } - callback.failure(exception); - return; - } - callback.success(new ServiceResponse<>(response.body(), response)); - } catch (IOException ex) { - callback.failure(ex); - } - } - }); - return call; - } - - /** - * Gets the interval time between two long running operation polls. - * - * @return the time in milliseconds. - */ - public Integer getLongRunningOperationRetryTimeout() { - return longRunningOperationRetryTimeout; - } - - /** - * Sets the interval time between two long running operation polls. - * - * @param longRunningOperationRetryTimeout the time in milliseconds. - */ - public void withLongRunningOperationRetryTimeout(Integer longRunningOperationRetryTimeout) { - this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; - } - - /** - * The Retrofit service used for polling. - */ - private interface AsyncService { - @GET - Call get(@Url String url, @Header("User-Agent") String userAgent); - } - - /** - * The task runner that describes the state of an asynchronous long running - * operation. - * - * @param the return type of the caller. - */ - abstract class AsyncPollingTask implements Runnable { - /** The {@link Call} object from Retrofit. */ - protected ServiceCall serviceCall; - /** The polling state for the current operation. */ - protected PollingState pollingState; - /** The callback used for asynchronous polling. */ - protected ServiceCallback pollingCallback; - /** The client callback to call when polling finishes. */ - protected ServiceCallback clientCallback; - } - - /** - * The task runner that handles PUT or PATCH operations. - * - * @param the return type of the caller. - */ - class PutPatchPollingTask extends AsyncPollingTask { - /** The URL to poll from. */ - private String url; - - /** - * Creates an instance of Polling task for PUT or PATCH operations. - * - * @param pollingState the current polling state. - * @param url the URL to poll from. - * @param serviceCall the ServiceCall object tracking Retrofit calls. - * @param clientCallback the client callback to call when a terminal status is hit. - */ - PutPatchPollingTask(final PollingState pollingState, final String url, final ServiceCall serviceCall, final ServiceCallback clientCallback) { - this.serviceCall = serviceCall; - this.pollingState = pollingState; - this.url = url; - this.clientCallback = clientCallback; - this.pollingCallback = new ServiceCallback() { - @Override - public void failure(Throwable t) { - clientCallback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - PutPatchPollingTask task = new PutPatchPollingTask<>(pollingState, url, serviceCall, clientCallback); - executor.schedule(task, pollingState.getDelayInMilliseconds(), TimeUnit.MILLISECONDS); - } - }; - } - - @Override - public void run() { - // Check provisioning state - if (!AzureAsyncOperation.getTerminalStatuses().contains(pollingState.getStatus())) { - if (pollingState.getAzureAsyncOperationHeaderLink() != null - && !pollingState.getAzureAsyncOperationHeaderLink().isEmpty()) { - this.serviceCall.newCall(updateStateFromAzureAsyncOperationHeaderAsync(pollingState, pollingCallback)); - } else if (pollingState.getLocationHeaderLink() != null - && !pollingState.getLocationHeaderLink().isEmpty()) { - this.serviceCall.newCall(updateStateFromLocationHeaderOnPutAsync(pollingState, pollingCallback)); - } else { - this.serviceCall.newCall(updateStateFromGetResourceOperationAsync(pollingState, url, pollingCallback)); - } - } else { - if (AzureAsyncOperation.SUCCESS_STATUS.equals(pollingState.getStatus()) && pollingState.getResource() == null) { - this.serviceCall.newCall(updateStateFromGetResourceOperationAsync(pollingState, url, clientCallback)); - } else if (AzureAsyncOperation.getFailedStatuses().contains(pollingState.getStatus())) { - clientCallback.failure(new ServiceException("Async operation failed")); - } else { - clientCallback.success(new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse())); - } - } - } - } - - /** - * The task runner that handles POST or DELETE operations. - * - * @param the return type of the caller. - */ - class PostDeletePollingTask extends AsyncPollingTask { - /** - * Creates an instance of Polling task for POST or DELETE operations. - * - * @param pollingState the current polling state. - * @param serviceCall the ServiceCall object tracking Retrofit calls. - * @param clientCallback the client callback to call when a terminal status is hit. - */ - PostDeletePollingTask(final PollingState pollingState, final ServiceCall serviceCall, final ServiceCallback clientCallback) { - this.serviceCall = serviceCall; - this.pollingState = pollingState; - this.clientCallback = clientCallback; - this.pollingCallback = new ServiceCallback() { - @Override - public void failure(Throwable t) { - clientCallback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - PostDeletePollingTask task = new PostDeletePollingTask<>(pollingState, serviceCall, clientCallback); - executor.schedule(task, pollingState.getDelayInMilliseconds(), TimeUnit.MILLISECONDS); - } - }; - } - - @Override - public void run() { - if (!AzureAsyncOperation.getTerminalStatuses().contains(pollingState.getStatus())) { - if (pollingState.getAzureAsyncOperationHeaderLink() != null - && !pollingState.getAzureAsyncOperationHeaderLink().isEmpty()) { - updateStateFromAzureAsyncOperationHeaderAsync(pollingState, pollingCallback); - } else if (pollingState.getLocationHeaderLink() != null - && !pollingState.getLocationHeaderLink().isEmpty()) { - updateStateFromLocationHeaderOnPostOrDeleteAsync(pollingState, pollingCallback); - } else { - pollingCallback.failure(new ServiceException("No header in response")); - } - } else { - // Check if operation failed - if (AzureAsyncOperation.getFailedStatuses().contains(pollingState.getStatus())) { - clientCallback.failure(new ServiceException("Async operation failed")); - } else { - clientCallback.success(new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse())); - } - } - } - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureEnvironment.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureEnvironment.java deleted file mode 100644 index 04a6af99d93db..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureEnvironment.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -/** - * An instance of this class describes an environment in Azure. - */ -public final class AzureEnvironment { - /** - * Base URL for calls to Azure management API. - */ - private final String baseURL; - - /** - * ActiveDirectory Endpoint for the Azure Environment. - */ - private String authenticationEndpoint; - - /** - * Token audience for an endpoint. - */ - private String tokenAudience; - - /** - * Determines whether the authentication endpoint should - * be validated with Azure AD. Default value is true. - */ - private boolean validateAuthority; - - /** - * Initializes an instance of AzureEnvironment class. - * - * @param authenticationEndpoint ActiveDirectory Endpoint for the Azure Environment. - * @param tokenAudience token audience for an endpoint. - * @param validateAuthority whether the authentication endpoint should - * be validated with Azure AD. - * @param baseUrl the base URL for the current environment. - */ - public AzureEnvironment( - String authenticationEndpoint, - String tokenAudience, - boolean validateAuthority, - String baseUrl) { - this.authenticationEndpoint = authenticationEndpoint; - this.tokenAudience = tokenAudience; - this.validateAuthority = validateAuthority; - this.baseURL = baseUrl; - } - - /** - * Provides the settings for authentication with Azure. - */ - public static final AzureEnvironment AZURE = new AzureEnvironment( - "https://login.windows.net/", - "https://management.core.windows.net/", - true, - "https://management.azure.com/"); - - /** - * Provides the settings for authentication with Azure China. - */ - public static final AzureEnvironment AZURE_CHINA = new AzureEnvironment( - "https://login.chinacloudapi.cn/", - "https://management.core.chinacloudapi.cn/", - true, - "https://management.chinacloudapi.cn/"); - - /** - * Provides the settings for authentication with Azure US Government. - */ - public static final AzureEnvironment AZURE_US_GOVERNMENT = new AzureEnvironment( - "https://login.microsoftonline.com/", - "https://management.core.usgovcloudapi.net/", - true, - "https://management.usgovcloudapi.net/"); - - /** - * Provides the settings for authentication with Azure Germany. - */ - public static final AzureEnvironment AZURE_GERMANY = new AzureEnvironment( - "https://login.microsoftonline.de/", - "https://management.core.cloudapi.de/", - true, - "https://management.microsoftazure.de/"); - - /** - * Gets the base URL of the management service. - * - * @return the Base URL for the management service. - */ - public String getBaseUrl() { - return this.baseURL; - } - - /** - * Gets a builder for {@link RestClient}. - * - * @return a builder for the rest client. - */ - public RestClient.Builder.Buildable newRestClientBuilder() { - return new RestClient.Builder() - .withDefaultBaseUrl(this) - .withInterceptor(new RequestIdHeaderInterceptor()); - } - - /** - * Gets the ActiveDirectory Endpoint for the Azure Environment. - * - * @return the ActiveDirectory Endpoint for the Azure Environment. - */ - public String getAuthenticationEndpoint() { - return authenticationEndpoint; - } - - /** - * Gets the token audience for an endpoint. - * - * @return the token audience for an endpoint. - */ - public String getTokenAudience() { - return tokenAudience; - } - - /** - * Gets whether the authentication endpoint should - * be validated with Azure AD. - * - * @return true if the authentication endpoint should be validated with - * Azure AD, false otherwise. - */ - public boolean isValidateAuthority() { - return validateAuthority; - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureResponse.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureResponse.java deleted file mode 100644 index f1b274c66302f..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureResponse.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.ServiceResponse; -import retrofit2.Response; - -/** - * A standard service response including request ID. - * - * @param the type of the response resource - */ -public class AzureResponse extends ServiceResponse { - /** - * Instantiate a ServiceResponse instance with a response object and a raw REST response. - * - * @param body deserialized response object - * @param response raw REST response - */ - public AzureResponse(T body, Response response) { - super(body, response); - } - - /** - * The value that uniquely identifies a request made against the service. - */ - private String requestId; - - /** - * Gets the value that uniquely identifies a request made against the service. - * - * @return the request id value. - */ - public String getRequestId() { - return requestId; - } - - /** - * Sets the value that uniquely identifies a request made against the service. - * - * @param requestId the request id value. - */ - public void setRequestId(String requestId) { - this.requestId = requestId; - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureServiceClient.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureServiceClient.java deleted file mode 100644 index 09c8c28fbd536..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureServiceClient.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.serializer.JacksonMapperAdapter; - -import okhttp3.OkHttpClient; -import retrofit2.Retrofit; - -/** - * ServiceClient is the abstraction for accessing REST operations and their payload data types. - */ -public abstract class AzureServiceClient { - /** - * The RestClient instance storing all information needed for making REST calls. - */ - private RestClient restClient; - - protected AzureServiceClient(String baseUrl) { - this(new RestClient.Builder().withBaseUrl(baseUrl) - .withInterceptor(new RequestIdHeaderInterceptor()).build()); - } - - /** - * Initializes a new instance of the ServiceClient class. - * - * @param restClient the REST client - */ - protected AzureServiceClient(RestClient restClient) { - this.restClient = restClient; - } - - /** - * The default User-Agent header. Override this method to override the user agent. - * - * @return the user agent string. - */ - public String userAgent() { - return "Azure-SDK-For-Java/" + getClass().getPackage().getImplementationVersion(); - } - - /** - * @return the {@link RestClient} instance. - */ - public RestClient restClient() { - return restClient; - } - - /** - * @return the Retrofit instance. - */ - public Retrofit retrofit() { - return restClient().retrofit(); - } - - /** - * @return the HTTP client. - */ - public OkHttpClient httpClient() { - return restClient().httpClient(); - } - - /** - * @return the adapter to a Jackson {@link com.fasterxml.jackson.databind.ObjectMapper}. - */ - public JacksonMapperAdapter mapperAdapter() { - return restClient().mapperAdapter(); - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureServiceResponseBuilder.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureServiceResponseBuilder.java deleted file mode 100644 index 7ad369ecc5686..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureServiceResponseBuilder.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.google.common.reflect.TypeToken; -import com.microsoft.rest.RestException; -import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseBuilder; -import com.microsoft.rest.serializer.JacksonMapperAdapter; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import retrofit2.Response; - -/** - * The builder for building a {@link ServiceResponse}. - * - * @param the return type from caller. - * @param the exception to throw in case of error. - */ -public class AzureServiceResponseBuilder extends ServiceResponseBuilder { - /** - * Create a ServiceResponseBuilder instance. - * - * @param deserializer the serialization utils to use for deserialization operations - */ - public AzureServiceResponseBuilder(JacksonMapperAdapter deserializer) { - this(deserializer, new HashMap()); - } - - /** - * Create a ServiceResponseBuilder instance. - * - * @param deserializer the serialization utils to use for deserialization operations - * @param responseTypes a mapping of response status codes and response destination types. - */ - public AzureServiceResponseBuilder(JacksonMapperAdapter deserializer, Map responseTypes) { - super(deserializer, responseTypes); - } - - @SuppressWarnings("unchecked") - @Override - public ServiceResponse buildEmpty(Response response) throws E, IOException { - int statusCode = response.code(); - if (responseTypes.containsKey(statusCode)) { - if (new TypeToken(getClass()) { }.getRawType().isAssignableFrom(Boolean.class)) { - ServiceResponse serviceResponse = new ServiceResponse<>(response); - serviceResponse.setBody((T) (Object) (statusCode / 100 == 2)); - return serviceResponse; - } else { - return new ServiceResponse<>(response); - } - } else { - try { - E exception = (E) exceptionType.getConstructor(String.class).newInstance("Invalid status code " + statusCode); - exceptionType.getMethod("setResponse", response.getClass()).invoke(exception, response); - throw exception; - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new IOException("Invalid status code " + statusCode + ", but an instance of " + exceptionType.getCanonicalName() - + " cannot be created.", e); - } - } - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/CloudError.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/CloudError.java deleted file mode 100644 index 72f3bcc2e6bb1..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/CloudError.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import java.util.ArrayList; -import java.util.List; - -/** - * An instance of this class provides additional information about an http error response. - */ -public class CloudError { - /** - * The error code parsed from the body of the http error response. - */ - private String code; - - /** - * The error message parsed from the body of the http error response. - */ - private String message; - - /** - * The target of the error. - */ - private String target; - - /** - * Details for the error. - */ - private List details; - - /** - * Initializes a new instance of CloudError. - */ - public CloudError() { - this.details = new ArrayList(); - } - - /** - * Gets the error code parsed from the body of the http error response. - * - * @return the error code. - */ - public String getCode() { - return code; - } - - /** - * Sets the error code parsed from the body of the http error response. - * - * @param code the error code. - */ - public void setCode(String code) { - this.code = code; - } - - /** - * Gets the error message parsed from the body of the http error response. - * - * @return the error message. - */ - public String getMessage() { - return message; - } - - /** - * Sets the error message parsed from the body of the http error response. - * - * @param message the error message. - */ - public void setMessage(String message) { - this.message = message; - } - - /** - * Gets the target of the error. - * - * @return the target of the error. - */ - public String getTarget() { - return target; - } - - /** - * Sets the target of the error. - * - * @param target the target of the error. - */ - public void setTarget(String target) { - this.target = target; - } - - /** - * Gets the eetails for the error. - * - * @return the details for the error. - */ - public List getDetails() { - return details; - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/CloudException.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/CloudException.java deleted file mode 100644 index 2e0a9db747838..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/CloudException.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.RestException; -import retrofit2.Response; - -/** - * Exception thrown for an invalid response with custom error information. - */ -public class CloudException extends RestException { - /** - * Information about the associated HTTP response. - */ - private Response response; - - /** - * The HTTP response body. - */ - private CloudError body; - - /** - * Initializes a new instance of the ServiceException class. - */ - public CloudException() { } - - /** - * Initializes a new instance of the ServiceException class. - * - * @param message The exception message. - */ - public CloudException(final String message) { - super(message); - } - - /** - * Initializes a new instance of the ServiceException class. - * - * @param message the exception message - * @param cause exception that caused this exception to occur - */ - public CloudException(final String message, final Throwable cause) { - super(message, cause); - } - - /** - * Initializes a new instance of the ServiceException class. - * - * @param cause exception that caused this exception to occur - */ - public CloudException(final Throwable cause) { - super(cause); - } - - /** - * Gets information about the associated HTTP response. - * - * @return the HTTP response - */ - public Response getResponse() { - return response; - } - - /** - * Gets the HTTP response body. - * - * @return the response body - */ - public CloudError getBody() { - return body; - } - - /** - * Sets the HTTP response. - * - * @param response the HTTP response - */ - public void setResponse(Response response) { - this.response = response; - } - - /** - * Sets the HTTP response body. - * - * @param body the response object - */ - public void setBody(CloudError body) { - this.body = body; - } - - @Override - public String toString() { - String message = super.toString(); - if (body != null && body.getMessage() != null) { - message = message + ": " + body.getMessage(); - } - return message; - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/CustomHeaderInterceptor.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/CustomHeaderInterceptor.java deleted file mode 100644 index 7486b838fb633..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/CustomHeaderInterceptor.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import okhttp3.Headers; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * An instance of this class enables adding custom headers in client requests - * when added to the {@link okhttp3.OkHttpClient} interceptors. - */ -public class CustomHeaderInterceptor implements Interceptor { - /** - * A mapping of custom headers. - */ - private Map> headers; - - /** - * Initialize an instance of {@link CustomHeaderInterceptor} class. - */ - public CustomHeaderInterceptor() { - headers = new HashMap>(); - } - - /** - * Initialize an instance of {@link CustomHeaderInterceptor} class. - * - * @param key the key for the header - * @param value the value of the header - */ - public CustomHeaderInterceptor(String key, String value) { - this(); - addHeader(key, value); - } - - /** - * Add a single header key-value pair. If one with the name already exists, - * it gets replaced. - * - * @param name the name of the header. - * @param value the value of the header. - * @return the interceptor instance itself. - */ - public CustomHeaderInterceptor replaceHeader(String name, String value) { - this.headers.put(name, Collections.singletonList(value)); - return this; - } - - /** - * Add a single header key-value pair. If one with the name already exists, - * both stay in the header map. - * - * @param name the name of the header. - * @param value the value of the header. - * @return the interceptor instance itself. - */ - public CustomHeaderInterceptor addHeader(String name, String value) { - if (this.headers.containsKey(name)) { - this.headers.get(name).add(value); - } else { - this.headers.put(name, Collections.singletonList(value)); - } - return this; - } - - /** - * Add all headers in a {@link Headers} object. - * - * @param headers an OkHttp {@link Headers} object. - * @return the interceptor instance itself. - */ - public CustomHeaderInterceptor addHeaders(Headers headers) { - this.headers.putAll(headers.toMultimap()); - return this; - } - - /** - * Add all headers in a header map. - * - * @param headers a map of headers. - * @return the interceptor instance itself. - */ - public CustomHeaderInterceptor addHeaderMap(Map headers) { - for (Map.Entry header : headers.entrySet()) { - this.headers.put(header.getKey(), Collections.singletonList(header.getValue())); - } - return this; - } - - /** - * Add all headers in a header multimap. - * - * @param headers a multimap of headers. - * @return the interceptor instance itself. - */ - public CustomHeaderInterceptor addHeaderMultimap(Map> headers) { - this.headers.putAll(headers); - return this; - } - - /** - * Remove a header. - * - * @param name the name of the header to remove. - * @return the interceptor instance itself. - */ - public CustomHeaderInterceptor removeHeader(String name) { - this.headers.remove(name); - return this; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request.Builder builder = chain.request().newBuilder(); - for (Map.Entry> header : headers.entrySet()) { - for (String value : header.getValue()) { - builder = builder.header(header.getKey(), value); - } - } - return chain.proceed(builder.build()); - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/DAGNode.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/DAGNode.java deleted file mode 100644 index 112130413fd87..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/DAGNode.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * The type representing node in a {@link DAGraph}. - * - * @param the type of the data stored in the node - */ -public class DAGNode extends Node { - private List dependentKeys; - private int toBeResolved; - private boolean isPreparer; - - /** - * Creates a DAG node. - * - * @param key unique id of the node - * @param data data to be stored in the node - */ - public DAGNode(String key, T data) { - super(key, data); - dependentKeys = new ArrayList<>(); - } - - /** - * @return a list of keys of nodes in {@link DAGraph} those are dependents on this node - */ - List dependentKeys() { - return Collections.unmodifiableList(this.dependentKeys); - } - - /** - * Mark the node identified by the given key as dependent of this node. - * - * @param key the id of the dependent node - */ - public void addDependent(String key) { - this.dependentKeys.add(key); - } - - /** - * @return a list of keys of nodes in {@link DAGraph} that this node depends on - */ - public List dependencyKeys() { - return this.children(); - } - - /** - * Mark the node identified by the given key as this node's dependency. - * - * @param dependencyKey the id of the dependency node - */ - public void addDependency(String dependencyKey) { - super.addChild(dependencyKey); - } - - /** - * @return true if this node has any dependency - */ - public boolean hasDependencies() { - return this.hasChildren(); - } - - /** - * Mark or un-mark this node as preparer. - * - * @param isPreparer true if this node needs to be marked as preparer, false otherwise. - */ - public void setPreparer(boolean isPreparer) { - this.isPreparer = isPreparer; - } - - /** - * @return true if this node is marked as preparer - */ - public boolean isPreparer() { - return isPreparer; - } - - /** - * Initialize the node so that traversal can be performed on the parent DAG. - */ - public void initialize() { - this.toBeResolved = this.dependencyKeys().size(); - this.dependentKeys.clear(); - } - - /** - * @return true if all dependencies of this node are ready to be consumed - */ - boolean hasAllResolved() { - return toBeResolved == 0; - } - - /** - * Reports that one of this node's dependency has been resolved and ready to be consumed. - * - * @param dependencyKey the id of the dependency node - */ - void reportResolved(String dependencyKey) { - if (toBeResolved == 0) { - throw new RuntimeException("invalid state - " + this.key() + ": The dependency '" + dependencyKey + "' is already reported or there is no such dependencyKey"); - } - toBeResolved--; - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/DAGraph.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/DAGraph.java deleted file mode 100644 index 58179e0152ed4..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/DAGraph.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import java.util.ArrayDeque; -import java.util.Map; -import java.util.Queue; - -/** - * Type representing a DAG (directed acyclic graph). - *

- * each node in a DAG is represented by {@link DAGNode} - * - * @param the type of the data stored in the graph nodes - * @param the type of the nodes in the graph - */ -public class DAGraph> extends Graph { - private Queue queue; - private boolean hasParent; - private U rootNode; - - /** - * Creates a new DAG. - * - * @param rootNode the root node of this DAG - */ - public DAGraph(U rootNode) { - this.rootNode = rootNode; - this.queue = new ArrayDeque<>(); - this.rootNode.setPreparer(true); - this.addNode(rootNode); - } - - /** - * @return true if this DAG is merged with another DAG and hence has a parent - */ - public boolean hasParent() { - return hasParent; - } - - /** - * Checks whether the given node is root node of this DAG. - * - * @param node the node {@link DAGNode} to be checked - * @return true if the given node is root node - */ - public boolean isRootNode(U node) { - return this.rootNode == node; - } - - /** - * @return true if this dag is the preparer responsible for - * preparing the DAG for traversal. - */ - public boolean isPreparer() { - return this.rootNode.isPreparer(); - } - - /** - * Merge this DAG with another DAG. - *

- * This will mark this DAG as a child DAG, the dependencies of nodes in this DAG will be merged - * with (copied to) the parent DAG - * - * @param parent the parent DAG - */ - public void merge(DAGraph parent) { - this.hasParent = true; - parent.rootNode.addDependency(this.rootNode.key()); - for (Map.Entry entry: graph.entrySet()) { - String key = entry.getKey(); - if (!parent.graph.containsKey(key)) { - parent.graph.put(key, entry.getValue()); - } - } - } - - /** - * Prepares this DAG for traversal using getNext method, each call to getNext returns next node - * in the DAG with no dependencies. - */ - public void prepare() { - if (isPreparer()) { - for (U node : graph.values()) { - // Prepare each node for traversal - node.initialize(); - if (!this.isRootNode(node)) { - // Mark other sub-DAGs as non-preparer - node.setPreparer(false); - } - } - initializeDependentKeys(); - initializeQueue(); - } - } - - /** - * Gets next node in the DAG which has no dependency or all of it's dependencies are resolved and - * ready to be consumed. - * - * @return next node or null if all the nodes have been explored - */ - public U getNext() { - return graph.get(queue.poll()); - } - - /** - * Gets the data stored in a graph node with a given key. - * - * @param key the key of the node - * @return the value stored in the node - */ - public T getNodeData(String key) { - return graph.get(key).data(); - } - - /** - * Reports that a node is resolved hence other nodes depends on it can consume it. - * - * @param completed the node ready to be consumed - */ - public void reportedCompleted(U completed) { - completed.setPreparer(true); - String dependency = completed.key(); - for (String dependentKey : graph.get(dependency).dependentKeys()) { - DAGNode dependent = graph.get(dependentKey); - dependent.reportResolved(dependency); - if (dependent.hasAllResolved()) { - queue.add(dependent.key()); - } - } - } - - /** - * Initializes dependents of all nodes. - *

- * The DAG will be explored in DFS order and all node's dependents will be identified, - * this prepares the DAG for traversal using getNext method, each call to getNext returns next node - * in the DAG with no dependencies. - */ - private void initializeDependentKeys() { - visit(new Visitor() { - // This 'visit' will be called only once per each node. - @Override - public void visit(U node) { - if (node.dependencyKeys().isEmpty()) { - return; - } - - String dependentKey = node.key(); - for (String dependencyKey : node.dependencyKeys()) { - graph.get(dependencyKey) - .addDependent(dependentKey); - } - } - }); - } - - /** - * Initializes the queue that tracks the next set of nodes with no dependencies or - * whose dependencies are resolved. - */ - private void initializeQueue() { - this.queue.clear(); - for (Map.Entry entry: graph.entrySet()) { - if (!entry.getValue().hasDependencies()) { - this.queue.add(entry.getKey()); - } - } - if (queue.isEmpty()) { - throw new RuntimeException("Found circular dependency"); - } - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Graph.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Graph.java deleted file mode 100644 index 40ceebaa50b2b..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Graph.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * Type representing a directed graph data structure. - *

- * Each node in a graph is represented by {@link Node} - * - * @param the type of the data stored in the graph's nodes - * @param the type of the nodes in the graph - */ -public class Graph> { - protected Map graph; - private Set visited; - - /** - * Creates a directed graph. - */ - public Graph() { - this.graph = new HashMap<>(); - this.visited = new HashSet<>(); - } - - /** - * Adds a node to this graph. - * - * @param node the node - */ - public void addNode(U node) { - graph.put(node.key(), node); - } - - /** - * Represents a visitor to be implemented by the consumer who want to visit the - * graph's nodes in DFS order. - * - * @param the type of the node - */ - interface Visitor { - /** - * visit a node. - * - * @param node the node to visited - */ - void visit(U node); - } - - /** - * Perform DFS visit in this graph. - *

- * The directed graph will be traversed in DFS order and the visitor will be notified as - * search explores each node - * - * @param visitor the graph visitor - */ - public void visit(Visitor visitor) { - for (Map.Entry> item : graph.entrySet()) { - if (!visited.contains(item.getKey())) { - this.dfs(visitor, item.getValue()); - } - } - visited.clear(); - } - - private void dfs(Visitor visitor, Node node) { - visitor.visit(node); - visited.add(node.key()); - for (String childKey : node.children()) { - if (!visited.contains(childKey)) { - this.dfs(visitor, this.graph.get(childKey)); - } - } - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/ListOperationCallback.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/ListOperationCallback.java deleted file mode 100644 index 6e0b2ea92a96b..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/ListOperationCallback.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.ServiceCallback; - -import java.util.List; - -/** - * The callback used for client side asynchronous list operations. - * - * @param the item type - */ -public abstract class ListOperationCallback extends ServiceCallback> { - /** - * A list result that stores the accumulated resources loaded from server. - */ - private List result; - - /** - * Number of loaded pages. - */ - private int pageCount; - - /** - * Creates an instance of ListOperationCallback. - */ - public ListOperationCallback() { - this.pageCount = 0; - } - - /** - * Override this method to handle progressive results. - * The user is responsible for returning a {@link PagingBahavior} Enum to indicate - * whether the client should continue loading or stop. - * - * @param partial the list of resources from the current request. - * @return CONTINUE if you want to go on loading, STOP otherwise. - * - */ - public PagingBahavior progress(List partial) { - return PagingBahavior.CONTINUE; - } - - /** - * Get the list result that stores the accumulated resources loaded from server. - * - * @return the list of resources. - */ - public List get() { - return result; - } - - /** - * This method is called by the client to load the most recent list of resources. - * This method should only be called by the service client. - * - * @param result the most recent list of resources. - */ - public void load(List result) { - ++pageCount; - if (this.result == null || this.result.isEmpty()) { - this.result = result; - } else { - this.result.addAll(result); - } - } - - /** - * Get the number of loaded pages. - * - * @return the number of pages. - */ - public int pageCount() { - return pageCount; - } - - /** - * An enum to indicate whether the client should continue loading or stop. - */ - public enum PagingBahavior { - /** - * Indicates that the client should continue loading. - */ - CONTINUE, - /** - * Indicates that the client should stop loading. - */ - STOP - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Node.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Node.java deleted file mode 100644 index cbb83f1d2a58f..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Node.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Type represents a node in a {@link Graph}. - * - * @param the type of the data stored in the node - */ -public class Node { - private String key; - private T data; - private List children; - - /** - * Creates a graph node. - * - * @param key unique id of the node - * @param data data to be stored in the node - */ - public Node(String key, T data) { - this.key = key; - this.data = data; - this.children = new ArrayList<>(); - } - - /** - * @return this node's unique id - */ - public String key() { - return this.key; - } - - /** - * @return data stored in this node - */ - public T data() { - return data; - } - - /** - * @return true if this node has any children - */ - public boolean hasChildren() { - return !this.children.isEmpty(); - } - - /** - * @return children (neighbours) of this node - */ - public List children() { - return Collections.unmodifiableList(this.children); - } - - /** - * @param childKey add a child (neighbour) of this node - */ - public void addChild(String childKey) { - this.children.add(childKey); - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Page.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Page.java deleted file mode 100644 index 0d3c04eb9215a..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Page.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import java.util.List; - -/** - * Defines a page interface in Azure responses. - * - * @param the element type. - */ -public interface Page { - /** - * Gets the link to the next page. - * - * @return the link. - */ - String getNextPageLink(); - - /** - * Gets the list of items. - * - * @return the list of items. - */ - List getItems(); -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java deleted file mode 100644 index a88a044f751e7..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java +++ /dev/null @@ -1,339 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.RestException; - -import javax.xml.bind.DataBindingException; -import javax.xml.ws.WebServiceException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -/** - * Defines a list response from a paging operation. The pages are - * lazy initialized when an instance of this class is iterated. - * - * @param the element type. - */ -public abstract class PagedList implements List { - /** The actual items in the list. */ - private List items; - /** Stores the link to get the next page of items. */ - private String nextPageLink; - /** Stores the latest page fetched. */ - private Page currentPage; - - /** - * Creates an instance of Pagedlist. - */ - public PagedList() { - items = new ArrayList<>(); - } - - /** - * Creates an instance of PagedList from a {@link Page} response. - * - * @param page the {@link Page} object. - */ - public PagedList(Page page) { - this(); - items.addAll(page.getItems()); - nextPageLink = page.getNextPageLink(); - currentPage = page; - } - - /** - * Override this method to load the next page of items from a next page link. - * - * @param nextPageLink the link to get the next page of items. - * @return the {@link Page} object storing a page of items and a link to the next page. - * @throws RestException thrown if an error is raised from Azure. - * @throws IOException thrown if there's any failure in deserialization. - */ - public abstract Page nextPage(String nextPageLink) throws RestException, IOException; - - /** - * If there are more pages available. - * - * @return true if there are more pages to load. False otherwise. - */ - public boolean hasNextPage() { - return this.nextPageLink != null; - } - - /** - * Loads a page from next page link. - * The exceptions are wrapped into Java Runtime exceptions. - */ - public void loadNextPage() { - try { - Page nextPage = nextPage(this.nextPageLink); - this.nextPageLink = nextPage.getNextPageLink(); - this.items.addAll(nextPage.getItems()); - this.currentPage = nextPage; - } catch (RestException e) { - throw new WebServiceException(e.toString(), e); - } catch (IOException e) { - throw new DataBindingException(e.getMessage(), e); - } - } - - /** - * Keep loading the next page from the next page link until all items are loaded. - */ - public void loadAll() { - while (hasNextPage()) { - loadNextPage(); - } - } - - /** - * Gets the latest page fetched. - * - * @return the latest page. - */ - public Page currentPage() { - return currentPage; - } - - /** - * Gets the next page's link. - * - * @return the next page link. - */ - public String nextPageLink() { - return nextPageLink; - } - - /** - * The implementation of {@link ListIterator} for PagedList. - */ - private class ListItr implements ListIterator { - /** The list iterator for the actual list of items. */ - private ListIterator itemsListItr; - - /** - * Creates an instance of the ListIterator. - * - * @param index the position in the list to start. - */ - ListItr(int index) { - itemsListItr = items.listIterator(index); - } - - @Override - public boolean hasNext() { - return itemsListItr.hasNext() || hasNextPage(); - } - - @Override - public E next() { - if (!itemsListItr.hasNext()) { - if (!hasNextPage()) { - throw new NoSuchElementException(); - } else { - int size = items.size(); - loadNextPage(); - itemsListItr = items.listIterator(size); - } - } - return itemsListItr.next(); - } - - @Override - public void remove() { - itemsListItr.remove(); - } - - @Override - public boolean hasPrevious() { - return itemsListItr.hasPrevious(); - } - - @Override - public E previous() { - return itemsListItr.previous(); - } - - @Override - public int nextIndex() { - return itemsListItr.nextIndex(); - } - - @Override - public int previousIndex() { - return itemsListItr.previousIndex(); - } - - @Override - public void set(E e) { - itemsListItr.set(e); - } - - @Override - public void add(E e) { - itemsListItr.add(e); - } - } - - @Override - public int size() { - loadAll(); - return items.size(); - } - - @Override - public boolean isEmpty() { - return items.isEmpty() && !hasNextPage(); - } - - @Override - public boolean contains(Object o) { - return indexOf(o) >= 0; - } - - @Override - public Iterator iterator() { - return new ListItr(0); - } - - @Override - public Object[] toArray() { - loadAll(); - return items.toArray(); - } - - @Override - public T[] toArray(T[] a) { - loadAll(); - return items.toArray(a); - } - - @Override - public boolean add(E e) { - return items.add(e); - } - - @Override - public boolean remove(Object o) { - return items.remove(o); - } - - @Override - public boolean containsAll(Collection c) { - for (Object e : c) { - if (!contains(e)) { - return false; - } - } - return true; - } - - @Override - public boolean addAll(Collection c) { - return items.addAll(c); - } - - @Override - public boolean addAll(int index, Collection c) { - return items.addAll(index, c); - } - - @Override - public boolean removeAll(Collection c) { - return items.removeAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return items.retainAll(c); - } - - @Override - public void clear() { - items.clear(); - } - - @Override - public E get(int index) { - while (index >= items.size() && hasNextPage()) { - loadNextPage(); - } - return items.get(index); - } - - @Override - public E set(int index, E element) { - return items.set(index, element); - } - - @Override - public void add(int index, E element) { - items.add(index, element); - } - - @Override - public E remove(int index) { - return items.remove(index); - } - - @Override - public int indexOf(Object o) { - int index = 0; - if (o == null) { - for (E item : this) { - if (item == null) { - return index; - } - ++index; - } - } else { - for (E item : this) { - if (item == o) { - return index; - } - ++index; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object o) { - loadAll(); - return items.lastIndexOf(o); - } - - @Override - public ListIterator listIterator() { - return new ListItr(0); - } - - @Override - public ListIterator listIterator(int index) { - while (index >= items.size() && hasNextPage()) { - loadNextPage(); - } - return new ListItr(index); - } - - @Override - public List subList(int fromIndex, int toIndex) { - while ((fromIndex >= items.size() - || toIndex >= items.size()) - && hasNextPage()) { - loadNextPage(); - } - return items.subList(fromIndex, toIndex); - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PollingState.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PollingState.java deleted file mode 100644 index 50255ba600899..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PollingState.java +++ /dev/null @@ -1,316 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.microsoft.rest.serializer.JacksonMapperAdapter; - -import java.io.IOException; -import java.lang.reflect.Type; - -import okhttp3.ResponseBody; -import retrofit2.Response; - -/** - * An instance of this class defines the state of a long running operation. - * - * @param the type of the resource the operation returns. - */ -public class PollingState { - /** The Retrofit response object. */ - private Response response; - /** The polling status. */ - private String status; - /** The link in 'Azure-AsyncOperation' header. */ - private String azureAsyncOperationHeaderLink; - /** The link in 'Location' Header. */ - private String locationHeaderLink; - /** The timeout interval between two polling operations. */ - private Integer retryTimeout; - /** The response resource object. */ - private T resource; - /** The type of the response resource object. */ - private Type resourceType; - /** The error during the polling operations. */ - private CloudError error; - /** The adapter for {@link com.fasterxml.jackson.databind.ObjectMapper}. */ - private JacksonMapperAdapter mapperAdapter; - - /** - * Initializes an instance of {@link PollingState}. - * - * @param response the response from Retrofit REST call. - * @param retryTimeout the long running operation retry timeout. - * @param resourceType the type of the resource the long running operation returns - * @param mapperAdapter the adapter for the Jackson object mapper - * @throws IOException thrown by deserialization - */ - public PollingState(Response response, Integer retryTimeout, Type resourceType, JacksonMapperAdapter mapperAdapter) throws IOException { - this.retryTimeout = retryTimeout; - this.setResponse(response); - this.resourceType = resourceType; - this.mapperAdapter = mapperAdapter; - - String responseContent = null; - PollingResource resource = null; - if (response.body() != null) { - responseContent = response.body().string(); - response.body().close(); - } - if (responseContent != null && !responseContent.isEmpty()) { - this.resource = mapperAdapter.deserialize(responseContent, resourceType); - resource = mapperAdapter.deserialize(responseContent, PollingResource.class); - } - if (resource != null && resource.getProperties() != null - && resource.getProperties().getProvisioningState() != null) { - setStatus(resource.getProperties().getProvisioningState()); - } else { - switch (this.response.code()) { - case 202: - setStatus(AzureAsyncOperation.IN_PROGRESS_STATUS); - break; - case 204: - case 201: - case 200: - setStatus(AzureAsyncOperation.SUCCESS_STATUS); - break; - default: - setStatus(AzureAsyncOperation.FAILED_STATUS); - } - } - } - - /** - * Updates the polling state from a PUT or PATCH operation. - * - * @param response the response from Retrofit REST call - * @throws CloudException thrown if the response is invalid - * @throws IOException thrown by deserialization - */ - public void updateFromResponseOnPutPatch(Response response) throws CloudException, IOException { - String responseContent = null; - if (response.body() != null) { - responseContent = response.body().string(); - response.body().close(); - } - - if (responseContent == null || responseContent.isEmpty()) { - CloudException exception = new CloudException("no body"); - exception.setResponse(response); - throw exception; - } - - PollingResource resource = mapperAdapter.deserialize(responseContent, PollingResource.class); - if (resource != null && resource.getProperties() != null && resource.getProperties().getProvisioningState() != null) { - this.setStatus(resource.getProperties().getProvisioningState()); - } else { - this.setStatus(AzureAsyncOperation.SUCCESS_STATUS); - } - - CloudError error = new CloudError(); - this.setError(error); - error.setCode(this.getStatus()); - error.setMessage("Long running operation failed"); - this.setResponse(response); - this.setResource(mapperAdapter.deserialize(responseContent, resourceType)); - } - - /** - * Updates the polling state from a DELETE or POST operation. - * - * @param response the response from Retrofit REST call - * @throws IOException thrown by deserialization - */ - - public void updateFromResponseOnDeletePost(Response response) throws IOException { - this.setResponse(response); - String responseContent = null; - if (response.body() != null) { - responseContent = response.body().string(); - response.body().close(); - } - this.setResource(mapperAdapter.deserialize(responseContent, resourceType)); - setStatus(AzureAsyncOperation.SUCCESS_STATUS); - } - - /** - * Gets long running operation delay in milliseconds. - * - * @return the delay in milliseconds. - */ - public int getDelayInMilliseconds() { - if (this.retryTimeout != null) { - return this.retryTimeout * 1000; - } - if (this.response != null && response.headers().get("Retry-After") != null) { - return Integer.parseInt(response.headers().get("Retry-After")) * 1000; - } - return AzureAsyncOperation.DEFAULT_DELAY * 1000; - } - - /** - * Gets the polling status. - * - * @return the polling status. - */ - public String getStatus() { - return status; - } - - - /** - * Sets the polling status. - * - * @param status the polling status. - * @throws IllegalArgumentException thrown if status is null. - */ - public void setStatus(String status) throws IllegalArgumentException { - if (status == null) { - throw new IllegalArgumentException("Status is null."); - } - this.status = status; - } - - /** - * Gets the last operation response. - * - * @return the last operation response. - */ - public Response getResponse() { - return this.response; - } - - - /** - * Sets the last operation response. - * - * @param response the last operation response. - */ - public void setResponse(Response response) { - this.response = response; - if (response != null) { - String asyncHeader = response.headers().get("Azure-AsyncOperation"); - String locationHeader = response.headers().get("Location"); - if (asyncHeader != null) { - this.azureAsyncOperationHeaderLink = asyncHeader; - } - if (locationHeader != null) { - this.locationHeaderLink = locationHeader; - } - } - } - - /** - * Gets the latest value captured from Azure-AsyncOperation header. - * - * @return the link in the header. - */ - public String getAzureAsyncOperationHeaderLink() { - return azureAsyncOperationHeaderLink; - } - - /** - * Gets the latest value captured from Location header. - * - * @return the link in the header. - */ - public String getLocationHeaderLink() { - return locationHeaderLink; - } - - /** - * Gets the resource. - * - * @return the resource. - */ - public T getResource() { - return resource; - } - - /** - * Sets the resource. - * - * @param resource the resource. - */ - public void setResource(T resource) { - this.resource = resource; - } - - /** - * Gets {@link CloudError} from current instance. - * - * @return the cloud error. - */ - public CloudError getError() { - return error; - } - - /** - * Sets {@link CloudError} from current instance. - * - * @param error the cloud error. - */ - public void setError(CloudError error) { - this.error = error; - } - - /** - * An instance of this class describes the status of a long running operation - * and is returned from server each time. - */ - static class PollingResource { - /** Inner properties object. */ - @JsonProperty(value = "properties") - private Properties properties; - - /** - * Gets the inner properties object. - * - * @return the inner properties. - */ - public Properties getProperties() { - return properties; - } - - /** - * Sets the inner properties object. - * - * @param properties the inner properties. - */ - public void setProperties(Properties properties) { - this.properties = properties; - } - - /** - * Inner properties class. - */ - static class Properties { - /** The provisioning state of the resource. */ - @JsonProperty(value = "provisioningState") - private String provisioningState; - - /** - * Gets the provisioning state of the resource. - * - * @return the provisioning state. - */ - public String getProvisioningState() { - return provisioningState; - } - - /** - * Sets the provisioning state of the resource. - * - * @param provisioningState the provisioning state. - */ - public void setProvisioningState(String provisioningState) { - this.provisioningState = provisioningState; - } - } - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/RequestIdHeaderInterceptor.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/RequestIdHeaderInterceptor.java deleted file mode 100644 index ddbe0db30ec0b..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/RequestIdHeaderInterceptor.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -import java.io.IOException; -import java.util.UUID; - -/** - * An instance of this class puts an UUID in the request header. Azure uses - * the request id as the unique identifier for - */ -public class RequestIdHeaderInterceptor implements Interceptor { - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request().newBuilder() - .header("x-ms-client-request-id", UUID.randomUUID().toString()) - .build(); - return chain.proceed(request); - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Resource.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Resource.java deleted file mode 100644 index 2f98e586a960d..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/Resource.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.Map; - -/** - * The Resource model. - */ -public class Resource { - /** - * Resource Id. - */ - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) - private String id; - - /** - * Resource name. - */ - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) - private String name; - - /** - * Resource type. - */ - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) - private String type; - - /** - * Resource location. - */ - @JsonProperty(required = true) - private String location; - - /** - * Resource tags. - */ - private Map tags; - - /** - * Get the id value. - * - * @return the id value - */ - public String id() { - return this.id; - } - - /** - * Get the name value. - * - * @return the name value - */ - public String name() { - return this.name; - } - - /** - * Get the type value. - * - * @return the type value - */ - public String type() { - return this.type; - } - - /** - * Get the location value. - * - * @return the location value - */ - public String location() { - return this.location; - } - - /** - * Set the location value. - * - * @param location the location value to set - * @return the resource itself - */ - public Resource withLocation(String location) { - this.location = location; - return this; - } - - /** - * Get the tags value. - * - * @return the tags value - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags value. - * - * @param tags the tags value to set - * @return the resource itself - */ - public Resource withTags(Map tags) { - this.tags = tags; - return this; - } -} \ No newline at end of file diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/ResourceGetExponentialBackoffRetryStrategy.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/ResourceGetExponentialBackoffRetryStrategy.java deleted file mode 100644 index a145fecc6795b..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/ResourceGetExponentialBackoffRetryStrategy.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.retry.RetryStrategy; -import okhttp3.Response; - -/** - * A retry strategy with backoff parameters for calculating the exponential - * delay between retries for 404s from GET calls. - */ -public class ResourceGetExponentialBackoffRetryStrategy extends RetryStrategy { - /** - * Represents the default number of retries. - */ - private static final int DEFAULT_NUMBER_OF_ATTEMPTS = 3; - - /** - * Creates an instance of the retry strategy. - */ - public ResourceGetExponentialBackoffRetryStrategy() { - this(null, DEFAULT_FIRST_FAST_RETRY); - } - - /** - * Initializes a new instance of the {@link RetryStrategy} class. - * - * @param name The name of the retry strategy. - * @param firstFastRetry true to immediately retry in the first attempt; otherwise, false. - */ - private ResourceGetExponentialBackoffRetryStrategy(String name, boolean firstFastRetry) { - super(name, firstFastRetry); - } - - @Override - public boolean shouldRetry(int retryCount, Response response) { - int code = response.code(); - //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES - return retryCount < DEFAULT_NUMBER_OF_ATTEMPTS - && code == 404 - && response.request().method().equalsIgnoreCase("GET"); - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/RestClient.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/RestClient.java deleted file mode 100644 index 0ace881f0ee51..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/RestClient.java +++ /dev/null @@ -1,351 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.azure.serializer.AzureJacksonMapperAdapter; -import com.microsoft.rest.BaseUrlHandler; -import com.microsoft.rest.CustomHeadersInterceptor; -import com.microsoft.rest.UserAgentInterceptor; -import com.microsoft.rest.credentials.ServiceClientCredentials; -import com.microsoft.rest.retry.RetryHandler; -import com.microsoft.rest.serializer.JacksonMapperAdapter; -import okhttp3.ConnectionPool; -import okhttp3.Interceptor; -import okhttp3.JavaNetCookieJar; -import okhttp3.OkHttpClient; -import okhttp3.logging.HttpLoggingInterceptor; -import retrofit2.Retrofit; - -import java.lang.reflect.Field; -import java.net.CookieManager; -import java.net.CookiePolicy; -import java.net.Proxy; -import java.util.concurrent.Executor; -import java.util.concurrent.TimeUnit; - -/** - * An instance of this class stores the client information for making REST calls. - */ -public class RestClient { - /** The {@link okhttp3.OkHttpClient} object. */ - private OkHttpClient httpClient; - /** The {@link retrofit2.Retrofit} object. */ - private Retrofit retrofit; - /** The credentials to authenticate. */ - private ServiceClientCredentials credentials; - /** The interceptor to handle custom headers. */ - private CustomHeadersInterceptor customHeadersInterceptor; - /** The interceptor to handle base URL. */ - private BaseUrlHandler baseUrlHandler; - /** The adapter to a Jackson {@link com.fasterxml.jackson.databind.ObjectMapper}. */ - private JacksonMapperAdapter mapperAdapter; - /** The interceptor to set 'User-Agent' header. */ - private UserAgentInterceptor userAgentInterceptor; - - protected RestClient(OkHttpClient httpClient, - Retrofit retrofit, - ServiceClientCredentials credentials, - CustomHeadersInterceptor customHeadersInterceptor, - UserAgentInterceptor userAgentInterceptor, - BaseUrlHandler baseUrlHandler, - JacksonMapperAdapter mapperAdapter) { - this.httpClient = httpClient; - this.retrofit = retrofit; - this.credentials = credentials; - this.customHeadersInterceptor = customHeadersInterceptor; - this.userAgentInterceptor = userAgentInterceptor; - this.baseUrlHandler = baseUrlHandler; - this.mapperAdapter = mapperAdapter; - } - - /** - * Get the headers interceptor. - * - * @return the headers interceptor. - */ - public CustomHeadersInterceptor headers() { - return customHeadersInterceptor; - } - - /** - * Get the adapter to {@link com.fasterxml.jackson.databind.ObjectMapper}. - * - * @return the Jackson mapper adapter. - */ - public JacksonMapperAdapter mapperAdapter() { - return mapperAdapter; - } - - /** - * Sets the mapper adapter. - * - * @param mapperAdapter an adapter to a Jackson mapper. - * @return the builder itself for chaining. - */ - public RestClient withMapperAdapater(JacksonMapperAdapter mapperAdapter) { - this.mapperAdapter = mapperAdapter; - return this; - } - - /** - * Get the http client. - * - * @return the {@link OkHttpClient} object. - */ - public OkHttpClient httpClient() { - return httpClient; - } - - /** - * Get the retrofit instance. - * - * @return the {@link Retrofit} object. - */ - public Retrofit retrofit() { - return retrofit; - } - - /** - * Get the credentials attached to this REST client. - * - * @return the credentials. - */ - public ServiceClientCredentials credentials() { - return this.credentials; - } - - /** - * The builder class for building a REST client. - */ - public static class Builder { - /** The dynamic base URL with variables wrapped in "{" and "}". */ - protected String baseUrl; - /** The builder to build an {@link OkHttpClient}. */ - protected OkHttpClient.Builder httpClientBuilder; - /** The builder to build a {@link Retrofit}. */ - protected Retrofit.Builder retrofitBuilder; - /** The credentials to authenticate. */ - protected ServiceClientCredentials credentials; - /** The interceptor to handle custom headers. */ - protected CustomHeadersInterceptor customHeadersInterceptor; - /** The interceptor to handle base URL. */ - protected BaseUrlHandler baseUrlHandler; - /** The interceptor to set 'User-Agent' header. */ - protected UserAgentInterceptor userAgentInterceptor; - /** The inner Builder instance. */ - protected Buildable buildable; - - /** - * Creates an instance of the builder with a base URL to the service. - */ - public Builder() { - this(new OkHttpClient.Builder(), new Retrofit.Builder()); - } - - /** - * Creates an instance of the builder with a base URL and 2 custom builders. - * - * @param httpClientBuilder the builder to build an {@link OkHttpClient}. - * @param retrofitBuilder the builder to build a {@link Retrofit}. - */ - public Builder(OkHttpClient.Builder httpClientBuilder, Retrofit.Builder retrofitBuilder) { - if (httpClientBuilder == null) { - throw new IllegalArgumentException("httpClientBuilder == null"); - } - if (retrofitBuilder == null) { - throw new IllegalArgumentException("retrofitBuilder == null"); - } - CookieManager cookieManager = new CookieManager(); - cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); - customHeadersInterceptor = new CustomHeadersInterceptor(); - baseUrlHandler = new BaseUrlHandler(); - userAgentInterceptor = new UserAgentInterceptor(); - // Set up OkHttp client - this.httpClientBuilder = httpClientBuilder - .cookieJar(new JavaNetCookieJar(cookieManager)) - .addInterceptor(userAgentInterceptor); - this.retrofitBuilder = retrofitBuilder; - this.buildable = new Buildable(); - } - - /** - * Sets the dynamic base URL. - * - * @param baseUrl the base URL to use. - * @return the builder itself for chaining. - */ - public Buildable withBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; - return buildable; - } - - /** - * Sets the base URL with the default from the service client. - * - * @param serviceClientClass the service client class containing a default base URL. - * @return the builder itself for chaining. - */ - public Buildable withDefaultBaseUrl(Class serviceClientClass) { - try { - Field field = serviceClientClass.getDeclaredField("DEFAULT_BASE_URL"); - field.setAccessible(true); - baseUrl = (String) field.get(null); - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new UnsupportedOperationException("Cannot read static field DEFAULT_BASE_URL", e); - } - return buildable; - } - - /** - * Sets the base URL with the default from the Azure Environment. - * - * @param environment the environment the application is running in - * @return the builder itself for chaining - */ - public RestClient.Builder.Buildable withDefaultBaseUrl(AzureEnvironment environment) { - withBaseUrl(environment.getBaseUrl()); - return buildable; - } - - /** - * The inner class from which a Rest Client can be built. - */ - public class Buildable { - /** - * Sets the user agent header. - * - * @param userAgent the user agent header. - * @return the builder itself for chaining. - */ - public Buildable withUserAgent(String userAgent) { - userAgentInterceptor.withUserAgent(userAgent); - return this; - } - - /** - * Sets the credentials. - * - * @param credentials the credentials object. - * @return the builder itself for chaining. - */ - public Buildable withCredentials(ServiceClientCredentials credentials) { - Builder.this.credentials = credentials; - if (credentials != null) { - credentials.applyCredentialsFilter(httpClientBuilder); - } - return this; - } - - /** - * Sets the log level. - * - * @param logLevel the {@link okhttp3.logging.HttpLoggingInterceptor.Level} enum. - * @return the builder itself for chaining. - */ - public Buildable withLogLevel(HttpLoggingInterceptor.Level logLevel) { - httpClientBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(logLevel)); - return this; - } - - /** - * Add an interceptor the Http client pipeline. - * - * @param interceptor the interceptor to add. - * @return the builder itself for chaining. - */ - public Buildable withInterceptor(Interceptor interceptor) { - httpClientBuilder.addInterceptor(interceptor); - return this; - } - - /** - * Set the read timeout on the HTTP client. Default is 10 seconds. - * - * @param timeout the timeout numeric value - * @param unit the time unit for the numeric value - * @return the builder itself for chaining - */ - public Buildable withReadTimeout(long timeout, TimeUnit unit) { - httpClientBuilder.readTimeout(timeout, unit); - return this; - } - - /** - * Set the connection timeout on the HTTP client. Default is 10 seconds. - * - * @param timeout the timeout numeric value - * @param unit the time unit for the numeric value - * @return the builder itself for chaining - */ - public Buildable withConnectionTimeout(long timeout, TimeUnit unit) { - httpClientBuilder.connectTimeout(timeout, unit); - return this; - } - - /** - * Set the maximum idle connections for the HTTP client. Default is 5. - * - * @param maxIdleConnections the maximum idle connections - * @return the builder itself for chaining - */ - public Buildable withMaxIdleConnections(int maxIdleConnections) { - httpClientBuilder.connectionPool(new ConnectionPool(maxIdleConnections, 5, TimeUnit.MINUTES)); - return this; - } - - /** - * Sets the executor for async callbacks to run on. - * - * @param executor the executor to execute the callbacks. - * @return the builder itself for chaining - */ - public Buildable withCallbackExecutor(Executor executor) { - retrofitBuilder.callbackExecutor(executor); - return this; - } - - /** - * Sets the proxy for the HTTP client. - * - * @param proxy the proxy to use - * @return the builder itself for chaining - */ - public Buildable withProxy(Proxy proxy) { - httpClientBuilder.proxy(proxy); - return this; - } - - /** - * Build a RestClient with all the current configurations. - * - * @return a {@link RestClient}. - */ - public RestClient build() { - AzureJacksonMapperAdapter mapperAdapter = new AzureJacksonMapperAdapter(); - OkHttpClient httpClient = httpClientBuilder - .addInterceptor(baseUrlHandler) - .addInterceptor(customHeadersInterceptor) - .addInterceptor(new RetryHandler(new ResourceGetExponentialBackoffRetryStrategy())) - .addInterceptor(new RetryHandler()) - .build(); - return new RestClient(httpClient, - retrofitBuilder - .baseUrl(baseUrl) - .client(httpClient) - .addConverterFactory(mapperAdapter.getConverterFactory()) - .build(), - credentials, - customHeadersInterceptor, - userAgentInterceptor, - baseUrlHandler, - mapperAdapter); - } - - } - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/SubResource.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/SubResource.java deleted file mode 100644 index 12bedc30c57fc..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/SubResource.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -/** - * The SubResource model. - */ -public class SubResource { - /** - * Resource Id. - */ - private String id; - - /** - * Get the id value. - * - * @return the id value - */ - public String id() { - return this.id; - } - - /** - * Set the id value. - * - * @param id the id value to set - * @return the sub resource itself - */ - public SubResource withId(String id) { - this.id = id; - return this; - } -} \ No newline at end of file diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/TaskGroup.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/TaskGroup.java deleted file mode 100644 index 26bbbece2606b..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/TaskGroup.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.ServiceCall; -import com.microsoft.rest.ServiceCallback; - -/** - * Represents a group of related tasks. - *

- * each task in a group is represented by {@link TaskItem} - * - * @param the type of result of tasks in the group - * @param the task type - */ -public interface TaskGroup> { - /** - * Gets underlying directed acyclic graph structure that stores tasks in the group and - * dependency information between them. - * - * @return the dag - */ - DAGraph> dag(); - - /** - * Merges this task group with parent task group. - *

- * once merged, calling execute in the parent group will executes the task in this - * group as well. - * - * @param parentTaskGroup task group - */ - void merge(TaskGroup parentTaskGroup); - - /** - * @return true if the group is responsible for preparing execution of original task in - * this group and all tasks belong other task group it composes. - */ - boolean isPreparer(); - - /** - * Prepare the graph for execution. - */ - void prepare(); - - /** - * Executes the tasks in the group. - *

- * the order of execution of tasks ensure that a task gets selected for execution only after - * the execution of all the tasks it depends on - * @throws Exception the exception - */ - void execute() throws Exception; - - /** - * Executes the tasks in the group asynchronously. - * - * @param callback the callback to call on failure or success - * @return the handle to the REST call - */ - ServiceCall executeAsync(ServiceCallback callback); - - /** - * Gets the result of execution of a task in the group. - *

- * this method can null if the task has not yet been executed - * - * @param taskId the task id - * @return the task result - */ - T taskResult(String taskId); -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/TaskGroupBase.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/TaskGroupBase.java deleted file mode 100644 index efc8d30e491bc..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/TaskGroupBase.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.ServiceCall; -import com.microsoft.rest.ServiceCallback; - -/** - * The base implementation of TaskGroup interface. - * - * @param the result type of the tasks in the group - */ -public abstract class TaskGroupBase - implements TaskGroup> { - private DAGraph, DAGNode>> dag; - - /** - * Creates TaskGroupBase. - * - * @param rootTaskItemId the id of the root task in this task group - * @param rootTaskItem the root task - */ - public TaskGroupBase(String rootTaskItemId, TaskItem rootTaskItem) { - this.dag = new DAGraph<>(new DAGNode<>(rootTaskItemId, rootTaskItem)); - } - - @Override - public DAGraph, DAGNode>> dag() { - return dag; - } - - @Override - public boolean isPreparer() { - return dag.isPreparer(); - } - - @Override - public void merge(TaskGroup> parentTaskGroup) { - dag.merge(parentTaskGroup.dag()); - } - - @Override - public void prepare() { - if (isPreparer()) { - dag.prepare(); - } - } - - @Override - public void execute() throws Exception { - DAGNode> nextNode = dag.getNext(); - if (nextNode == null) { - return; - } - - if (dag.isRootNode(nextNode)) { - executeRootTask(nextNode.data()); - } else { - nextNode.data().execute(this, nextNode); - } - } - - @Override - public ServiceCall executeAsync(final ServiceCallback callback) { - final DAGNode> nextNode = dag.getNext(); - if (nextNode == null) { - return null; - } - - if (dag.isRootNode(nextNode)) { - return executeRootTaskAsync(nextNode.data(), callback); - } else { - return nextNode.data().executeAsync(this, nextNode, callback); - } - } - - @Override - public T taskResult(String taskId) { - return dag.getNodeData(taskId).result(); - } - - /** - * Executes the root task in this group. - *

- * This method will be invoked when all the task dependencies of the root task are finished - * executing, at this point root task can be executed by consuming the result of tasks it - * depends on. - * - * @param task the root task in this group - * @throws Exception the exception - */ - public abstract void executeRootTask(TaskItem task) throws Exception; - - /** - * Executes the root task in this group asynchronously. - *

- * This method will be invoked when all the task dependencies of the root task are finished - * executing, at this point root task can be executed by consuming the result of tasks it - * depends on. - * - * @param task the root task in this group - * @param callback the callback when the task fails or succeeds - * @return the handle to the REST call - */ - public abstract ServiceCall executeRootTaskAsync(TaskItem task, ServiceCallback callback); -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/TaskItem.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/TaskItem.java deleted file mode 100644 index fb74c23845c3b..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/TaskItem.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.ServiceCall; -import com.microsoft.rest.ServiceCallback; - -/** - * Type representing a task in a task group {@link TaskGroup}. - * - * @param the task result type - */ -public interface TaskItem { - /** - * @return the result of the task execution - */ - U result(); - - /** - * Executes the task. - *

- * once executed the result will be available through result getter - * - * @param taskGroup the task group dispatching tasks - * @param node the node the task item is associated with - * @throws Exception exception - */ - void execute(TaskGroup> taskGroup, DAGNode> node) throws Exception; - - /** - * Executes the task asynchronously. - *

- * once executed the result will be available through result getter - - * @param taskGroup the task group dispatching tasks - * @param node the node the task item is associated with - * @param callback callback to call on success or failure - * @return the handle of the REST call - */ - ServiceCall executeAsync(TaskGroup> taskGroup, DAGNode> node, ServiceCallback callback); -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/package-info.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/package-info.java deleted file mode 100644 index a94e7e5884c5d..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * The package contains the runtime classes required for AutoRest generated - * Azure clients to compile and function. To learn more about AutoRest generator, - * see https://github.com/azure/autorest. - */ -package com.microsoft.azure; \ No newline at end of file diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/serializer/AzureJacksonMapperAdapter.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/serializer/AzureJacksonMapperAdapter.java deleted file mode 100644 index d73fcd6f925c4..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/serializer/AzureJacksonMapperAdapter.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure.serializer; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.microsoft.rest.serializer.FlatteningDeserializer; -import com.microsoft.rest.serializer.FlatteningSerializer; -import com.microsoft.rest.serializer.JacksonMapperAdapter; - -/** - * A serialization helper class overriding {@link JacksonMapperAdapter} with extra - * functionality useful for Azure operations. - */ -public final class AzureJacksonMapperAdapter extends JacksonMapperAdapter { - /** - * An instance of {@link ObjectMapper} to serialize/deserialize objects. - */ - private ObjectMapper azureObjectMapper; - - @Override - public ObjectMapper getObjectMapper() { - if (azureObjectMapper == null) { - azureObjectMapper = new ObjectMapper(); - initializeObjectMapper(azureObjectMapper); - azureObjectMapper.registerModule(FlatteningSerializer.getModule(getSimpleMapper())) - .registerModule(FlatteningDeserializer.getModule(getSimpleMapper())) - .registerModule(CloudErrorDeserializer.getModule(getSimpleMapper())); - } - return azureObjectMapper; - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/serializer/CloudErrorDeserializer.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/serializer/CloudErrorDeserializer.java deleted file mode 100644 index ee0a371cf2add..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/serializer/CloudErrorDeserializer.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure.serializer; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.microsoft.azure.CloudError; - -import java.io.IOException; - -/** - * Custom serializer for serializing {@link CloudError} objects. - */ -public class CloudErrorDeserializer extends JsonDeserializer { - /** Object mapper for default deserializations. */ - private ObjectMapper mapper; - - /** - * Creates an instance of CloudErrorDeserializer. - * - * @param mapper the object mapper for default deserializations. - */ - protected CloudErrorDeserializer(ObjectMapper mapper) { - this.mapper = mapper; - } - - /** - * Gets a module wrapping this serializer as an adapter for the Jackson - * ObjectMapper. - * - * @param mapper the object mapper for default deserializations. - * @return a simple module to be plugged onto Jackson ObjectMapper. - */ - public static SimpleModule getModule(ObjectMapper mapper) { - SimpleModule module = new SimpleModule(); - module.addDeserializer(CloudError.class, new CloudErrorDeserializer(mapper)); - return module; - } - - @Override - public CloudError deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode topNode = p.readValueAsTree(); - if (topNode == null) { - return null; - } - JsonNode errorNode = topNode.get("error"); - if (errorNode == null) { - return null; - } - JsonParser parser = new JsonFactory().createParser(errorNode.toString()); - parser.setCodec(mapper); - return parser.readValueAs(CloudError.class); - } -} diff --git a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/serializer/package-info.java b/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/serializer/package-info.java deleted file mode 100644 index f436fafd93926..0000000000000 --- a/src/client/Java/azure-client-runtime/src/main/java/com/microsoft/azure/serializer/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * The package contains classes that handle serialization and deserialization - * for the REST call payloads in Azure. - */ -package com.microsoft.azure.serializer; \ No newline at end of file diff --git a/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/DAGraphTest.java b/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/DAGraphTest.java deleted file mode 100644 index f3b278797e2dd..0000000000000 --- a/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/DAGraphTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.microsoft.azure; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -public class DAGraphTest { - @Test - public void testDAGraphGetNext() { - /** - * |-------->[D]------>[B]-----------[A] - * | ^ ^ - * | | | - * [F]------->[E]-------| | - * | | | - * | |------->[G]----->[C]---- - * | - * |-------->[H]-------------------->[I] - */ - List expectedOrder = new ArrayList<>(); - expectedOrder.add("A"); expectedOrder.add("I"); - expectedOrder.add("B"); expectedOrder.add("C"); expectedOrder.add("H"); - expectedOrder.add("D"); expectedOrder.add("G"); - expectedOrder.add("E"); - expectedOrder.add("F"); - - DAGNode nodeA = new DAGNode<>("A", "dataA"); - DAGNode nodeI = new DAGNode<>("I", "dataI"); - - DAGNode nodeB = new DAGNode<>("B", "dataB"); - nodeB.addDependency(nodeA.key()); - - DAGNode nodeC = new DAGNode<>("C", "dataC"); - nodeC.addDependency(nodeA.key()); - - DAGNode nodeH = new DAGNode<>("H", "dataH"); - nodeH.addDependency(nodeI.key()); - - DAGNode nodeG = new DAGNode<>("G", "dataG"); - nodeG.addDependency(nodeC.key()); - - DAGNode nodeE = new DAGNode<>("E", "dataE"); - nodeE.addDependency(nodeB.key()); - nodeE.addDependency(nodeG.key()); - - DAGNode nodeD = new DAGNode<>("D", "dataD"); - nodeD.addDependency(nodeB.key()); - - - DAGNode nodeF = new DAGNode<>("F", "dataF"); - nodeF.addDependency(nodeD.key()); - nodeF.addDependency(nodeE.key()); - nodeF.addDependency(nodeH.key()); - - DAGraph> dag = new DAGraph<>(nodeF); - dag.addNode(nodeA); - dag.addNode(nodeB); - dag.addNode(nodeC); - dag.addNode(nodeD); - dag.addNode(nodeE); - dag.addNode(nodeG); - dag.addNode(nodeH); - dag.addNode(nodeI); - - dag.prepare(); - DAGNode nextNode = dag.getNext(); - int i = 0; - while (nextNode != null) { - Assert.assertEquals(nextNode.key(), expectedOrder.get(i)); - dag.reportedCompleted(nextNode); - nextNode = dag.getNext(); - i++; - } - - System.out.println("done"); - } - - @Test - public void testGraphMerge() { - /** - * |-------->[D]------>[B]-----------[A] - * | ^ ^ - * | | | - * [F]------->[E]-------| | - * | | | - * | |------->[G]----->[C]---- - * | - * |-------->[H]-------------------->[I] - */ - List expectedOrder = new ArrayList<>(); - expectedOrder.add("A"); expectedOrder.add("I"); - expectedOrder.add("B"); expectedOrder.add("C"); expectedOrder.add("H"); - expectedOrder.add("D"); expectedOrder.add("G"); - expectedOrder.add("E"); - expectedOrder.add("F"); - - DAGraph> graphA = createGraph("A"); - DAGraph> graphI = createGraph("I"); - - DAGraph> graphB = createGraph("B"); - graphA.merge(graphB); - - DAGraph> graphC = createGraph("C"); - graphA.merge(graphC); - - DAGraph> graphH = createGraph("H"); - graphI.merge(graphH); - - DAGraph> graphG = createGraph("G"); - graphC.merge(graphG); - - DAGraph> graphE = createGraph("E"); - graphB.merge(graphE); - graphG.merge(graphE); - - DAGraph> graphD = createGraph("D"); - graphB.merge(graphD); - - DAGraph> graphF = createGraph("F"); - graphD.merge(graphF); - graphE.merge(graphF); - graphH.merge(graphF); - - DAGraph> dag = graphF; - dag.prepare(); - - DAGNode nextNode = dag.getNext(); - int i = 0; - while (nextNode != null) { - Assert.assertEquals(expectedOrder.get(i), nextNode.key()); - // Process the node - dag.reportedCompleted(nextNode); - nextNode = dag.getNext(); - i++; - } - } - - private DAGraph> createGraph(String resourceName) { - DAGNode node = new DAGNode<>(resourceName, "data" + resourceName); - DAGraph> graph = new DAGraph<>(node); - return graph; - } -} diff --git a/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/DAGraphTests.java b/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/DAGraphTests.java deleted file mode 100644 index 985fe306f0f52..0000000000000 --- a/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/DAGraphTests.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -public class DAGraphTests { - @Test - public void testDAGraphGetNext() { - /** - * |-------->[D]------>[B]-----------[A] - * | ^ ^ - * | | | - * [F]------->[E]-------| | - * | | | - * | |------->[G]----->[C]---- - * | - * |-------->[H]-------------------->[I] - */ - List expectedOrder = new ArrayList<>(); - expectedOrder.add("A"); expectedOrder.add("I"); - expectedOrder.add("B"); expectedOrder.add("C"); expectedOrder.add("H"); - expectedOrder.add("D"); expectedOrder.add("G"); - expectedOrder.add("E"); - expectedOrder.add("F"); - - DAGNode nodeA = new DAGNode<>("A", "dataA"); - DAGNode nodeI = new DAGNode<>("I", "dataI"); - - DAGNode nodeB = new DAGNode<>("B", "dataB"); - nodeB.addDependency(nodeA.key()); - - DAGNode nodeC = new DAGNode<>("C", "dataC"); - nodeC.addDependency(nodeA.key()); - - DAGNode nodeH = new DAGNode<>("H", "dataH"); - nodeH.addDependency(nodeI.key()); - - DAGNode nodeG = new DAGNode<>("G", "dataG"); - nodeG.addDependency(nodeC.key()); - - DAGNode nodeE = new DAGNode<>("E", "dataE"); - nodeE.addDependency(nodeB.key()); - nodeE.addDependency(nodeG.key()); - - DAGNode nodeD = new DAGNode<>("D", "dataD"); - nodeD.addDependency(nodeB.key()); - - - DAGNode nodeF = new DAGNode<>("F", "dataF"); - nodeF.addDependency(nodeD.key()); - nodeF.addDependency(nodeE.key()); - nodeF.addDependency(nodeH.key()); - - DAGraph> dag = new DAGraph<>(nodeF); - dag.addNode(nodeA); - dag.addNode(nodeB); - dag.addNode(nodeC); - dag.addNode(nodeD); - dag.addNode(nodeE); - dag.addNode(nodeG); - dag.addNode(nodeH); - dag.addNode(nodeI); - - dag.prepare(); - DAGNode nextNode = dag.getNext(); - int i = 0; - while (nextNode != null) { - Assert.assertEquals(nextNode.key(), expectedOrder.get(i)); - dag.reportedCompleted(nextNode); - nextNode = dag.getNext(); - i++; - } - - System.out.println("done"); - } - - @Test - public void testGraphMerge() { - /** - * |-------->[D]------>[B]-----------[A] - * | ^ ^ - * | | | - * [F]------->[E]-------| | - * | | | - * | |------->[G]----->[C]---- - * | - * |-------->[H]-------------------->[I] - */ - List expectedOrder = new ArrayList<>(); - expectedOrder.add("A"); expectedOrder.add("I"); - expectedOrder.add("B"); expectedOrder.add("C"); expectedOrder.add("H"); - expectedOrder.add("D"); expectedOrder.add("G"); - expectedOrder.add("E"); - expectedOrder.add("F"); - - DAGraph> graphA = createGraph("A"); - DAGraph> graphI = createGraph("I"); - - DAGraph> graphB = createGraph("B"); - graphA.merge(graphB); - - DAGraph> graphC = createGraph("C"); - graphA.merge(graphC); - - DAGraph> graphH = createGraph("H"); - graphI.merge(graphH); - - DAGraph> graphG = createGraph("G"); - graphC.merge(graphG); - - DAGraph> graphE = createGraph("E"); - graphB.merge(graphE); - graphG.merge(graphE); - - DAGraph> graphD = createGraph("D"); - graphB.merge(graphD); - - DAGraph> graphF = createGraph("F"); - graphD.merge(graphF); - graphE.merge(graphF); - graphH.merge(graphF); - - DAGraph> dag = graphF; - dag.prepare(); - - DAGNode nextNode = dag.getNext(); - int i = 0; - while (nextNode != null) { - Assert.assertEquals(expectedOrder.get(i), nextNode.key()); - // Process the node - dag.reportedCompleted(nextNode); - nextNode = dag.getNext(); - i++; - } - } - - private DAGraph> createGraph(String resourceName) { - DAGNode node = new DAGNode<>(resourceName, "data" + resourceName); - DAGraph> graph = new DAGraph<>(node); - return graph; - } -} diff --git a/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/PagedListTests.java b/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/PagedListTests.java deleted file mode 100644 index b82c8d0628787..0000000000000 --- a/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/PagedListTests.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class PagedListTests { - private PagedList list; - - @Before - public void setupList() { - list = new PagedList(new TestPage(0, 20)) { - @Override - public Page nextPage(String nextPageLink) throws CloudException, IOException { - int pageNum = Integer.parseInt(nextPageLink); - return new TestPage(pageNum, 20); - } - }; - } - - @Test - public void sizeTest() { - Assert.assertEquals(20, list.size()); - } - - @Test - public void getTest() { - Assert.assertEquals(15, (int) list.get(15)); - } - - @Test - public void iterateTest() { - int j = 0; - for (int i : list) { - Assert.assertEquals(i, j++); - } - } - - @Test - public void removeTest() { - Integer i = list.get(10); - list.remove(10); - Assert.assertEquals(19, list.size()); - Assert.assertEquals(19, (int) list.get(18)); - } - - @Test - public void addTest() { - Integer i = list.get(10); - list.add(100); - Assert.assertEquals(21, list.size()); - Assert.assertEquals(100, (int) list.get(11)); - Assert.assertEquals(19, (int) list.get(20)); - } - - @Test - public void containsTest() { - Assert.assertTrue(list.contains(0)); - Assert.assertTrue(list.contains(3)); - Assert.assertTrue(list.contains(19)); - Assert.assertFalse(list.contains(20)); - } - - @Test - public void containsAllTest() { - List subList = new ArrayList<>(); - subList.addAll(Arrays.asList(0, 3, 19)); - Assert.assertTrue(list.containsAll(subList)); - subList.add(20); - Assert.assertFalse(list.containsAll(subList)); - } - - @Test - public void subListTest() { - List subList = list.subList(5, 15); - Assert.assertEquals(10, subList.size()); - Assert.assertTrue(list.containsAll(subList)); - Assert.assertEquals(7, (int) subList.get(2)); - } - - @Test - public void testIndexOf() { - Assert.assertEquals(15, list.indexOf(15)); - } - - @Test - public void testLastIndexOf() { - Assert.assertEquals(15, list.lastIndexOf(15)); - } - - public static class TestPage implements Page { - private int page; - private int max; - - public TestPage(int page, int max) { - this.page = page; - this.max = max; - } - - @Override - public String getNextPageLink() { - if (page + 1 == max) { - return null; - } - return Integer.toString(page + 1); - } - - @Override - public List getItems() { - List items = new ArrayList<>(); - items.add(page); - return items; - } - } -} diff --git a/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/RequestIdHeaderInterceptorTests.java b/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/RequestIdHeaderInterceptorTests.java deleted file mode 100644 index 060336cd23d29..0000000000000 --- a/src/client/Java/azure-client-runtime/src/test/java/com/microsoft/azure/RequestIdHeaderInterceptorTests.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.azure; - -import com.microsoft.rest.retry.RetryHandler; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; - -public class RequestIdHeaderInterceptorTests { - private static final String REQUEST_ID_HEADER = "x-ms-client-request-id"; - - @Test - public void newRequestIdForEachCall() throws Exception { - RestClient restClient = new RestClient.Builder() - .withBaseUrl("http://localhost") - .withInterceptor(new RequestIdHeaderInterceptor()) - .withInterceptor(new Interceptor() { - private String firstRequestId = null; - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - if (request.header(REQUEST_ID_HEADER) != null) { - if (firstRequestId == null) { - firstRequestId = request.header(REQUEST_ID_HEADER); - return new Response.Builder().code(200).request(request) - .protocol(Protocol.HTTP_1_1).build(); - } else if (!request.header(REQUEST_ID_HEADER).equals(firstRequestId)) { - return new Response.Builder().code(200).request(request) - .protocol(Protocol.HTTP_1_1).build(); - } - } - return new Response.Builder().code(400).request(request) - .protocol(Protocol.HTTP_1_1).build(); - } - }) - .build(); - AzureServiceClient serviceClient = new AzureServiceClient(restClient) { }; - Response response = serviceClient.restClient().httpClient() - .newCall(new Request.Builder().get().url("http://localhost").build()).execute(); - Assert.assertEquals(200, response.code()); - response = serviceClient.restClient().httpClient() - .newCall(new Request.Builder().get().url("http://localhost").build()).execute(); - Assert.assertEquals(200, response.code()); - } - - @Test - public void sameRequestIdForRetry() throws Exception { - RestClient restClient = new RestClient.Builder() - .withBaseUrl("http://localhost") - .withInterceptor(new RequestIdHeaderInterceptor()) - .withInterceptor(new RetryHandler()) - .withInterceptor(new Interceptor() { - private String firstRequestId = null; - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - if (request.header(REQUEST_ID_HEADER) != null) { - if (firstRequestId == null) { - firstRequestId = request.header(REQUEST_ID_HEADER); - return new Response.Builder().code(500).request(request) - .protocol(Protocol.HTTP_1_1).build(); - } else if (request.header(REQUEST_ID_HEADER).equals(firstRequestId)) { - return new Response.Builder().code(200).request(request) - .protocol(Protocol.HTTP_1_1).build(); - } - } - return new Response.Builder().code(400).request(request) - .protocol(Protocol.HTTP_1_1).build(); - } - }) - .build(); - AzureServiceClient serviceClient = new AzureServiceClient(restClient) { }; - Response response = serviceClient.restClient().httpClient() - .newCall(new Request.Builder().get().url("http://localhost").build()).execute(); - Assert.assertEquals(200, response.code()); - } -} diff --git a/src/client/Java/build-tools/pom.xml b/src/client/Java/build-tools/pom.xml deleted file mode 100644 index d540f8f5e6980..0000000000000 --- a/src/client/Java/build-tools/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - - com.microsoft.azure - autorest-clientruntime-for-java - 1.0.0-SNAPSHOT - ../pom.xml - - - autorest-build-tools - jar - - Build tools for AutoRest client runtime for Java - This package contains the build tools for AutoRest generated Java clients. - https://github.com/Azure/autorest-clientruntime-for-java - - - - The MIT License (MIT) - http://opensource.org/licenses/MIT - repo - - - - - scm:git:https://github.com/Azure/autorest-clientruntime-for-java - scm:git:git@github.com:Azure/autorest-clientruntime-for-java.git - HEAD - - - - UTF-8 - - - - - - microsoft - Microsoft - - - diff --git a/src/client/Java/build-tools/src/main/resources/checkstyle.xml b/src/client/Java/build-tools/src/main/resources/checkstyle.xml deleted file mode 100644 index b7f934898253c..0000000000000 --- a/src/client/Java/build-tools/src/main/resources/checkstyle.xml +++ /dev/null @@ -1,254 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/client/Java/build-tools/src/main/resources/suppressions.xml b/src/client/Java/build-tools/src/main/resources/suppressions.xml deleted file mode 100644 index 29e5bd66eefb5..0000000000000 --- a/src/client/Java/build-tools/src/main/resources/suppressions.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/src/client/Java/client-runtime/build.gradle b/src/client/Java/client-runtime/build.gradle deleted file mode 100644 index e530072694672..0000000000000 --- a/src/client/Java/client-runtime/build.gradle +++ /dev/null @@ -1,107 +0,0 @@ -buildscript { - repositories { - jcenter() - } - dependencies { - classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.2' - } -} - -apply plugin: 'java' -apply plugin: 'com.github.johnrengelman.shadow' -apply plugin: 'checkstyle' - -group = 'com.microsoft.rest' -version = '1.0.0-SNAPSHOT' - -checkstyle { - toolVersion = "6.18" - configFile = new File("$rootDir/src/client/Java/build-tools/src/main/resources/checkstyle.xml") - configProperties = [samedir: "$rootDir/src/client/Java/build-tools/src/main/resources"] - reportsDir = new File("$rootDir/src/client/Java/build-tools/reports") -} - -dependencies { - compile 'com.google.guava:guava:18.0' - compile 'com.squareup.retrofit2:retrofit:2.0.2' - compile 'com.squareup.okhttp3:okhttp:3.3.1' - compile 'com.squareup.okhttp3:logging-interceptor:3.3.1' - compile 'com.squareup.okhttp3:okhttp-urlconnection:3.3.1' - compile 'com.squareup.retrofit2:converter-jackson:2.0.2' - compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.7.2' - compile 'org.apache.commons:commons-lang3:3.4' - testCompile 'junit:junit:4.12' - testCompile 'junit:junit-dep:4.11' - deployerJars "org.apache.maven.wagon:wagon-ftp:2.10" -} - -uploadArchives { - repositories { - mavenDeployer { - configuration = configurations.deployerJars - snapshotRepository(url: "ftp://waws-prod-bay-005.ftp.azurewebsites.windows.net/site/wwwroot/") { - authentication(userName: username, password: password) - } - repository(url: "file://$buildDir/repository") - pom.project { - name 'Microsoft AutoRest Runtime for Java' - description 'This is the client runtime for AutoRest generated Java clients.' - url 'https://github.com/Azure/autorest' - - scm { - url 'scm:git:https://github.com/Azure/AutoRest' - connection 'scm:git:git://github.com/Azure/AutoRest.git' - } - - licenses { - license { - name 'The MIT License (MIT)' - url 'http://opensource.org/licenses/MIT' - distribution 'repo' - } - } - - developers { - developer { - id 'microsoft' - name 'Microsoft' - } - } - } - } - } -} - -test { - testLogging { - events "passed", "skipped", "failed", "standardError" - } -} - -javadoc { - options.encoding = 'UTF-8' -} - -task sourcesJar(type: Jar, dependsOn:classes) { - classifier = 'sources' - from sourceSets.main.allSource -} - -task javadocJar(type: Jar, dependsOn: [javadoc]) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -artifacts { - archives sourcesJar - archives javadocJar -} - -test { - reports.getHtml() - reports.html.destination = file("$rootDir/TestResults/JavaRuntime") -} - -tasks.compileJava.dependsOn 'clean' - -println sourceSets.main.runtimeClasspath.asPath diff --git a/src/client/Java/client-runtime/pom.xml b/src/client/Java/client-runtime/pom.xml deleted file mode 100644 index e63a421434b38..0000000000000 --- a/src/client/Java/client-runtime/pom.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - 4.0.0 - - com.microsoft.azure - autorest-clientruntime-for-java - 1.0.0-SNAPSHOT - ../pom.xml - - - com.microsoft.rest - client-runtime - jar - - Java Client Runtime for AutoRest - This package contains the basic runtime for AutoRest generated Java clients. - https://github.com/Azure/autorest-clientruntime-for-java - - - - The MIT License (MIT) - http://opensource.org/licenses/MIT - repo - - - - - scm:git:https://github.com/Azure/autorest-clientruntime-for-java - scm:git:git@github.com:Azure/autorest-clientruntime-for-java.git - HEAD - - - - UTF-8 - - - - - - microsoft - Microsoft - - - - - - com.google.guava - guava - - - com.squareup.retrofit2 - retrofit - - - com.squareup.okhttp3 - okhttp - - - com.squareup.okhttp3 - logging-interceptor - - - com.squareup.okhttp3 - okhttp-urlconnection - - - com.squareup.retrofit2 - converter-jackson - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - - - org.apache.commons - commons-lang3 - - - junit - junit - test - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.7 - 1.7 - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage - /** -
* Copyright (c) Microsoft Corporation. All rights reserved. -
* Licensed under the MIT License. See License.txt in the project root for -
* license information. -
*/]]>
-
-
- -
-
-
diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/Base64Url.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/Base64Url.java deleted file mode 100644 index 61b02879feae1..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/Base64Url.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import com.google.common.io.BaseEncoding; - -import java.util.Arrays; - -/** - * Simple wrapper over Base64Url encoded byte array used during serialization/deserialization. - */ -public final class Base64Url { - /** - * The Base64Url encoded bytes. - */ - private final byte[] bytes; - - /** - * Creates a new Base64Url object with the specified encoded string. - * - * @param string The encoded string. - */ - private Base64Url(String string) { - if (string == null) { - this.bytes = null; - } else { - this.bytes = string.getBytes(); - } - } - - /** - * Encode a byte array into Base64Url encoded bytes. - * - * @param bytes The byte array to encode. - * @return a Base64Url instance - */ - public static Base64Url encode(byte[] bytes) { - if (bytes == null) { - return new Base64Url(null); - } else { - return new Base64Url(BaseEncoding.base64Url().omitPadding().encode(bytes)); - } - } - - /** - * Returns the underlying encoded byte array. - * - * @return The underlying encoded byte array. - */ - public byte[] getEncodedBytes() { - return bytes; - } - - /** - * Decode the bytes and return. - * - * @return The decoded byte array. - */ - public byte[] getDecodedBytes() { - if (this.bytes == null) { - return null; - } - return BaseEncoding.base64Url().decode(new String(bytes)); - } - - @Override - public String toString() { - return new String(bytes); - } - - @Override - public int hashCode() { - return Arrays.hashCode(bytes); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (!(obj instanceof Base64Url)) { - return false; - } - - Base64Url rhs = (Base64Url) obj; - return Arrays.equals(this.bytes, rhs.getEncodedBytes()); - } -} \ No newline at end of file diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/BaseUrlHandler.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/BaseUrlHandler.java deleted file mode 100644 index 46eacbd472e23..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/BaseUrlHandler.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import java.io.IOException; - -import okhttp3.HttpUrl; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -/** - * Handles dynamic replacements on base URL. The arguments must be in pairs - * with the string in raw URL to replace as replacements[i] and the dynamic - * part as replacements[i+1]. E.g. {subdomain}.microsoft.com can be set - * dynamically by setting header x-ms-parameterized-host: "{subdomain}, azure" - */ -public class BaseUrlHandler implements Interceptor { - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - String parameters = request.header("x-ms-parameterized-host"); - if (parameters != null && !parameters.isEmpty()) { - String[] replacements = parameters.split(", "); - if (replacements.length % 2 != 0) { - throw new IllegalArgumentException("Must provide a replacement value for each pattern"); - } - String baseUrl = request.url().toString(); - for (int i = 0; i < replacements.length; i += 2) { - baseUrl = baseUrl.replaceAll("(?i)\\Q" + replacements[i] + "\\E", replacements[i + 1]); - } - HttpUrl baseHttpUrl = HttpUrl.parse(baseUrl); - request = request.newBuilder() - .url(baseHttpUrl) - .removeHeader("x-ms-parameterized-host") - .build(); - } - return chain.proceed(request); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/CustomHeadersInterceptor.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/CustomHeadersInterceptor.java deleted file mode 100644 index 00903b93a9e01..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/CustomHeadersInterceptor.java +++ /dev/null @@ -1,136 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import okhttp3.Headers; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * An instance of this class enables adding custom headers in client requests - * when added to the {@link okhttp3.OkHttpClient} interceptors. - */ -public class CustomHeadersInterceptor implements Interceptor { - /** - * A mapping of custom headers. - */ - private Map> headers; - - /** - * Initialize an instance of {@link CustomHeadersInterceptor} class. - */ - public CustomHeadersInterceptor() { - headers = new HashMap>(); - } - - /** - * Initialize an instance of {@link CustomHeadersInterceptor} class. - * - * @param key the key for the header - * @param value the value of the header - */ - public CustomHeadersInterceptor(String key, String value) { - this(); - addHeader(key, value); - } - - /** - * Add a single header key-value pair. If one with the name already exists, - * it gets replaced. - * - * @param name the name of the header. - * @param value the value of the header. - * @return the interceptor instance itself. - */ - public CustomHeadersInterceptor replaceHeader(String name, String value) { - this.headers.put(name, new ArrayList()); - this.headers.get(name).add(value); - return this; - } - - /** - * Add a single header key-value pair. If one with the name already exists, - * both stay in the header map. - * - * @param name the name of the header. - * @param value the value of the header. - * @return the interceptor instance itself. - */ - public CustomHeadersInterceptor addHeader(String name, String value) { - if (!this.headers.containsKey(name)) { - this.headers.put(name, new ArrayList()); - } - this.headers.get(name).add(value); - return this; - } - - /** - * Add all headers in a {@link Headers} object. - * - * @param headers an OkHttp {@link Headers} object. - * @return the interceptor instance itself. - */ - public CustomHeadersInterceptor addHeaders(Headers headers) { - this.headers.putAll(headers.toMultimap()); - return this; - } - - /** - * Add all headers in a header map. - * - * @param headers a map of headers. - * @return the interceptor instance itself. - */ - public CustomHeadersInterceptor addHeaderMap(Map headers) { - for (Map.Entry header : headers.entrySet()) { - this.headers.put(header.getKey(), Collections.singletonList(header.getValue())); - } - return this; - } - - /** - * Add all headers in a header multimap. - * - * @param headers a multimap of headers. - * @return the interceptor instance itself. - */ - public CustomHeadersInterceptor addHeaderMultimap(Map> headers) { - this.headers.putAll(headers); - return this; - } - - /** - * Remove a header. - * - * @param name the name of the header to remove. - * @return the interceptor instance itself. - */ - public CustomHeadersInterceptor removeHeader(String name) { - this.headers.remove(name); - return this; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request.Builder builder = chain.request().newBuilder(); - for (Map.Entry> header : headers.entrySet()) { - for (String value : header.getValue()) { - builder = builder.header(header.getKey(), value); - } - } - return chain.proceed(builder.build()); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/DateTimeRfc1123.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/DateTimeRfc1123.java deleted file mode 100644 index d4e8078cb7173..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/DateTimeRfc1123.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import java.util.Locale; - -/** - * Simple wrapper over joda.time.DateTime used for specifying RFC1123 format during serialization/deserialization. - */ -public class DateTimeRfc1123 { - /** - * The pattern of the datetime used for RFC1123 datetime format. - */ - private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = - DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC().withLocale(Locale.US); - - /** - * The actual datetime object. - */ - private final DateTime dateTime; - - /** - * Creates a new DateTimeRfc1123 object with the specified DateTime. - * @param dateTime The DateTime object to wrap. - */ - public DateTimeRfc1123(DateTime dateTime) { - this.dateTime = dateTime; - } - - /** - * Creates a new DateTimeRfc1123 object with the specified DateTime. - * @param formattedString The datetime string in RFC1123 format - */ - public DateTimeRfc1123(String formattedString) { - this.dateTime = DateTime.parse(formattedString, RFC1123_DATE_TIME_FORMATTER); - } - - /** - * Returns the underlying DateTime. - * @return The underlying DateTime. - */ - public DateTime getDateTime() { - if (this.dateTime == null) { - return null; - } - return this.dateTime; - } - - @Override - public String toString() { - return RFC1123_DATE_TIME_FORMATTER.print(this.dateTime); - } - - @Override - public int hashCode() { - return this.dateTime.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (!(obj instanceof DateTimeRfc1123)) { - return false; - } - - DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; - return this.dateTime.equals(rhs.getDateTime()); - } -} \ No newline at end of file diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/RestException.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/RestException.java deleted file mode 100644 index cf5dff556aea0..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/RestException.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -/** - * Exception thrown for an invalid response with custom error information. - */ -public abstract class RestException extends Exception { - /** - * Initializes a new instance of the AutoRestException class. - */ - public RestException() { } - - /** - * Initializes a new instance of the AutoRestException class. - * - * @param message The exception message. - */ - public RestException(String message) { - super(message); - } - - /** - * Initializes a new instance of the AutoRestException class. - * - * @param cause exception that caused this exception to occur - */ - public RestException(Throwable cause) { - super(cause); - } - - /** - * Initializes a new instance of the AutoRestException class. - * - * @param message the exception message - * @param cause exception that caused this exception to occur - */ - public RestException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceCall.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceCall.java deleted file mode 100644 index dcffd781c7c59..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceCall.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import retrofit2.Call; - -/** - * An instance of this class provides access to the underlying REST call invocation. - * This class wraps around the Retrofit Call object and allows updates to it in the - * progress of a long running operation or a paging operation. - */ -public class ServiceCall { - /** - * The Retrofit method invocation. - */ - private Call call; - - /** - * Creates an instance of ServiceCall. - * - * @param call the Retrofit call to wrap around. - */ - public ServiceCall(Call call) { - this.call = call; - } - - /** - * Updates the current Retrofit call object. - * - * @param call the new call object. - */ - public void newCall(Call call) { - this.call = call; - } - - /** - * Gets the current Retrofit call object. - * - * @return the current call object. - */ - public Call getCall() { - return call; - } - - /** - * Cancel the Retrofit call if possible. - */ - public void cancel() { - call.cancel(); - } - - /** - * If the Retrofit call has been canceled. - * - * @return true if the call has been canceled; false otherwise. - */ - public boolean isCanceled() { - return call.isCanceled(); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceCallback.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceCallback.java deleted file mode 100644 index dd3791bbb2d19..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceCallback.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -/** - * The callback used for client side asynchronous operations. - * - * @param the type of the response - */ -public abstract class ServiceCallback { - /** - * Override this method to handle REST call failures. - * - * @param t the exception thrown from the pipeline. - */ - public abstract void failure(Throwable t); - - /** - * Override this method to handle successful REST call results. - * - * @param result the ServiceResponse holding the response. - */ - public abstract void success(ServiceResponse result); -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceClient.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceClient.java deleted file mode 100644 index 5d6f0f850336c..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceClient.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import com.microsoft.rest.retry.RetryHandler; -import com.microsoft.rest.serializer.JacksonMapperAdapter; - -import java.net.CookieManager; -import java.net.CookiePolicy; - -import okhttp3.JavaNetCookieJar; -import okhttp3.OkHttpClient; -import retrofit2.Retrofit; - -/** - * ServiceClient is the abstraction for accessing REST operations and their payload data types. - */ -public abstract class ServiceClient { - /** The HTTP client. */ - private OkHttpClient httpClient; - /** The Retrofit instance. */ - private Retrofit retrofit; - /** The adapter to a Jackson {@link com.fasterxml.jackson.databind.ObjectMapper}. */ - private JacksonMapperAdapter mapperAdapter; - - /** - * Initializes a new instance of the ServiceClient class. - * - * @param baseUrl the service endpoint - */ - protected ServiceClient(String baseUrl) { - this(baseUrl, new OkHttpClient.Builder(), new Retrofit.Builder()); - } - - /** - * Initializes a new instance of the ServiceClient class. - * - * @param baseUrl the service base uri - * @param clientBuilder the http client builder - * @param restBuilder the retrofit rest client builder - */ - protected ServiceClient(String baseUrl, OkHttpClient.Builder clientBuilder, Retrofit.Builder restBuilder) { - if (clientBuilder == null) { - throw new IllegalArgumentException("clientBuilder == null"); - } - if (restBuilder == null) { - throw new IllegalArgumentException("restBuilder == null"); - } - this.mapperAdapter = new JacksonMapperAdapter(); - CookieManager cookieManager = new CookieManager(); - cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); - this.httpClient = clientBuilder - .cookieJar(new JavaNetCookieJar(cookieManager)) - .addInterceptor(new UserAgentInterceptor()) - .addInterceptor(new BaseUrlHandler()) - .addInterceptor(new CustomHeadersInterceptor()) - .addInterceptor(new RetryHandler()) - .build(); - this.retrofit = restBuilder - .baseUrl(baseUrl) - .client(httpClient) - .addConverterFactory(mapperAdapter.getConverterFactory()) - .build(); - } - - /** - * @return the Retrofit instance. - */ - public Retrofit retrofit() { - return this.retrofit; - } - - /** - * @return the HTTP client. - */ - public OkHttpClient httpClient() { - return this.httpClient; - } - - /** - * @return the adapter to a Jackson {@link com.fasterxml.jackson.databind.ObjectMapper}. - */ - public JacksonMapperAdapter mapperAdapter() { - return this.mapperAdapter; - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceException.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceException.java deleted file mode 100644 index c041ae3bda3ab..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceException.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import retrofit2.Response; - -/** - * Exception thrown for an invalid response with custom error information. - */ -public class ServiceException extends RestException { - /** - * Information about the associated HTTP response. - */ - private Response response; - - /** - * The HTTP response body. - */ - private Object body; - - /** - * Initializes a new instance of the ServiceException class. - */ - public ServiceException() { } - - /** - * Initializes a new instance of the ServiceException class. - * - * @param message The exception message. - */ - public ServiceException(final String message) { - super(message); - } - - /** - * Initializes a new instance of the ServiceException class. - * - * @param message the exception message - * @param cause exception that caused this exception to occur - */ - public ServiceException(final String message, final Throwable cause) { - super(message, cause); - } - - /** - * Initializes a new instance of the ServiceException class. - * - * @param cause exception that caused this exception to occur - */ - public ServiceException(final Throwable cause) { - super(cause); - } - - /** - * Gets information about the associated HTTP response. - * - * @return the HTTP response - */ - public Response getResponse() { - return response; - } - - /** - * Gets the HTTP response body. - * - * @return the response body - */ - public Object getBody() { - return body; - } - - /** - * Sets the HTTP response. - * - * @param response the HTTP response - */ - public void setResponse(Response response) { - this.response = response; - } - - /** - * Sets the HTTP response body. - * - * @param body the response object - */ - public void setBody(Object body) { - this.body = body; - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponse.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponse.java deleted file mode 100644 index a116349a694dc..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponse.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import okhttp3.ResponseBody; -import retrofit2.Response; - -/** - * An instance of this class holds a response object and a raw REST response. - * - * @param the type of the response - */ -public class ServiceResponse { - /** - * The response body object. - */ - private T body; - - /** - * The retrofit response wrapper containing information about the REST response. - */ - private Response response; - - /** - * The retrofit response wrapper if it's returned from a HEAD operation. - */ - private Response headResponse; - - /** - * Instantiate a ServiceResponse instance with a response object and a raw REST response. - * - * @param body deserialized response object - * @param response raw REST response - */ - public ServiceResponse(T body, Response response) { - this.body = body; - this.response = response; - } - - /** - * Instantiate a ServiceResponse instance with a response from a HEAD operation. - * - * @param headResponse raw REST response from a HEAD operation - */ - public ServiceResponse(Response headResponse) { - this.headResponse = headResponse; - } - - /** - * Gets the response object. - * @return the response object. Null if there isn't one. - */ - public T getBody() { - return this.body; - } - - /** - * Sets the response object. - * - * @param body the response object. - */ - public void setBody(T body) { - this.body = body; - } - - /** - * Gets the raw REST response. - * - * @return the raw REST response. - */ - public Response getResponse() { - return response; - } - - /** - * Gets the raw REST response from a HEAD operation. - * - * @return the raw REST response from a HEAD operation. - */ - public Response getHeadResponse() { - return headResponse; - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java deleted file mode 100644 index 3ad57cb938f40..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java +++ /dev/null @@ -1,289 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.microsoft.rest.serializer.JacksonMapperAdapter; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import okhttp3.ResponseBody; -import retrofit2.Response; - -/** - * The builder for building a {@link ServiceResponse}. - * - * @param The return type the caller expects from the REST response. - * @param the exception to throw in case of error. - */ -public class ServiceResponseBuilder { - /** - * A mapping of HTTP status codes and their corresponding return types. - */ - protected Map responseTypes; - - /** - * The exception type to thrown in case of error. - */ - protected Class exceptionType; - - /** - * The mapperAdapter used for deserializing the response. - */ - protected JacksonMapperAdapter mapperAdapter; - - /** - * Create a ServiceResponseBuilder instance. - * - * @param mapperAdapter the serialization utils to use for deserialization operations - */ - public ServiceResponseBuilder(JacksonMapperAdapter mapperAdapter) { - this(mapperAdapter, new HashMap()); - } - - /** - * Create a ServiceResponseBuilder instance. - * - * @param mapperAdapter the serialization utils to use for deserialization operations - * @param responseTypes a mapping of response status codes and response destination types - */ - public ServiceResponseBuilder(JacksonMapperAdapter mapperAdapter, Map responseTypes) { - this.mapperAdapter = mapperAdapter; - this.responseTypes = responseTypes; - this.exceptionType = ServiceException.class; - this.responseTypes.put(0, Object.class); - } - - /** - * Register a mapping from a response status code to a response destination type. - * - * @param statusCode the status code. - * @param type the type to deserialize. - * @return the same builder instance. - */ - public ServiceResponseBuilder register(int statusCode, final Type type) { - this.responseTypes.put(statusCode, type); - return this; - } - - /** - * Register a destination type for errors with models. - * - * @param type the type to deserialize. - * @return the same builder instance. - */ - public ServiceResponseBuilder registerError(final Class type) { - this.exceptionType = type; - try { - Field f = type.getDeclaredField("body"); - this.responseTypes.put(0, f.getType()); - } catch (NoSuchFieldException e) { - // AutoRestException always has a body. Register Object as a fallback plan. - this.responseTypes.put(0, Object.class); - } - return this; - } - - /** - * Register all the mappings from a response status code to a response - * destination type stored in a {@link Map}. - * - * @param responseTypes the mapping from response status codes to response types. - * @return the same builder instance. - */ - public ServiceResponseBuilder registerAll(Map responseTypes) { - this.responseTypes.putAll(responseTypes); - return this; - } - - /** - * Build a ServiceResponse instance from a REST call response and a - * possible error. - * - *

- * If the status code in the response is registered, the response will - * be considered valid and deserialized into the specified destination - * type. If the status code is not registered, the response will be - * considered invalid and deserialized into the specified error type if - * there is one. An AutoRestException is also thrown. - *

- * - * @param response the {@link Response} instance from REST call - * @return a ServiceResponse instance of generic type {@link T} - * @throws E exceptions from the REST call - * @throws IOException exceptions from deserialization - */ - @SuppressWarnings("unchecked") - public ServiceResponse build(Response response) throws E, IOException { - if (response == null) { - return null; - } - - int statusCode = response.code(); - ResponseBody responseBody; - if (response.isSuccessful()) { - responseBody = response.body(); - } else { - responseBody = response.errorBody(); - } - - if (responseTypes.containsKey(statusCode)) { - return new ServiceResponse<>((T) buildBody(statusCode, responseBody), response); - } else if (response.isSuccessful() && responseTypes.size() == 1) { - return new ServiceResponse<>((T) buildBody(statusCode, responseBody), response); - } else { - try { - E exception = (E) exceptionType.getConstructor(String.class).newInstance("Invalid status code " + statusCode); - exceptionType.getMethod("setResponse", response.getClass()).invoke(exception, response); - exceptionType.getMethod("setBody", (Class) responseTypes.get(0)).invoke(exception, buildBody(statusCode, responseBody)); - throw exception; - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new IOException("Invalid status code " + statusCode + ", but an instance of " + exceptionType.getCanonicalName() - + " cannot be created.", e); - } - } - } - - /** - * Build a ServiceResponse instance from a REST call response and a - * possible error, which does not have a response body. - * - *

- * If the status code in the response is registered, the response will - * be considered valid. If the status code is not registered, the - * response will be considered invalid. An AutoRestException is also thrown. - *

- * - * @param response the {@link Response} instance from REST call - * @return a ServiceResponse instance of generic type {@link T} - * @throws E exceptions from the REST call - * @throws IOException exceptions from deserialization - */ - @SuppressWarnings("unchecked") - public ServiceResponse buildEmpty(Response response) throws E, IOException { - int statusCode = response.code(); - if (responseTypes.containsKey(statusCode)) { - return new ServiceResponse<>(response); - } else if (response.isSuccessful() && responseTypes.size() == 1) { - return new ServiceResponse<>(response); - } else { - try { - E exception = (E) exceptionType.getConstructor(String.class).newInstance("Invalid status code " + statusCode); - exceptionType.getMethod("setResponse", response.getClass()).invoke(exception, response); - response.errorBody().close(); - throw exception; - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new IOException("Invalid status code " + statusCode + ", but an instance of " + exceptionType.getCanonicalName() - + " cannot be created.", e); - } - } - } - - /** - * Build a ServiceResponseWithHeaders instance from a REST call response, a header - * in JSON format, and a possible error. - * - *

- * If the status code in the response is registered, the response will - * be considered valid and deserialized into the specified destination - * type. If the status code is not registered, the response will be - * considered invalid and deserialized into the specified error type if - * there is one. An AutoRestException is also thrown. - *

- * - * @param response the {@link Response} instance from REST call - * @param headerType the type of the header - * @param the type of the header - * @return a ServiceResponseWithHeaders instance of generic type {@link T} - * @throws E exceptions from the REST call - * @throws IOException exceptions from deserialization - */ - public ServiceResponseWithHeaders buildWithHeaders(Response response, Class headerType) throws E, IOException { - ServiceResponse bodyResponse = build(response); - THeader headers = mapperAdapter.deserialize( - mapperAdapter.serialize(response.headers()), - headerType); - return new ServiceResponseWithHeaders<>(bodyResponse.getBody(), headers, bodyResponse.getResponse()); - } - - /** - * Build a ServiceResponseWithHeaders instance from a REST call response, a header - * in JSON format, and a possible error, which does not have a response body. - * - *

- * If the status code in the response is registered, the response will - * be considered valid. If the status code is not registered, the - * response will be considered invalid. An AutoRestException is also thrown. - *

- * - * @param response the {@link Response} instance from REST call - * @param headerType the type of the header - * @param the type of the header - * @return a ServiceResponseWithHeaders instance of generic type {@link T} - * @throws E exceptions from the REST call - * @throws IOException exceptions from deserialization - */ - public ServiceResponseWithHeaders buildEmptyWithHeaders(Response response, Class headerType) throws E, IOException { - ServiceResponse bodyResponse = buildEmpty(response); - THeader headers = mapperAdapter.deserialize( - mapperAdapter.serialize(response.headers()), - headerType); - ServiceResponseWithHeaders serviceResponse = new ServiceResponseWithHeaders<>(headers, bodyResponse.getHeadResponse()); - serviceResponse.setBody(bodyResponse.getBody()); - return serviceResponse; - } - - /** - * Builds the body object from the HTTP status code and returned response - * body undeserialized and wrapped in {@link ResponseBody}. - * - * @param statusCode the HTTP status code - * @param responseBody the response body - * @return the response body, deserialized - * @throws IOException thrown for any deserialization errors - */ - protected Object buildBody(int statusCode, ResponseBody responseBody) throws IOException { - if (responseBody == null) { - return null; - } - - Type type; - if (responseTypes.containsKey(statusCode)) { - type = responseTypes.get(statusCode); - } else if (responseTypes.get(0) != Object.class) { - type = responseTypes.get(0); - } else { - type = new TypeReference() { }.getType(); - } - - // Void response - if (type == Void.class) { - return null; - } - // Return raw response if InputStream is the target type - else if (type == InputStream.class) { - InputStream stream = responseBody.byteStream(); - return stream; - } - // Deserialize - else { - String responseContent = responseBody.string(); - responseBody.close(); - if (responseContent.length() <= 0) { - return null; - } - return mapperAdapter.deserialize(responseContent, type); - } - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseCallback.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseCallback.java deleted file mode 100644 index 8808bfac9639c..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseCallback.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import okhttp3.ResponseBody; -import retrofit2.Call; -import retrofit2.Callback; - -/** - * Inner callback used to merge both successful and failed responses into one - * callback for customized response handling in a response handling delegate. - * - * @param the response body type - */ -public abstract class ServiceResponseCallback implements Callback { - /** - * The client callback. - */ - private ServiceCallback serviceCallback; - - /** - * Creates an instance of ServiceResponseCallback. - * - * @param serviceCallback the client callback to call on a terminal state. - */ - public ServiceResponseCallback(ServiceCallback serviceCallback) { - this.serviceCallback = serviceCallback; - } - - @Override - public void onFailure(Call call, Throwable t) { - serviceCallback.failure(new ServiceException(t)); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseEmptyCallback.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseEmptyCallback.java deleted file mode 100644 index fe848128c57df..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseEmptyCallback.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import retrofit2.Call; -import retrofit2.Callback; - -/** - * Inner callback used to merge both successful and failed responses into one - * callback for customized response handling in a response handling delegate. - * - * @param the response body type - */ -public abstract class ServiceResponseEmptyCallback implements Callback { - /** - * The client callback. - */ - private ServiceCallback serviceCallback; - - /** - * Creates an instance of ServiceResponseCallback. - * - * @param serviceCallback the client callback to call on a terminal state. - */ - public ServiceResponseEmptyCallback(ServiceCallback serviceCallback) { - this.serviceCallback = serviceCallback; - } - - @Override - public void onFailure(Call call, Throwable t) { - serviceCallback.failure(new ServiceException(t)); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseWithHeaders.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseWithHeaders.java deleted file mode 100644 index a09d119599bf5..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseWithHeaders.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import okhttp3.ResponseBody; -import retrofit2.Response; - -/** - * An instance of this class holds a response object and a raw REST response. - * - * @param the type of the response - * @param the type of the response header object - */ -public class ServiceResponseWithHeaders extends ServiceResponse { - /** - * The response header headers. - */ - private THeader headers; - - /** - * Instantiate a ServiceResponse instance with a response object and a raw REST response. - * - * @param body deserialized response object - * @param headers deserialized response header object - * @param response raw REST response - */ - public ServiceResponseWithHeaders(TBody body, THeader headers, Response response) { - super(body, response); - this.headers = headers; - } - - /** - * Instantiate a ServiceResponse instance with a response object and a raw REST response. - * - * @param headers deserialized response header object - * @param response raw REST response - */ - public ServiceResponseWithHeaders(THeader headers, Response response) { - super(response); - this.headers = headers; - } - - /** - * Gets the response headers. - * @return the response headers. Null if there isn't one. - */ - public THeader getHeaders() { - return this.headers; - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/UserAgentInterceptor.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/UserAgentInterceptor.java deleted file mode 100644 index 7b822078d79ab..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/UserAgentInterceptor.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -import java.io.IOException; - -/** - * User agent interceptor for putting a 'User-Agent' header in the request. - */ -public class UserAgentInterceptor implements Interceptor { - /** - * The default user agent header. - */ - private static final String DEFAULT_USER_AGENT_HEADER = "AutoRest-Java"; - - /** - * The user agent header string. - */ - private String userAgent; - - /** - * Initialize an instance of {@link UserAgentInterceptor} class with the default - * 'User-Agent' header. - */ - public UserAgentInterceptor() { - this.userAgent = DEFAULT_USER_AGENT_HEADER; - } - - /** - * Overwrite the User-Agent header. - * - * @param userAgent the new user agent value. - * @return the user agent interceptor itself - */ - public UserAgentInterceptor withUserAgent(String userAgent) { - this.userAgent = userAgent; - return this; - } - - /** - * Append a text to the User-Agent header. - * - * @param userAgent the user agent value to append. - * @return the user agent interceptor itself - */ - public UserAgentInterceptor appendUserAgent(String userAgent) { - this.userAgent += " " + userAgent; - return this; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - String header = request.header("User-Agent"); - if (header == null) { - header = DEFAULT_USER_AGENT_HEADER; - } - if (!userAgent.equals(DEFAULT_USER_AGENT_HEADER)) { - if (header.equals(DEFAULT_USER_AGENT_HEADER)) { - header = userAgent; - } else { - header = userAgent + " " + header; - } - } - request = chain.request().newBuilder() - .header("User-Agent", header) - .build(); - return chain.proceed(request); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/Validator.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/Validator.java deleted file mode 100644 index 51c24722404af..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/Validator.java +++ /dev/null @@ -1,124 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.primitives.Primitives; -import com.google.common.reflect.TypeToken; - -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.Period; - -import java.lang.reflect.Field; -import java.util.List; -import java.util.Map; - -/** - * Validates user provided parameters are not null if they are required. - */ -public final class Validator { - /** - * Hidden constructor for utility class. - */ - private Validator() { } - - /** - * Validates a user provided required parameter to be not null. - * An {@link IllegalArgumentException} is thrown if a property fails the validation. - * - * @param parameter the parameter to validate - * @throws IllegalArgumentException thrown when the Validator determines the argument is invalid - */ - public static void validate(Object parameter) throws IllegalArgumentException { - // Validation of top level payload is done outside - if (parameter == null) { - return; - } - - Class parameterType = parameter.getClass(); - TypeToken parameterToken = TypeToken.of(parameterType); - if (Primitives.isWrapperType(parameterType)) { - parameterToken = parameterToken.unwrap(); - } - if (parameterToken.isPrimitive() - || parameterType.isEnum() - || parameterToken.isAssignableFrom(LocalDate.class) - || parameterToken.isAssignableFrom(DateTime.class) - || parameterToken.isAssignableFrom(String.class) - || parameterToken.isAssignableFrom(DateTimeRfc1123.class) - || parameterToken.isAssignableFrom(Period.class)) { - return; - } - - for (Class c : parameterToken.getTypes().classes().rawTypes()) { - // Ignore checks for Object type. - if (c.isAssignableFrom(Object.class)) { - continue; - } - for (Field field : c.getDeclaredFields()) { - field.setAccessible(true); - JsonProperty annotation = field.getAnnotation(JsonProperty.class); - Object property; - try { - property = field.get(parameter); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e.getMessage(), e); - } - if (property == null) { - if (annotation != null && annotation.required()) { - throw new IllegalArgumentException(field.getName() + " is required and cannot be null."); - } - } else { - try { - Class propertyType = property.getClass(); - if (TypeToken.of(List.class).isAssignableFrom(propertyType)) { - List items = (List) property; - for (Object item : items) { - Validator.validate(item); - } - } - else if (TypeToken.of(Map.class).isAssignableFrom(propertyType)) { - Map entries = (Map) property; - for (Map.Entry entry : entries.entrySet()) { - Validator.validate(entry.getKey()); - Validator.validate(entry.getValue()); - } - } - else if (parameterType != propertyType) { - Validator.validate(property); - } - } catch (IllegalArgumentException ex) { - if (ex.getCause() == null) { - // Build property chain - throw new IllegalArgumentException(field.getName() + "." + ex.getMessage()); - } else { - throw ex; - } - } - } - } - } - } - - /** - * Validates a user provided required parameter to be not null. Returns if - * the parameter passes the validation. An {@link IllegalArgumentException} is passed - * to the {@link ServiceCallback#failure(Throwable)} if a property fails the validation. - * - * @param parameter the parameter to validate - * @param serviceCallback the callback to call with the failure - */ - public static void validate(Object parameter, ServiceCallback serviceCallback) { - try { - validate(parameter); - } catch (IllegalArgumentException ex) { - serviceCallback.failure(ex); - } - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/BasicAuthenticationCredentials.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/BasicAuthenticationCredentials.java deleted file mode 100644 index c63133e12809c..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/BasicAuthenticationCredentials.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.credentials; - -import okhttp3.OkHttpClient; - -/** - * Basic Auth credentials for use with a REST Service Client. - */ -public class BasicAuthenticationCredentials implements ServiceClientCredentials { - - /** - * Basic auth UserName. - */ - private String userName; - - /** - * Basic auth password. - */ - private String password; - - /** - * Instantiates a new basic authentication credential. - * - * @param userName basic auth user name - * @param password basic auth password - */ - public BasicAuthenticationCredentials(String userName, String password) { - this.userName = userName; - this.password = password; - } - - /** - * Get the user name of the credential. - * - * @return the user name - */ - public String getUserName() { - return userName; - } - - /** - * Get the password of the credential. - * - * @return the password - */ - public String getPassword() { - return password; - } - - @Override - public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) { - clientBuilder.interceptors().add(new BasicAuthenticationCredentialsInterceptor(this)); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/BasicAuthenticationCredentialsInterceptor.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/BasicAuthenticationCredentialsInterceptor.java deleted file mode 100644 index 4d35226e17cf3..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/BasicAuthenticationCredentialsInterceptor.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.credentials; - -import com.google.common.io.BaseEncoding; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -import java.io.IOException; - -/** - * Basic Auth credentials interceptor for placing a basic auth credential into request headers. - */ -public class BasicAuthenticationCredentialsInterceptor implements Interceptor { - /** - * The credentials instance to apply to the HTTP client pipeline. - */ - private BasicAuthenticationCredentials credentials; - - /** - * Initialize a BasicAuthenticationCredentialsFilter class with a - * BasicAuthenticationCredentials credential. - * - * @param credentials a BasicAuthenticationCredentials instance - */ - public BasicAuthenticationCredentialsInterceptor(BasicAuthenticationCredentials credentials) { - this.credentials = credentials; - } - - @Override - public Response intercept(Chain chain) throws IOException { - String auth = credentials.getUserName() + ":" + credentials.getPassword(); - auth = BaseEncoding.base64().encode(auth.getBytes("UTF8")); - Request newRequest = chain.request().newBuilder() - .header("Authorization", "Basic " + auth) - .build(); - return chain.proceed(newRequest); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/ServiceClientCredentials.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/ServiceClientCredentials.java deleted file mode 100644 index 89d15a9d750ac..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/ServiceClientCredentials.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.credentials; - -import okhttp3.OkHttpClient; - -/** - * ServiceClientCredentials is the abstraction for credentials used by - * ServiceClients accessing REST services. - */ -public interface ServiceClientCredentials { - /** - * Apply the credentials to the HTTP client builder. - * - * @param clientBuilder the builder for building up an {@link OkHttpClient} - */ - void applyCredentialsFilter(OkHttpClient.Builder clientBuilder); -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/TokenCredentials.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/TokenCredentials.java deleted file mode 100644 index a82c43e15011e..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/TokenCredentials.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.credentials; - -import okhttp3.OkHttpClient; - -import java.io.IOException; - -/** - * Token based credentials for use with a REST Service Client. - */ -public class TokenCredentials implements ServiceClientCredentials { - /** The authentication scheme. */ - protected String scheme; - - /** The secure token. */ - protected String token; - - /** - * Initializes a new instance of the TokenCredentials. - * - * @param scheme scheme to use. If null, defaults to Bearer - * @param token valid token - */ - public TokenCredentials(String scheme, String token) { - if (scheme == null) { - scheme = "Bearer"; - } - this.scheme = scheme; - this.token = token; - } - - /** - * Get the secure token. - * - * @return the secure token. - * @throws IOException exception thrown from token acquisition operations. - */ - public String getToken() throws IOException { - return token; - } - - /** - * Refresh the secure token. - * @throws IOException exception thrown from token acquisition operations. - */ - public void refreshToken() throws IOException { - // do nothing - } - - /** - * Set the secure token. - * - * @param token the token string - */ - public void setToken(String token) { - this.token = token; - } - - /** - * Get the authentication scheme. - * - * @return the authentication scheme - */ - public String getScheme() { - return scheme; - } - - @Override - public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) { - clientBuilder.interceptors().add(new TokenCredentialsInterceptor(this)); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/TokenCredentialsInterceptor.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/TokenCredentialsInterceptor.java deleted file mode 100644 index 2054c5a6e258d..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/TokenCredentialsInterceptor.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.credentials; - -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -import java.io.IOException; - -/** - * Token credentials filter for placing a token credential into request headers. - */ -public class TokenCredentialsInterceptor implements Interceptor { - /** - * The credentials instance to apply to the HTTP client pipeline. - */ - private TokenCredentials credentials; - - /** - * Initialize a TokenCredentialsFilter class with a - * TokenCredentials credential. - * - * @param credentials a TokenCredentials instance - */ - public TokenCredentialsInterceptor(TokenCredentials credentials) { - this.credentials = credentials; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Response response = sendRequestWithAuthorization(chain); - if (response == null || response.code() == 401) { - credentials.refreshToken(); - response = sendRequestWithAuthorization(chain); - } - return response; - } - - private Response sendRequestWithAuthorization(Chain chain) throws IOException { - Request newRequest = chain.request().newBuilder() - .header("Authorization", credentials.getScheme() + " " + credentials.getToken()) - .build(); - return chain.proceed(newRequest); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/package-info.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/package-info.java deleted file mode 100644 index d5a2aec9cce02..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/credentials/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * The package provides 2 basic credential classes that work with AutoRest - * generated clients for authentication purposes. - */ -package com.microsoft.rest.credentials; \ No newline at end of file diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/package-info.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/package-info.java deleted file mode 100644 index 9229a121aea2d..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * The package contains the runtime classes required for AutoRest generated - * clients to compile and function. To learn more about AutoRest generator, - * see https://github.com/azure/autorest. - */ -package com.microsoft.rest; \ No newline at end of file diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/ExponentialBackoffRetryStrategy.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/ExponentialBackoffRetryStrategy.java deleted file mode 100644 index 1af917a4eb05d..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/ExponentialBackoffRetryStrategy.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.retry; - -import okhttp3.Response; - -/** - * A retry strategy with backoff parameters for calculating the exponential delay between retries. - */ -public class ExponentialBackoffRetryStrategy extends RetryStrategy { - /** - * Represents the default amount of time used when calculating a random delta in the exponential - * delay between retries. - */ - public static final int DEFAULT_CLIENT_BACKOFF = 1000 * 10; - /** - * Represents the default maximum amount of time used when calculating the exponential - * delay between retries. - */ - public static final int DEFAULT_MAX_BACKOFF = 1000 * 30; - /** - *Represents the default minimum amount of time used when calculating the exponential - * delay between retries. - */ - public static final int DEFAULT_MIN_BACKOFF = 1000; - - /** - * The value that will be used to calculate a random delta in the exponential delay - * between retries. - */ - private final int deltaBackoff; - /** - * The maximum backoff time. - */ - private final int maxBackoff; - /** - * The minimum backoff time. - */ - private final int minBackoff; - /** - * The maximum number of retry attempts. - */ - private final int retryCount; - - /** - * Initializes a new instance of the {@link ExponentialBackoffRetryStrategy} class. - */ - public ExponentialBackoffRetryStrategy() { - this(DEFAULT_CLIENT_RETRY_COUNT, DEFAULT_MIN_BACKOFF, DEFAULT_MAX_BACKOFF, DEFAULT_CLIENT_BACKOFF); - } - - /** - * Initializes a new instance of the {@link ExponentialBackoffRetryStrategy} class. - * - * @param retryCount The maximum number of retry attempts. - * @param minBackoff The minimum backoff time. - * @param maxBackoff The maximum backoff time. - * @param deltaBackoff The value that will be used to calculate a random delta in the exponential delay - * between retries. - */ - public ExponentialBackoffRetryStrategy(int retryCount, int minBackoff, int maxBackoff, int deltaBackoff) { - this(null, retryCount, minBackoff, maxBackoff, deltaBackoff, DEFAULT_FIRST_FAST_RETRY); - } - - /** - * Initializes a new instance of the {@link ExponentialBackoffRetryStrategy} class. - * - * @param name The name of the retry strategy. - * @param retryCount The maximum number of retry attempts. - * @param minBackoff The minimum backoff time. - * @param maxBackoff The maximum backoff time. - * @param deltaBackoff The value that will be used to calculate a random delta in the exponential delay - * between retries. - * @param firstFastRetry true to immediately retry in the first attempt; otherwise, false. The subsequent - * retries will remain subject to the configured retry interval. - */ - public ExponentialBackoffRetryStrategy(String name, int retryCount, int minBackoff, int maxBackoff, - int deltaBackoff, boolean firstFastRetry) { - super(name, firstFastRetry); - this.retryCount = retryCount; - this.minBackoff = minBackoff; - this.maxBackoff = maxBackoff; - this.deltaBackoff = deltaBackoff; - } - - /** - * Returns if a request should be retried based on the retry count, current response, - * and the current strategy. - * - * @param retryCount The current retry attempt count. - * @param response The exception that caused the retry conditions to occur. - * @return true if the request should be retried; false otherwise. - */ - @Override - public boolean shouldRetry(int retryCount, Response response) { - int code = response.code(); - //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES - return retryCount < this.retryCount - && (code == 408 || (code >= 500 && code != 501 && code != 505)); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/RetryHandler.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/RetryHandler.java deleted file mode 100644 index 586673e513bd7..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/RetryHandler.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.retry; - -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -import java.io.IOException; - -/** - * An instance of this interceptor placed in the request pipeline handles retriable errors. - */ -public class RetryHandler implements Interceptor { - /** - * Represents the default number of retries. - */ - private static final int DEFAULT_NUMBER_OF_ATTEMPTS = 3; - /** - * Represents the default value that will be used to calculate a random - * delta in the exponential delay between retries. - */ - private static final int DEFAULT_BACKOFF_DELTA = 1000 * 10; - /** - * Represents the default maximum backoff time. - */ - private static final int DEFAULT_MAX_BACKOFF = 1000 * 10; - /** - * Represents the default minimum backoff time. - */ - private static final int DEFAULT_MIN_BACKOFF = 1000; - - /** - * The retry strategy to use. - */ - private RetryStrategy retryStrategy; - - /** - * Initialized an instance of {@link RetryHandler} class. - * Sets default retry strategy base on Exponential Backoff. - */ - public RetryHandler() { - this.retryStrategy = new ExponentialBackoffRetryStrategy( - DEFAULT_NUMBER_OF_ATTEMPTS, - DEFAULT_MIN_BACKOFF, - DEFAULT_MAX_BACKOFF, - DEFAULT_BACKOFF_DELTA); - } - - /** - * Initialized an instance of {@link RetryHandler} class. - * - * @param retryStrategy retry strategy to use. - */ - public RetryHandler(RetryStrategy retryStrategy) { - this.retryStrategy = retryStrategy; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - - // try the request - Response response = chain.proceed(request); - - int tryCount = 0; - while (retryStrategy.shouldRetry(tryCount, response)) { - tryCount++; - if (response.body() != null) { - response.body().close(); - } - // retry the request - response = chain.proceed(request); - } - - // otherwise just pass the original response on - return response; - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/RetryStrategy.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/RetryStrategy.java deleted file mode 100644 index d5002a5a2e6bb..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/RetryStrategy.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.retry; - -import okhttp3.Response; - -/** - * Represents a retry strategy that determines the number of retry attempts and the interval - * between retries. - */ -public abstract class RetryStrategy { - /** - * Represents the default number of retry attempts. - */ - public static final int DEFAULT_CLIENT_RETRY_COUNT = 10; - - /** - * Represents the default interval between retries. - */ - public static final int DEFAULT_RETRY_INTERVAL = 1000; - /** - * Represents the default flag indicating whether the first retry attempt will be made immediately, - * whereas subsequent retries will remain subject to the retry interval. - */ - public static final boolean DEFAULT_FIRST_FAST_RETRY = true; - - /** - * The name of the retry strategy. - */ - private String name; - - /** - * The value indicating whether the first retry attempt will be made immediately, - * whereas subsequent retries will remain subject to the retry interval. - */ - private boolean fastFirstRetry; - - /** - * Initializes a new instance of the {@link RetryStrategy} class. - * - * @param name The name of the retry strategy. - * @param firstFastRetry true to immediately retry in the first attempt; otherwise, false. - */ - protected RetryStrategy(String name, boolean firstFastRetry) { - this.name = name; - this.fastFirstRetry = firstFastRetry; - } - - /** - * Returns if a request should be retried based on the retry count, current response, - * and the current strategy. - * - * @param retryCount The current retry attempt count. - * @param response The exception that caused the retry conditions to occur. - * @return true if the request should be retried; false otherwise. - */ - public abstract boolean shouldRetry(int retryCount, Response response); - - /** - * Gets the name of the retry strategy. - * - * @return the name of the retry strategy. - */ - public String getName() { - return name; - } - - /** - * Gets whether the first retry attempt will be made immediately. - * - * @return true if the first retry attempt will be made immediately. - * false otherwise. - */ - public boolean isFastFirstRetry() { - return fastFirstRetry; - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/package-info.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/package-info.java deleted file mode 100644 index 2abd7034fa800..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/retry/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * The package contains classes that define the retry behaviors when an error - * occurs during a REST call. - */ -package com.microsoft.rest.retry; \ No newline at end of file diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/Base64UrlSerializer.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/Base64UrlSerializer.java deleted file mode 100644 index 757ab735e2c0d..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/Base64UrlSerializer.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.microsoft.rest.Base64Url; - -import java.io.IOException; - -/** - * Custom serializer for serializing {@link Byte[]} objects into Base64 strings. - */ -public class Base64UrlSerializer extends JsonSerializer { - /** - * Gets a module wrapping this serializer as an adapter for the Jackson - * ObjectMapper. - * - * @return a simple module to be plugged onto Jackson ObjectMapper. - */ - public static SimpleModule getModule() { - SimpleModule module = new SimpleModule(); - module.addSerializer(Base64Url.class, new Base64UrlSerializer()); - return module; - } - - @Override - public void serialize(Base64Url value, JsonGenerator jgen, SerializerProvider provider) throws IOException { - jgen.writeString(value.toString()); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/ByteArraySerializer.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/ByteArraySerializer.java deleted file mode 100644 index e32093a1c1803..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/ByteArraySerializer.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; - -import java.io.IOException; - -/** - * Custom serializer for serializing {@link Byte[]} objects into Base64 strings. - */ -public class ByteArraySerializer extends JsonSerializer { - /** - * Gets a module wrapping this serializer as an adapter for the Jackson - * ObjectMapper. - * - * @return a simple module to be plugged onto Jackson ObjectMapper. - */ - public static SimpleModule getModule() { - SimpleModule module = new SimpleModule(); - module.addSerializer(Byte[].class, new ByteArraySerializer()); - return module; - } - - @Override - public void serialize(Byte[] value, JsonGenerator jgen, SerializerProvider provider) throws IOException { - byte[] bytes = new byte[value.length]; - for (int i = 0; i < value.length; i++) { - bytes[i] = value[i]; - } - jgen.writeBinary(bytes); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/CollectionFormat.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/CollectionFormat.java deleted file mode 100644 index 12e4c3fdeb01e..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/CollectionFormat.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -/** - * Swagger collection format to use for joining {@link java.util.List} parameters in - * paths, queries, and headers. - * See https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#fixed-fields-7. - */ -public enum CollectionFormat { - /** - * Comma separated values. - * E.g. foo,bar - */ - CSV(","), - /** - * Space separated values. - * E.g. foo bar - */ - SSV(" "), - /** - * Tab separated values. - * E.g. foo\tbar - */ - TSV("\t"), - /** - * Pipe(|) separated values. - * E.g. foo|bar - */ - PIPES("|"), - /** - * Corresponds to multiple parameter instances instead of multiple values - * for a single instance. - * E.g. foo=bar&foo=baz - */ - MULTI("&"); - - /** - * The delimiter separating the values. - */ - private String delimiter; - - /** - * Creates an instance of the enum. - * @param delimiter the delimiter as a string. - */ - CollectionFormat(String delimiter) { - this.delimiter = delimiter; - } - - /** - * Gets the delimiter used to join a list of parameters. - * @return the delimiter of the current collection format. - */ - public String getDelimiter() { - return delimiter; - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/DateTimeRfc1123Serializer.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/DateTimeRfc1123Serializer.java deleted file mode 100644 index ac90cd471c7ce..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/DateTimeRfc1123Serializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.microsoft.rest.DateTimeRfc1123; - -import java.io.IOException; - -/** - * Custom serializer for serializing {@link DateTimeRfc1123} object into RFC1123 formats. - */ -public class DateTimeRfc1123Serializer extends JsonSerializer { - /** - * Gets a module wrapping this serializer as an adapter for the Jackson - * ObjectMapper. - * - * @return a simple module to be plugged onto Jackson ObjectMapper. - */ - public static SimpleModule getModule() { - SimpleModule module = new SimpleModule(); - module.addSerializer(DateTimeRfc1123.class, new DateTimeRfc1123Serializer()); - return module; - } - - @Override - public void serialize(DateTimeRfc1123 value, JsonGenerator jgen, SerializerProvider provider) throws IOException { - if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) { - jgen.writeNumber(value.getDateTime().getMillis()); - } else { - jgen.writeString(value.toString()); //Use the default toString as it is RFC1123. - } - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/DateTimeSerializer.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/DateTimeSerializer.java deleted file mode 100644 index 30dc795a415b8..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/DateTimeSerializer.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.format.ISODateTimeFormat; - -import java.io.IOException; - -/** - * Custom serializer for serializing {@link DateTime} object into ISO8601 formats. - */ -public class DateTimeSerializer extends JsonSerializer { - /** - * Gets a module wrapping this serializer as an adapter for the Jackson - * ObjectMapper. - * - * @return a simple module to be plugged onto Jackson ObjectMapper. - */ - public static SimpleModule getModule() { - SimpleModule module = new SimpleModule(); - module.addSerializer(DateTime.class, new DateTimeSerializer()); - return module; - } - - @Override - public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException { - if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) { - jgen.writeNumber(value.getMillis()); - } else { - value = value.withZone(DateTimeZone.UTC); - jgen.writeString(value.toString(ISODateTimeFormat.dateTime())); - } - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/FlatteningDeserializer.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/FlatteningDeserializer.java deleted file mode 100644 index dd7468a728372..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/FlatteningDeserializer.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.BeanDescription; -import com.fasterxml.jackson.databind.DeserializationConfig; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; -import com.fasterxml.jackson.databind.deser.ResolvableDeserializer; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import java.io.IOException; -import java.lang.reflect.Field; - -/** - * Custom serializer for deserializing complex types with wrapped properties. - * For example, a property with annotation @JsonProperty(value = "properties.name") - * will be mapped to a top level "name" property in the POJO model. - */ -public class FlatteningDeserializer extends StdDeserializer implements ResolvableDeserializer { - /** - * The default mapperAdapter for the current type. - */ - private final JsonDeserializer defaultDeserializer; - - /** - * The object mapper for default deserializations. - */ - private final ObjectMapper mapper; - - /** - * Creates an instance of FlatteningDeserializer. - * @param vc handled type - * @param defaultDeserializer the default JSON mapperAdapter - * @param mapper the object mapper for default deserializations - */ - protected FlatteningDeserializer(Class vc, JsonDeserializer defaultDeserializer, ObjectMapper mapper) { - super(vc); - this.defaultDeserializer = defaultDeserializer; - this.mapper = mapper; - } - - /** - * Gets a module wrapping this serializer as an adapter for the Jackson - * ObjectMapper. - * - * @param mapper the object mapper for default deserializations - * @return a simple module to be plugged onto Jackson ObjectMapper. - */ - public static SimpleModule getModule(final ObjectMapper mapper) { - SimpleModule module = new SimpleModule(); - module.setDeserializerModifier(new BeanDeserializerModifier() { - @Override - public JsonDeserializer modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer deserializer) { - if (beanDesc.getBeanClass().getAnnotation(JsonFlatten.class) != null) { - return new FlatteningDeserializer(beanDesc.getBeanClass(), deserializer, mapper); - } - return deserializer; - } - }); - return module; - } - - @SuppressWarnings("unchecked") - @Override - public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { - JsonNode root = mapper.readTree(jp); - final Class tClass = this.defaultDeserializer.handledType(); - for (Field field : tClass.getDeclaredFields()) { - JsonNode node = root; - JsonProperty property = field.getAnnotation(JsonProperty.class); - if (property != null) { - String value = property.value(); - if (value.matches(".+[^\\\\]\\..+")) { - String[] values = value.split("((? implements ResolvableSerializer { - /** - * The default mapperAdapter for the current type. - */ - private final JsonSerializer defaultSerializer; - - /** - * The object mapper for default serializations. - */ - private final ObjectMapper mapper; - - /** - * Creates an instance of FlatteningSerializer. - * @param vc handled type - * @param defaultSerializer the default JSON serializer - * @param mapper the object mapper for default serializations - */ - protected FlatteningSerializer(Class vc, JsonSerializer defaultSerializer, ObjectMapper mapper) { - super(vc, false); - this.defaultSerializer = defaultSerializer; - this.mapper = mapper; - } - - /** - * Gets a module wrapping this serializer as an adapter for the Jackson - * ObjectMapper. - * - * @param mapper the object mapper for default serializations - * @return a simple module to be plugged onto Jackson ObjectMapper. - */ - public static SimpleModule getModule(final ObjectMapper mapper) { - SimpleModule module = new SimpleModule(); - module.setSerializerModifier(new BeanSerializerModifier() { - @Override - public JsonSerializer modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer serializer) { - if (beanDesc.getBeanClass().getAnnotation(JsonFlatten.class) != null) { - return new FlatteningSerializer(beanDesc.getBeanClass(), serializer, mapper); - } - return serializer; - } - }); - return module; - } - - @Override - public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { - if (value == null) { - jgen.writeNull(); - return; - } - - // BFS for all collapsed properties - ObjectNode root = mapper.valueToTree(value); - ObjectNode res = root.deepCopy(); - Queue source = new LinkedBlockingQueue(); - Queue target = new LinkedBlockingQueue(); - source.add(root); - target.add(res); - while (!source.isEmpty()) { - ObjectNode current = source.poll(); - ObjectNode resCurrent = target.poll(); - Iterator> fields = current.fields(); - while (fields.hasNext()) { - Map.Entry field = fields.next(); - ObjectNode node = resCurrent; - String key = field.getKey(); - JsonNode outNode = resCurrent.get(key); - if (field.getKey().matches(".+[^\\\\]\\..+")) { - String[] values = field.getKey().split("((? 0 - && (field.getValue()).get(0) instanceof ObjectNode) { - Iterator sourceIt = field.getValue().elements(); - Iterator targetIt = outNode.elements(); - while (sourceIt.hasNext()) { - source.add((ObjectNode) sourceIt.next()); - target.add((ObjectNode) targetIt.next()); - } - } - } - } - jgen.writeTree(res); - } - - @Override - public void resolve(SerializerProvider provider) throws JsonMappingException { - ((ResolvableSerializer) defaultSerializer).resolve(provider); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/HeadersSerializer.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/HeadersSerializer.java deleted file mode 100644 index a0b109a0fe153..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/HeadersSerializer.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; -import okhttp3.Headers; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Custom serializer for serializing {@link Headers} objects. - */ -public class HeadersSerializer extends JsonSerializer { - /** - * Gets a module wrapping this serializer as an adapter for the Jackson - * ObjectMapper. - * - * @return a simple module to be plugged onto Jackson ObjectMapper. - */ - public static SimpleModule getModule() { - SimpleModule module = new SimpleModule(); - module.addSerializer(Headers.class, new HeadersSerializer()); - return module; - } - - @Override - public void serialize(Headers value, JsonGenerator jgen, SerializerProvider provider) throws IOException { - Map headers = new HashMap(); - for (Map.Entry> entry : value.toMultimap().entrySet()) { - if (entry.getValue() != null && entry.getValue().size() == 1) { - headers.put(entry.getKey(), entry.getValue().get(0)); - } else if (entry.getValue() != null && entry.getValue().size() > 1) { - headers.put(entry.getKey(), entry.getValue()); - } - } - jgen.writeObject(headers); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/JacksonConverterFactory.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/JacksonConverterFactory.java deleted file mode 100644 index 96749a19c9f16..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/JacksonConverterFactory.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; -import com.fasterxml.jackson.databind.ObjectWriter; -import okhttp3.MediaType; -import okhttp3.RequestBody; -import okhttp3.ResponseBody; -import retrofit2.Converter; -import retrofit2.Retrofit; - -import java.io.IOException; -import java.io.Reader; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; - -/** - * A similar implementation of {@link retrofit2.converter.jackson.JacksonConverterFactory} which supports polymorphism. - */ -public final class JacksonConverterFactory extends Converter.Factory { - /** - * Create an instance using a default {@link ObjectMapper} instance for conversion. - * - * @return an instance of JacksonConverterFactory - */ - public static JacksonConverterFactory create() { - return create(new ObjectMapper()); - } - - - /** - * Create an instance using {@code mapper} for conversion. - * - * @param mapper a user-provided {@link ObjectMapper} to use - * @return an instance of JacksonConverterFactory - */ - public static JacksonConverterFactory create(ObjectMapper mapper) { - return new JacksonConverterFactory(mapper); - } - - /** - * The Jackson object mapper. - */ - private final ObjectMapper mapper; - - private JacksonConverterFactory(ObjectMapper mapper) { - if (mapper == null) { - throw new NullPointerException("mapper == null"); - } - this.mapper = mapper; - } - - @Override - public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { - JavaType javaType = mapper.getTypeFactory().constructType(type); - ObjectReader reader = mapper.reader(javaType); - return new JacksonResponseBodyConverter<>(reader); - } - - @Override - public Converter requestBodyConverter(Type type, - Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { - ObjectWriter writer = mapper.writer(); - return new JacksonRequestBodyConverter<>(writer); - } - - /** - * An instance of this class converts an object into JSON. - * - * @param type of request object - */ - final class JacksonRequestBodyConverter implements Converter { - /** Jackson object writer. */ - private final ObjectWriter adapter; - - JacksonRequestBodyConverter(ObjectWriter adapter) { - this.adapter = adapter; - } - - @Override public RequestBody convert(T value) throws IOException { - byte[] bytes = adapter.writeValueAsBytes(value); - return RequestBody.create(MediaType.parse("application/json; charset=UTF-8"), bytes); - } - } - - /** - * An instance of this class converts a JSON payload into an object. - * - * @param the expected object type to convert to - */ - final class JacksonResponseBodyConverter implements Converter { - /** Jackson object reader. */ - private final ObjectReader adapter; - - JacksonResponseBodyConverter(ObjectReader adapter) { - this.adapter = adapter; - } - - @Override public T convert(ResponseBody value) throws IOException { - Reader reader = value.charStream(); - try { - return adapter.readValue(reader); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException ignored) { - } - } - } - } - } -} - diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/JacksonMapperAdapter.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/JacksonMapperAdapter.java deleted file mode 100644 index ea938fe50c9c5..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/JacksonMapperAdapter.java +++ /dev/null @@ -1,186 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.joda.JodaModule; -import com.google.common.base.CharMatcher; -import com.google.common.base.Joiner; - -import java.io.IOException; -import java.io.StringWriter; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; - -/** - * A serialization helper class wrapped around {@link JacksonConverterFactory} and {@link ObjectMapper}. - */ -public class JacksonMapperAdapter { - /** - * An instance of {@link ObjectMapper} to serialize/deserialize objects. - */ - private ObjectMapper mapper; - - /** - * An instance of {@link ObjectMapper} that does not do flattening. - */ - private ObjectMapper simpleMapper; - - /** - * An instance of {@link JacksonConverterFactory} for Retrofit to use. - */ - private JacksonConverterFactory converterFactory; - - /** - * Initializes an instance of JacksonMapperAdapter with default configurations - * applied to the object mapper. - * - * @param mapper the object mapper to use. - */ - protected void initializeObjectMapper(ObjectMapper mapper) { - mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) - .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true) - .setSerializationInclusion(JsonInclude.Include.NON_NULL) - .registerModule(new JodaModule()) - .registerModule(ByteArraySerializer.getModule()) - .registerModule(Base64UrlSerializer.getModule()) - .registerModule(DateTimeSerializer.getModule()) - .registerModule(DateTimeRfc1123Serializer.getModule()) - .registerModule(HeadersSerializer.getModule()); - mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker() - .withFieldVisibility(JsonAutoDetect.Visibility.ANY) - .withSetterVisibility(JsonAutoDetect.Visibility.NONE) - .withGetterVisibility(JsonAutoDetect.Visibility.NONE) - .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)); - } - - /** - * Gets a static instance of {@link ObjectMapper} that doesn't handle flattening. - * - * @return an instance of {@link ObjectMapper}. - */ - protected ObjectMapper getSimpleMapper() { - if (simpleMapper == null) { - simpleMapper = new ObjectMapper(); - initializeObjectMapper(simpleMapper); - } - return simpleMapper; - } - - /** - * Gets a static instance of {@link ObjectMapper}. - * - * @return an instance of {@link ObjectMapper}. - */ - public ObjectMapper getObjectMapper() { - if (mapper == null) { - mapper = new ObjectMapper(); - initializeObjectMapper(mapper); - mapper.registerModule(FlatteningSerializer.getModule(getSimpleMapper())) - .registerModule(FlatteningDeserializer.getModule(getSimpleMapper())); - } - return mapper; - } - - /** - * Gets a static instance of JacksonConverter factory. - * - * @return an instance of JacksonConverter factory. - */ - public JacksonConverterFactory getConverterFactory() { - if (converterFactory == null) { - converterFactory = JacksonConverterFactory.create(getObjectMapper()); - } - return converterFactory; - } - - /** - * Serializes an object into a JSON string using the current {@link ObjectMapper}. - * - * @param object the object to serialize. - * @return the serialized string. Null if the object to serialize is null. - * @throws IOException exception from serialization. - */ - public String serialize(Object object) throws IOException { - if (object == null) { - return null; - } - StringWriter writer = new StringWriter(); - getObjectMapper().writeValue(writer, object); - return writer.toString(); - } - - /** - * Serializes an object into a raw string using the current {@link ObjectMapper}. - * The leading and trailing quotes will be trimmed. - * - * @param object the object to serialize. - * @return the serialized string. Null if the object to serialize is null. - */ - public String serializeRaw(Object object) { - if (object == null) { - return null; - } - try { - return CharMatcher.is('"').trimFrom(serialize(object)); - } catch (IOException ex) { - return null; - } - } - - /** - * Serializes a list into a string with the delimiter specified with the - * Swagger collection format joining each individual serialized items in - * the list. - * - * @param list the list to serialize. - * @param format the Swagger collection format. - * @return the serialized string - */ - public String serializeList(List list, CollectionFormat format) { - if (list == null) { - return null; - } - List serialized = new ArrayList<>(); - for (Object element : list) { - String raw = serializeRaw(element); - serialized.add(raw != null ? raw : ""); - } - return Joiner.on(format.getDelimiter()).join(serialized); - } - - /** - * Deserializes a string into a {@link T} object using the current {@link ObjectMapper}. - * - * @param value the string value to deserialize. - * @param the type of the deserialized object. - * @param type the type to deserialize. - * @return the deserialized object. - * @throws IOException exception in deserialization - */ - @SuppressWarnings("unchecked") - public T deserialize(String value, final Type type) throws IOException { - if (value == null || value.isEmpty()) { - return null; - } - return (T) getObjectMapper().readValue(value, new TypeReference() { - @Override - public Type getType() { - return type; - } - }); - } -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/JsonFlatten.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/JsonFlatten.java deleted file mode 100644 index 070447cad973c..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/JsonFlatten.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest.serializer; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation used for flattening properties separated by '.'. - * E.g. a property with JsonProperty value "properties.value" - * will have "value" property under the "properties" tree on - * the wire. - * - */ -@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface JsonFlatten { -} diff --git a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/package-info.java b/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/package-info.java deleted file mode 100644 index 7c8d20b9d256a..0000000000000 --- a/src/client/Java/client-runtime/src/main/java/com/microsoft/rest/serializer/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * The package contains classes that handle serialization and deserialization - * for the REST call payloads. - */ -package com.microsoft.rest.serializer; \ No newline at end of file diff --git a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/CredentialsTests.java b/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/CredentialsTests.java deleted file mode 100644 index d21de3ef9bd1e..0000000000000 --- a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/CredentialsTests.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import com.microsoft.rest.credentials.BasicAuthenticationCredentials; -import com.microsoft.rest.credentials.TokenCredentials; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import retrofit2.Retrofit; - -public class CredentialsTests { - @Test - public void basicCredentialsTest() throws Exception { - BasicAuthenticationCredentials credentials = new BasicAuthenticationCredentials("user", "pass"); - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); - credentials.applyCredentialsFilter(clientBuilder); - clientBuilder.addInterceptor( - new Interceptor() { - @Override - public Response intercept(Chain chain) throws IOException { - String header = chain.request().header("Authorization"); - Assert.assertEquals("Basic dXNlcjpwYXNz", header); - return new Response.Builder() - .request(chain.request()) - .code(200) - .protocol(Protocol.HTTP_1_1) - .build(); - } - }); - ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, new Retrofit.Builder()) { }; - Response response = serviceClient.httpClient().newCall(new Request.Builder().url("http://localhost").build()).execute(); - Assert.assertEquals(200, response.code()); - } - - @Test - public void tokenCredentialsTest() throws Exception { - TokenCredentials credentials = new TokenCredentials(null, "this_is_a_token"); - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); - credentials.applyCredentialsFilter(clientBuilder); - clientBuilder.addInterceptor( - new Interceptor() { - @Override - public Response intercept(Chain chain) throws IOException { - String header = chain.request().header("Authorization"); - Assert.assertEquals("Bearer this_is_a_token", header); - return new Response.Builder() - .request(chain.request()) - .code(200) - .protocol(Protocol.HTTP_1_1) - .build(); - } - }); - ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, new Retrofit.Builder()) { }; - Response response = serviceClient.httpClient().newCall(new Request.Builder().url("http://localhost").build()).execute(); - Assert.assertEquals(200, response.code()); - } -} diff --git a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/RetryHandlerTests.java b/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/RetryHandlerTests.java deleted file mode 100644 index 068e57b214323..0000000000000 --- a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/RetryHandlerTests.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import com.microsoft.rest.retry.RetryHandler; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import retrofit2.Retrofit; - -public class RetryHandlerTests { - @Test - public void exponentialRetryEndOn501() throws Exception { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); - Retrofit.Builder retrofitBuilder = new Retrofit.Builder(); - clientBuilder.addInterceptor(new RetryHandler()); - clientBuilder.addInterceptor(new Interceptor() { - // Send 408, 500, 502, all retried, with a 501 ending - private int[] codes = new int[]{408, 500, 502, 501}; - private int count = 0; - - @Override - public Response intercept(Chain chain) throws IOException { - return new Response.Builder() - .request(chain.request()) - .code(codes[count++]) - .protocol(Protocol.HTTP_1_1) - .build(); - } - }); - ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, retrofitBuilder) { }; - Response response = serviceClient.httpClient().newCall( - new Request.Builder().url("http://localhost").get().build()).execute(); - Assert.assertEquals(501, response.code()); - } - - @Test - public void exponentialRetryMax() throws Exception { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); - Retrofit.Builder retrofitBuilder = new Retrofit.Builder(); - clientBuilder.addInterceptor(new RetryHandler()); - clientBuilder.addInterceptor(new Interceptor() { - // Send 500 until max retry is hit - private int count = 0; - - @Override - public Response intercept(Chain chain) throws IOException { - Assert.assertTrue(count++ < 5); - return new Response.Builder() - .request(chain.request()) - .code(500) - .protocol(Protocol.HTTP_1_1) - .build(); - } - }); - ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, retrofitBuilder) { }; - Response response = serviceClient.httpClient().newCall( - new Request.Builder().url("http://localhost").get().build()).execute(); - Assert.assertEquals(500, response.code()); - } -} diff --git a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/ServiceClientTests.java b/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/ServiceClientTests.java deleted file mode 100644 index 9d76292d20a03..0000000000000 --- a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/ServiceClientTests.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import retrofit2.Retrofit; - -public class ServiceClientTests { - @Test - public void filterTests() throws Exception { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); - Retrofit.Builder retrofitBuilder = new Retrofit.Builder(); - clientBuilder.interceptors().add(0, new FirstFilter()); - clientBuilder.interceptors().add(1, new SecondFilter()); - clientBuilder.interceptors().add(new Interceptor() { - @Override - public Response intercept(Chain chain) throws IOException { - Assert.assertEquals("1", chain.request().header("filter1")); - Assert.assertEquals("2", chain.request().header("filter2")); - return new Response.Builder() - .request(chain.request()) - .code(200) - .protocol(Protocol.HTTP_1_1) - .build(); - } - }); - ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, retrofitBuilder) { }; - Response response = serviceClient.httpClient().newCall(new Request.Builder().url("http://localhost").build()).execute(); - Assert.assertEquals(200, response.code()); - } - - public class FirstFilter implements Interceptor { - @Override - public Response intercept(Chain chain) throws IOException { - return chain.proceed(chain.request().newBuilder().header("filter1", "1").build()); - } - } - - public class SecondFilter implements Interceptor { - @Override - public Response intercept(Chain chain) throws IOException { - return chain.proceed(chain.request().newBuilder().header("filter2", "2").build()); - } - } -} diff --git a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/UserAgentTests.java b/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/UserAgentTests.java deleted file mode 100644 index 9aa60e5b26313..0000000000000 --- a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/UserAgentTests.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import retrofit2.Retrofit; - -public class UserAgentTests { - @Test - public void defaultUserAgentTests() throws Exception { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() - .addInterceptor(new UserAgentInterceptor()) - .addInterceptor(new Interceptor() { - @Override - public Response intercept(Chain chain) throws IOException { - String header = chain.request().header("User-Agent"); - Assert.assertEquals("AutoRest-Java", header); - return new Response.Builder() - .request(chain.request()) - .code(200) - .protocol(Protocol.HTTP_1_1) - .build(); - } - }); - ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, new Retrofit.Builder()) { }; - Response response = serviceClient.httpClient() - .newCall(new Request.Builder().get().url("http://localhost").build()).execute(); - Assert.assertEquals(200, response.code()); - } - - @Test - public void customUserAgentTests() throws Exception { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() - .addInterceptor(new UserAgentInterceptor().withUserAgent("Awesome")) - .addInterceptor(new Interceptor() { - @Override - public Response intercept(Chain chain) throws IOException { - String header = chain.request().header("User-Agent"); - Assert.assertEquals("Awesome", header); - return new Response.Builder() - .request(chain.request()) - .code(200) - .protocol(Protocol.HTTP_1_1) - .build(); - } - }); - ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, new Retrofit.Builder()) { }; - Response response = serviceClient.httpClient() - .newCall(new Request.Builder().get().url("http://localhost").build()).execute(); - Assert.assertEquals(200, response.code()); - } -} diff --git a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/ValidatorTests.java b/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/ValidatorTests.java deleted file mode 100644 index 5120c33df0cef..0000000000000 --- a/src/client/Java/client-runtime/src/test/java/com/microsoft/rest/ValidatorTests.java +++ /dev/null @@ -1,195 +0,0 @@ -/** - * - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * - */ - -package com.microsoft.rest; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.node.TextNode; - -import org.junit.Assert; -import org.joda.time.LocalDate; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.fail; - -public class ValidatorTests { - @Test - public void validateInt() throws Exception { - IntWrapper body = new IntWrapper(); - body.value = 2; - body.nullable = null; - Validator.validate(body); // pass - } - - @Test - public void validateInteger() throws Exception { - IntegerWrapper body = new IntegerWrapper(); - body.value = 3; - Validator.validate(body); // pass - try { - body.value = null; - Validator.validate(body); // fail - fail(); - } catch (IllegalArgumentException ex) { - Assert.assertTrue(ex.getMessage().contains("value is required")); - } - } - - @Test - public void validateString() throws Exception { - StringWrapper body = new StringWrapper(); - body.value = ""; - Validator.validate(body); // pass - try { - body.value = null; - Validator.validate(body); // fail - fail(); - } catch (IllegalArgumentException ex) { - Assert.assertTrue(ex.getMessage().contains("value is required")); - } - } - - @Test - public void validateLocalDate() throws Exception { - LocalDateWrapper body = new LocalDateWrapper(); - body.value = new LocalDate(1, 2, 3); - Validator.validate(body); // pass - try { - body.value = null; - Validator.validate(body); // fail - fail(); - } catch (IllegalArgumentException ex) { - Assert.assertTrue(ex.getMessage().contains("value is required")); - } - } - - @Test - public void validateList() throws Exception { - ListWrapper body = new ListWrapper(); - try { - body.list = null; - Validator.validate(body); // fail - fail(); - } catch (IllegalArgumentException ex) { - Assert.assertTrue(ex.getMessage().contains("list is required")); - } - body.list = new ArrayList(); - Validator.validate(body); // pass - StringWrapper wrapper = new StringWrapper(); - wrapper.value = "valid"; - body.list.add(wrapper); - Validator.validate(body); // pass - body.list.add(null); - Validator.validate(body); // pass - body.list.add(new StringWrapper()); - try { - Validator.validate(body); // fail - fail(); - } catch (IllegalArgumentException ex) { - Assert.assertTrue(ex.getMessage().contains("list.value is required")); - } - } - - @Test - public void validateMap() throws Exception { - MapWrapper body = new MapWrapper(); - try { - body.map = null; - Validator.validate(body); // fail - fail(); - } catch (IllegalArgumentException ex) { - Assert.assertTrue(ex.getMessage().contains("map is required")); - } - body.map = new HashMap(); - Validator.validate(body); // pass - StringWrapper wrapper = new StringWrapper(); - wrapper.value = "valid"; - body.map.put(new LocalDate(1, 2, 3), wrapper); - Validator.validate(body); // pass - body.map.put(new LocalDate(1, 2, 3), null); - Validator.validate(body); // pass - body.map.put(new LocalDate(1, 2, 3), new StringWrapper()); - try { - Validator.validate(body); // fail - fail(); - } catch (IllegalArgumentException ex) { - Assert.assertTrue(ex.getMessage().contains("map.value is required")); - } - } - - @Test - public void validateObject() throws Exception { - Product product = new Product(); - Validator.validate(product); - } - - @Test - public void validateRecursive() throws Exception { - TextNode textNode = new TextNode("\"\""); - Validator.validate(textNode); - } - - public final class IntWrapper { - @JsonProperty(required = true) - // CHECKSTYLE IGNORE VisibilityModifier FOR NEXT 2 LINES - public int value; - public Object nullable; - } - - public final class IntegerWrapper { - @JsonProperty(required = true) - // CHECKSTYLE IGNORE VisibilityModifier FOR NEXT 1 LINE - public Integer value; - } - - public final class StringWrapper { - @JsonProperty(required = true) - // CHECKSTYLE IGNORE VisibilityModifier FOR NEXT 1 LINE - public String value; - } - - public final class LocalDateWrapper { - @JsonProperty(required = true) - // CHECKSTYLE IGNORE VisibilityModifier FOR NEXT 1 LINE - public LocalDate value; - } - - public final class ListWrapper { - @JsonProperty(required = true) - // CHECKSTYLE IGNORE VisibilityModifier FOR NEXT 1 LINE - public List list; - } - - public final class MapWrapper { - @JsonProperty(required = true) - // CHECKSTYLE IGNORE VisibilityModifier FOR NEXT 1 LINE - public Map map; - } - - public enum Color { - RED, - GREEN, - Blue - } - - public final class EnumWrapper { - @JsonProperty(required = true) - // CHECKSTYLE IGNORE VisibilityModifier FOR NEXT 1 LINE - public Color color; - } - - public final class Product { - // CHECKSTYLE IGNORE VisibilityModifier FOR NEXT 2 LINES - public String id; - public String tag; - } -} diff --git a/src/client/Java/pom.xml b/src/client/Java/pom.xml deleted file mode 100644 index aa77260c5893f..0000000000000 --- a/src/client/Java/pom.xml +++ /dev/null @@ -1,220 +0,0 @@ - - - 4.0.0 - - com.microsoft.azure - autorest-clientruntime-for-java - 1.0.0-SNAPSHOT - pom - - AutoRest Client Runtimes for Java - This package contains the runtimes for AutoRest generated Java clients. - https://github.com/Azure/autorest-clientruntime-for-java - - - - The MIT License (MIT) - http://opensource.org/licenses/MIT - repo - - - - - scm:git:https://github.com/Azure/autorest-clientruntime-for-java - scm:git:git@github.com:Azure/autorest-clientruntime-for-java.git - HEAD - - - - UTF-8 - - - - - - microsoft - Microsoft - - - - - - ossrh - Sonatype Snapshots - https://oss.sonatype.org/content/repositories/snapshots/ - default - - true - always - - - - - - - ossrh - Maven Central Snapshots - https://oss.sonatype.org/content/repositories/snapshots - true - default - - - ossrh - Maven Central - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - - com.google.guava - guava - 18.0 - - - com.squareup.retrofit2 - retrofit - 2.0.2 - - - com.squareup.okhttp3 - okhttp - 3.3.1 - - - com.squareup.okhttp3 - logging-interceptor - 3.3.1 - - - com.squareup.okhttp3 - okhttp-urlconnection - 3.3.1 - - - com.squareup.retrofit2 - converter-jackson - 2.0.2 - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - 2.7.2 - - - org.apache.commons - commons-lang3 - 3.4 - - - com.microsoft.azure - adal4j - 1.1.2 - - - com.microsoft.aad - adal - 1.1.11 - - - junit - junit - 4.12 - test - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - - com.microsoft.azure - autorest-build-tools - 1.0.0-SNAPSHOT - - - com.puppycrawl.tools - checkstyle - 6.18 - - - - checkstyle.xml - samedir=build-tools/src/main/resources - suppressions.xml - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.7 - 1.7 - true - true - -Xlint:unchecked - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage - /** -
* Copyright (c) Microsoft Corporation. All rights reserved. -
* Licensed under the MIT License. See License.txt in the project root for -
* license information. -
*/]]>
-
-
-
- - - - org.apache.maven.plugins - maven-resources-plugin - 2.4.3 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18.1 - - - **/Test*.java - **/*Test.java - **/*Tests.java - **/*TestCase.java - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.2 - - - -
- - build-tools - client-runtime - azure-client-runtime - azure-client-authentication - -