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