github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/java/libraries/retrofit2/auth/OAuthOkHttpClient.mustache (about) 1 package {{invokerPackage}}.auth; 2 3 import java.io.IOException; 4 import java.util.Map; 5 import java.util.Map.Entry; 6 7 import org.apache.oltu.oauth2.client.HttpClient; 8 import org.apache.oltu.oauth2.client.request.OAuthClientRequest; 9 import org.apache.oltu.oauth2.client.response.OAuthClientResponse; 10 import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; 11 import org.apache.oltu.oauth2.common.exception.OAuthProblemException; 12 import org.apache.oltu.oauth2.common.exception.OAuthSystemException; 13 14 15 import okhttp3.Interceptor; 16 import okhttp3.OkHttpClient; 17 import okhttp3.Request; 18 import okhttp3.Request.Builder; 19 import okhttp3.Response; 20 import okhttp3.MediaType; 21 import okhttp3.RequestBody; 22 23 24 public class OAuthOkHttpClient implements HttpClient { 25 26 private OkHttpClient client; 27 28 public OAuthOkHttpClient() { 29 this.client = new OkHttpClient(); 30 } 31 32 public OAuthOkHttpClient(OkHttpClient client) { 33 this.client = client; 34 } 35 36 public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, 37 String requestMethod, Class<T> responseClass) 38 throws OAuthSystemException, OAuthProblemException { 39 40 MediaType mediaType = MediaType.parse("application/json"); 41 Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); 42 43 if(headers != null) { 44 for (Entry<String, String> entry : headers.entrySet()) { 45 if (entry.getKey().equalsIgnoreCase("Content-Type")) { 46 mediaType = MediaType.parse(entry.getValue()); 47 } else { 48 requestBuilder.addHeader(entry.getKey(), entry.getValue()); 49 } 50 } 51 } 52 53 RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; 54 requestBuilder.method(requestMethod, body); 55 56 try { 57 Response response = client.newCall(requestBuilder.build()).execute(); 58 return OAuthClientResponseFactory.createCustomResponse( 59 response.body().string(), 60 response.body().contentType().toString(), 61 response.code(), 62 responseClass); 63 } catch (IOException e) { 64 throw new OAuthSystemException(e); 65 } 66 } 67 68 public void shutdown() { 69 // Nothing to do here 70 } 71 72 }