github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/java/libraries/retrofit/auth/ApiKeyAuth.mustache (about) 1 package {{invokerPackage}}.auth; 2 3 import java.io.IOException; 4 import java.net.URI; 5 import java.net.URISyntaxException; 6 7 import com.squareup.okhttp.Interceptor; 8 import com.squareup.okhttp.Request; 9 import com.squareup.okhttp.Response; 10 11 public class ApiKeyAuth implements Interceptor { 12 private final String location; 13 private final String paramName; 14 15 private String apiKey; 16 17 public ApiKeyAuth(String location, String paramName) { 18 this.location = location; 19 this.paramName = paramName; 20 } 21 22 public String getLocation() { 23 return location; 24 } 25 26 public String getParamName() { 27 return paramName; 28 } 29 30 public String getApiKey() { 31 return apiKey; 32 } 33 34 public void setApiKey(String apiKey) { 35 this.apiKey = apiKey; 36 } 37 38 @Override 39 public Response intercept(Chain chain) throws IOException { 40 String paramValue; 41 Request request = chain.request(); 42 43 if ("query".equals(location)) { 44 String newQuery = request.uri().getQuery(); 45 paramValue = paramName + "=" + apiKey; 46 if (newQuery == null) { 47 newQuery = paramValue; 48 } else { 49 newQuery += "&" + paramValue; 50 } 51 52 URI newUri; 53 try { 54 newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), 55 request.uri().getPath(), newQuery, request.uri().getFragment()); 56 } catch (URISyntaxException e) { 57 throw new IOException(e); 58 } 59 60 request = request.newBuilder().url(newUri.toURL()).build(); 61 } else if ("header".equals(location)) { 62 request = request.newBuilder() 63 .addHeader(paramName, apiKey) 64 .build(); 65 } else if ("cookie".equals(location)) { 66 request = request.newBuilder() 67 .addHeader("Cookie", String.format("%s=%s", paramName, apiKey)) 68 .build(); 69 } 70 return chain.proceed(request); 71 } 72 }