/**
 *
 * 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");
        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]);
        }
        if (baseUrl != null) {
            HttpUrl baseHttpUrl = HttpUrl.parse(baseUrl);
            request = request.newBuilder()
                    .url(baseHttpUrl)
                    .build();
        }
        return chain.proceed(request);
    }
}

@@ -877,24 +877,87 @@
 zed-host%22);%0A
+        if (parameters != null && !parameters.isEmpty()) %7B%0A    
         Stri
@@ -1004,24 +1004,28 @@
 %22);%0A        
+   
+ 
 if (replacem
@@ -1044,24 +1044,28 @@
 %25 2 != 0) %7B%0A
+    
             
@@ -1153,34 +1153,42 @@
 tern%22);%0A        
+  
-%7D%0A
+  %7D%0A    
         String b
@@ -1230,16 +1230,20 @@
         
+ 
+   
 for (int
@@ -1281,24 +1281,28 @@
 ; i += 2) %7B%0A
+    
             
@@ -1401,40 +1401,13 @@
     
-%7D%0A        if (baseUrl != null) %7B
+    %7D
 %0A   
@@ -1504,16 +1504,16 @@
 ilder()%0A
-
         
@@ -1542,16 +1542,77 @@
 ttpUrl)%0A
+                    .removeHeader(%22x-ms-parameterized-host%22)%0A
         

Remove header after use