3
3
import io .swagger .codegen .v3 .CodegenConfig ;
4
4
import io .swagger .v3 .oas .models .OpenAPI ;
5
5
import io .swagger .v3 .oas .models .servers .Server ;
6
+ import io .swagger .v3 .oas .models .servers .ServerVariables ;
6
7
import org .apache .commons .lang3 .StringUtils ;
8
+ import org .apache .commons .lang3 .text .StrSubstitutor ;
7
9
import org .slf4j .Logger ;
8
10
import org .slf4j .LoggerFactory ;
9
11
10
12
import java .net .MalformedURLException ;
11
13
import java .net .URL ;
12
14
import java .util .List ;
15
+ import java .util .Map ;
16
+ import java .util .stream .Collectors ;
13
17
14
18
public class URLPathUtil {
15
19
16
20
protected static final Logger LOGGER = LoggerFactory .getLogger (URLPathUtil .class );
17
21
public static String DEFAULT_PATH = "/" ;
22
+ public static String DEFAULT_PORT = "8080" ;
18
23
public static final String LOCAL_HOST = "http://localhost:8080" ;
19
24
20
25
public static URL getServerURL (OpenAPI openAPI ) {
@@ -30,7 +35,8 @@ public static URL getServerURL(OpenAPI openAPI) {
30
35
url = LOCAL_HOST + url ;
31
36
}
32
37
try {
33
- return new URL (url );
38
+ String varReplacedUrl = replaceServerVarsWthDefaultValues (url , server .getVariables ());
39
+ return new URL (varReplacedUrl );
34
40
} catch (MalformedURLException e ) {
35
41
LOGGER .warn ("Not valid URL: " + server .getUrl (), e );
36
42
return null ;
@@ -67,7 +73,8 @@ public static URL getServerURL(OpenAPI openAPI, CodegenConfig config) {
67
73
serverUrl = inputURL ;
68
74
break ;
69
75
}
70
- return new URL (serverUrl );
76
+ String varReplacedUrl = replaceServerVarsWthDefaultValues (serverUrl , server .getVariables ());
77
+ return new URL (varReplacedUrl );
71
78
} catch (Exception e ) {
72
79
LOGGER .warn ("Not valid URL: " + server .getUrl (), e );
73
80
return null ;
@@ -94,4 +101,16 @@ public static String getHost(OpenAPI openAPI){
94
101
}
95
102
return LOCAL_HOST ;
96
103
}
104
+
105
+ private static String replaceServerVarsWthDefaultValues (String url , ServerVariables vars ) {
106
+ if (vars != null && vars .size () > 0 ) {
107
+ Map <String , Object > defaultValues = vars .entrySet ()
108
+ .stream ()
109
+ .collect (Collectors .toMap (
110
+ Map .Entry ::getKey ,
111
+ e -> e .getValue ().getDefault () != null ? e .getValue ().getDefault () : DEFAULT_PORT ));
112
+ return StrSubstitutor .replace (url , defaultValues , "{" , "}" );
113
+ }
114
+ return url ;
115
+ }
97
116
}
0 commit comments