Open ab48917 opened 7 years ago
Sorry, your issue fails to give any details which could be used to help you.
For which language are you generating stuff? (Please post the full command line, or maven plugin configuration, and the Swagger-Codegen version number.) Also, please include or link the API definition file (swagger/OpenAPI), either the full one or a reduced which still allows reproducing your problem. Then, please include the full code which is creating, setting up and using the client.
Sorry for inconvenience caused, I generated the stubs for java using below command-
java -jar swagger-codegen-cli-2.2.1.jar generate -i geo.json -l java -o myclient -a "Authorization:Basic ****=="
But my swagger schema does not have securityconfig information. Producer did not write this in json schema file. And still, Producer has used basic authentication. So the problem here , My stubs does not hold any credentials after generating and neither I am manually able to pass the credentials into ApiClient generated class of swagger.
Below is generated ApiClient
/**
package io.swagger.client;
import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Headers; import com.squareup.okhttp.internal.http.HttpMethod; import com.squareup.okhttp.logging.HttpLoggingInterceptor; import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level;
import java.lang.reflect.Type;
import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern;
import java.net.URLEncoder; import java.net.URLConnection;
import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate;
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager;
import okio.BufferedSink; import okio.Okio;
import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth;
public class ApiClient { public static final double JAVA_VERSION; public static final boolean IS_ANDROID; public static final int ANDROID_SDK_VERSION;
static {
JAVA_VERSION =
Double.parseDouble(System.getProperty("java.specification.version")); boolean isAndroid; try { Class.forName("android.app.Activity"); isAndroid = true; } catch (ClassNotFoundException e) { isAndroid = false; } IS_ANDROID = isAndroid; int sdkVersion = 0; if (IS_ANDROID) { try { sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); } catch (Exception e) { try { sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); } catch (Exception e2) { } } } ANDROID_SDK_VERSION = sdkVersion; }
/**
* The datetime format to be used when
lenientDatetimeFormat
is enabled.
*/
public static final String LENIENT_DATETIME_FORMAT =
"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
private String basePath = "http://geoestest1.dev.qintra.com";
private boolean lenientOnJson = false;
private boolean debugging = false;
private Map<String, String> defaultHeaderMap = new HashMap<String,
String>(); private String tempFolderPath = null;
private Map<String, Authentication> authentications;
private DateFormat dateFormat;
private DateFormat datetimeFormat;
private boolean lenientDatetimeFormat;
private int dateLength;
private InputStream sslCaCert;
private boolean verifyingSsl;
private OkHttpClient httpClient;
private JSON json;
private HttpLoggingInterceptor loggingInterceptor;
/*
* Constructor for ApiClient
*/
public ApiClient() {
httpClient = new OkHttpClient();
verifyingSsl = true;
json = new JSON(this);
/*
* Use RFC3339 format for date and datetime.
* See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
*/
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Always use UTC as the default time zone when dealing with date
(without time). this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); initDatetimeFormat();
// Be lenient on datetime formats when parsing datetime from string.
// See <code>parseDatetime</code>.
this.lenientDatetimeFormat = true;
// Set default User-Agent.
setUserAgent("Swagger-Codegen/1.0.0/java");
// Setup authentications (key: authentication name, value:
authentication). authentications = new HashMap<String, Authentication>(); HttpBasicAuth hba= new HttpBasicAuth();
hba.setUsername("EASELSR");
hba.setPassword("9Em54RUG");
authentications.put("basic", hba);
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
/**
* Get base path
*
* @return Baes path
*/
public String getBasePath() {
return basePath;
}
/**
* Set base path
*
* @param basePath Base path of the URL (e.g
http://geoestest1.dev.qintra.com
@return An instance of OkHttpClient */ public ApiClient setBasePath(String basePath) { this.basePath = basePath; return this; }
/**
@return An instance of OkHttpClient */ public OkHttpClient getHttpClient() { return httpClient; }
/**
@return Api Client */ public ApiClient setHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; return this; }
/**
@return JSON object */ public JSON getJSON() { return json; }
/**
@return Api client */ public ApiClient setJSON(JSON json) { this.json = json; return this; }
/**
@return True if isVerifySsl flag is on */ public boolean isVerifyingSsl() { return verifyingSsl; }
/**
@return ApiClient */ public ApiClient setVerifyingSsl(boolean verifyingSsl) { this.verifyingSsl = verifyingSsl; applySslSettings(); return this; }
/**
@return Input stream to the SSL CA cert */ public InputStream getSslCaCert() { return sslCaCert; }
/**
@return ApiClient */ public ApiClient setSslCaCert(InputStream sslCaCert) { this.sslCaCert = sslCaCert; applySslSettings(); return this; }
public DateFormat getDateFormat() { return dateFormat; }
public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; this.dateLength = this.dateFormat.format(new Date()).length(); return this; }
public DateFormat getDatetimeFormat() { return datetimeFormat; }
public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { this.datetimeFormat = datetimeFormat; return this; }
/**
@return True if lenientDatetimeFormat flag is set to true */ public boolean isLenientDatetimeFormat() { return lenientDatetimeFormat; }
public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { this.lenientDatetimeFormat = lenientDatetimeFormat; return this; }
/**
dateFormat
supports these ISO 8601 date
formats:@return Date */ public Date parseDate(String str) { if (str == null) return null; try { return dateFormat.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } }
/**
@return Date representation of the string */ public Date parseDatetime(String str) { if (str == null) return null;
DateFormat format;
if (lenientDatetimeFormat) {
/*
* When lenientDatetimeFormat is enabled, normalize the date
string
LENIENT_DATETIME_FORMAT
to support various
formatsdefined by ISO 8601. */ // normalize time zone // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 str = str.replaceAll("[zZ]\z", "+0000"); // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 str = str.replaceAll("([+-]\d{2}):(\d{2})\z", "$1$2"); // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 str = str.replaceAll("([+-]\d{2})\z", "$100"); // add milliseconds when missing // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 str = str.replaceAll("(:\d{1,2})([+-]\d{4})\z", "$1.000$2"); format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); } else { format = this.datetimeFormat; }
try { return format.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } }
/*
@return Date representation of the string */ public Date parseDateOrDatetime(String str) { if (str == null) return null; else if (str.length() <= dateLength) return parseDate(str); else return parseDatetime(str); }
/**
@return Formatted date in string representation */ public String formatDate(Date date) { return dateFormat.format(date); }
/**
@return Formatted datetime in string representation */ public String formatDatetime(Date date) { return datetimeFormat.format(date); }
/**
@return Map of authentication objects */ public Map<String, Authentication> getAuthentications() { return authentications; }
/**
@return The authentication, null if not found */ public Authentication getAuthentication(String authName) { return authentications.get(authName); }
/**
@param username Username */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setUsername(username); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); }
/**
@param password Password */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setPassword(password); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); }
/**
@param apiKey API key */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { ((ApiKeyAuth) auth).setApiKey(apiKey); return; } } throw new RuntimeException("No API key authentication configured!"); }
/**
@param apiKeyPrefix API key prefix */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); return; } } throw new RuntimeException("No API key authentication configured!"); }
/**
@param accessToken Access token */ public void setAccessToken(String accessToken) { for (Authentication auth : authentications.values()) { if (auth instanceof OAuth) { ((OAuth) auth).setAccessToken(accessToken); return; } } throw new RuntimeException("No OAuth2 authentication configured!"); }
/**
@return ApiClient */ public ApiClient setUserAgent(String userAgent) { addDefaultHeader("User-Agent", userAgent); return this; }
/**
@return ApiClient */ public ApiClient addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); return this; }
/**
@return True if lenientOnJson is enabled, false otherwise. */ public boolean isLenientOnJson() { return lenientOnJson; }
/**
@return ApiClient */ public ApiClient setLenientOnJson(boolean lenient) { this.lenientOnJson = lenient; return this; }
/**
@return True if debugging is enabled, false otherwise. */ public boolean isDebugging() { return debugging; }
/**
@return ApiClient */ public ApiClient setDebugging(boolean debugging) { if (debugging != this.debugging) { if (debugging) { loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(Level.BODY); httpClient.interceptors().add(loggingInterceptor); } else { httpClient.interceptors().remove(loggingInterceptor); loggingInterceptor = null; } } this.debugging = debugging; return this; }
/**
null
, i.e.
using@return Temporary folder path */ public String getTempFolderPath() { return tempFolderPath; }
/**
@return ApiClient */ public ApiClient setTempFolderPath(String tempFolderPath) { this.tempFolderPath = tempFolderPath; return this; }
/**
@return Timeout in milliseconds */ public int getConnectTimeout() { return httpClient.getConnectTimeout(); }
/**
@return Api client */ public ApiClient setConnectTimeout(int connectionTimeout) { httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); return this; }
/**
@return String representation of the parameter */ public String parameterToString(Object param) { if (param == null) { return ""; } else if (param instanceof Date) { return formatDatetime((Date) param); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); for (Object o : (Collection)param) { if (b.length() > 0) { b.append(","); } b.append(String.valueOf(o)); } return b.toString(); } else { return String.valueOf(param); } }
/**
@return A list of Pair objects
*/
public List
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection valueCollection = null;
if (value instanceof Collection) {
valueCollection = (Collection) value;
} else {
params.add(new Pair(name, parameterToString(value)));
return params;
}
if (valueCollection.isEmpty()){
return params;
}
// get the collection format
collectionFormat = (collectionFormat == null ||
collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
for (Object item : valueCollection) {
params.add(new Pair(name, parameterToString(item)));
}
return params;
}
String delimiter = ",";
if (collectionFormat.equals("csv")) {
delimiter = ",";
} else if (collectionFormat.equals("ssv")) {
delimiter = " ";
} else if (collectionFormat.equals("tsv")) {
delimiter = "\t";
} else if (collectionFormat.equals("pipes")) {
delimiter = "|";
}
StringBuilder sb = new StringBuilder() ;
for (Object item : valueCollection) {
sb.append(delimiter);
sb.append(parameterToString(item));
}
params.add(new Pair(name, sb.substring(1)));
return params;
}
/**
@return The sanitized filename / public String sanitizeFilename(String filename) { return filename.replaceAll(".[/\\]", ""); }
/**
@return True if the given MIME is JSON, false otherwise. / public boolean isJsonMime(String mime) { return mime != null && mime.matches("(?i)application\/json(;.)?"); }
/**
null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { if (accepts.length == 0) { return null; } for (String accept : accepts) { if (isJsonMime(accept)) { return accept; } } return StringUtil.join(accepts, ","); }
/**
JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { if (contentTypes.length == 0) { return "application/json"; } for (String contentType : contentTypes) { if (isJsonMime(contentType)) { return contentType; } } return contentTypes[0]; }
/**
@return Escaped string */ public String escapeString(String str) { try { return URLEncoder.encode(str, "utf8").replaceAll("\+", "%20"); } catch (UnsupportedEncodingException e) { return str; } }
/**
or the Content-Type of the response is not supported.
*/
@SuppressWarnings("unchecked")
public
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
try {
return (T) response.body().bytes();
} catch (IOException e) {
throw new ApiException(e);
}
} else if (returnType.equals(File.class)) {
// Handle file downloading.
return (T) downloadFileFromResponse(response);
}
String respBody;
try {
if (response.body() != null)
respBody = response.body().string();
else
respBody = null;
} catch (IOException e) {
throw new ApiException(e);
}
if (respBody == null || "".equals(respBody)) {
return null;
}
String contentType = response.headers().get("Content-Type");
if (contentType == null) {
// ensuring a default content type
contentType = "application/json";
}
if (isJsonMime(contentType)) {
return json.deserialize(respBody, returnType);
} else if (returnType.equals(String.class)) {
// Expecting string, return the raw response body.
return (T) respBody;
} else {
throw new ApiException(
"Content type \"" + contentType + "\" is not supported
for type: " + returnType, response.code(), response.headers().toMultimap(), respBody); } }
/**
@throws ApiException If fail to serialize the given object */ public RequestBody serialize(Object obj, String contentType) throws ApiException { if (obj instanceof byte[]) { // Binary (byte array) body parameter support. return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); } else if (obj instanceof File) { // File body parameter support. return RequestBody.create(MediaType.parse(contentType), (File) obj); } else if (isJsonMime(contentType)) { String content; if (obj != null) { content = json.serialize(obj); } else { content = null; } return RequestBody.create(MediaType.parse(contentType), content); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } }
/**
@return Downloaded file */ public File downloadFileFromResponse(Response response) throws ApiException { try { File file = prepareDownloadFile(response); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(response.body().source()); sink.close(); return file; } catch (IOException e) { throw new ApiException(e); } }
/**
@return Prepared file for the download */ public File prepareDownloadFile(Response response) throws IOException { String filename = null; String contentDisposition = response.header("Content-Disposition"); if (contentDisposition != null && !"".equals(contentDisposition)) { // Get filename from the Content-Disposition header. Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\s]+)['\"]?"); Matcher matcher = pattern.matcher(contentDisposition); if (matcher.find()) { filename = sanitizeFilename(matcher.group(1)); } }
String prefix = null;
String suffix = null;
if (filename == null) {
prefix = "download-";
suffix = "";
} else {
int pos = filename.lastIndexOf(".");
if (pos == -1) {
prefix = filename + "-";
} else {
prefix = filename.substring(0, pos) + "-";
suffix = filename.substring(pos);
}
// File.createTempFile requires the prefix to be at least three
characters long if (prefix.length() < 3) prefix = "download-"; }
if (tempFolderPath == null)
return File.createTempFile(prefix, suffix);
else
return File.createTempFile(prefix, suffix, new
File(tempFolderPath)); }
/**
@return ApiResponse<T>
*/
public
/**
@throws ApiException If fail to execute the call
*/
public
/**
@param callback ApiCallback<T>
*/
public
/**
@param callback ApiCallback
*/
@SuppressWarnings("unchecked")
public
@Override
public void onResponse(Response response) throws IOException {
T result;
try {
result = (T) handleResponse(response, returnType);
} catch (ApiException e) {
callback.onFailure(e, response.code(),
response.headers().toMultimap()); return; } callback.onSuccess(result, response.code(), response.headers().toMultimap()); } }); }
/**
@return Type
*/
public
/**
@throws ApiException If fail to serialize the request body object
*/
public Call buildCall(String path, String method, List
final String url = buildUrl(path, queryParams);
final Request.Builder reqBuilder = new Request.Builder().url(url);
processHeaderParams(headerParams, reqBuilder);
String contentType = (String) headerParams.get("Content-Type");
// ensuring a default content type
if (contentType == null) {
contentType = "application/json";
}
RequestBody reqBody;
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if ("application/x-www-form-urlencoded".equals(contentType))
{ reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); }
Request request = null;
if(progressRequestListener != null && reqBody != null) {
ProgressRequestBody progressRequestBody = new
ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); }
return httpClient.newCall(request);
}
/**
@return The full URL
*/
public String buildUrl(String path, List
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g.
"/posts?draft=1" String prefix = path.contains("?") ? "&" : "?"; for (Pair param : queryParams) { if (param.getValue() != null) { if (prefix != null) { url.append(prefix); prefix = null; } else { url.append("&"); } String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value)); } } }
return url.toString();
}
/**
* Set header parameters to the request builder, including default
headers. *
@param reqBuilder Reqeust.Builder */ public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) { for (Entry<String, String> param : headerParams.entrySet()) { reqBuilder.header(param.getKey(), parameterToString(param.getValue())); } for (Entry<String, String> header : defaultHeaderMap.entrySet()) { if (!headerParams.containsKey(header.getKey())) { reqBuilder.header(header.getKey(), parameterToString(header.getValue())); } } }
/**
@param headerParams Map of header parameters
*/
public void updateParamsForAuth(String[] authNames, List
/**
@return RequestBody */ public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) { FormEncodingBuilder formBuilder = new FormEncodingBuilder(); for (Entry<String, Object> param : formParams.entrySet()) { formBuilder.add(param.getKey(), parameterToString(param.getValue())); } return formBuilder.build(); }
/**
@return RequestBody */ public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) { MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); for (Entry<String, Object> param : formParams.entrySet()) { if (param.getValue() instanceof File) { File file = (File) param.getValue(); Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName()
/**
@return The guessed Content-Type */ public String guessContentTypeFromFile(File file) { String contentType = URLConnection.guessContentTypeFromName(file.getName()); if (contentType == null) { return "application/octet-stream"; } else { return contentType; } }
/**
Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. */ private void initDatetimeFormat() { String formatWithTimeZone = null; if (IS_ANDROID) { if (ANDROID_SDK_VERSION >= 18) { // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; } } else if (JAVA_VERSION >= 1.7) { // The time zone format "XXX" is available since Java 1.7 formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; } if (formatWithTimeZone != null) { this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); // NOTE: Use the system's default time zone (mainly for datetime formatting). } else { // Use a common format that works across all systems. this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Always use the UTC time zone as we are using a constant trailing "Z" here. this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } }
/**
verifyingSsl and sslCaCert. */ private void applySslSettings() { try { KeyManager[] keyManagers = null; TrustManager[] trustManagers = null; HostnameVerifier hostnameVerifier = null; if (!verifyingSsl) { TrustManager trustAll = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslContext = SSLContext.getInstance("TLS"); trustManagers = new TrustManager[]{ trustAll }; hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; } else if (sslCaCert != null) { char[] password = null; // Any password will work. CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert); if (certificates.isEmpty()) { throw new IllegalArgumentException("expected non-empty set of trusted certificates"); } KeyStore caKeyStore = newEmptyKeyStore(password); int index = 0; for (Certificate certificate : certificates) { String certificateAlias = "ca" + Integer.toString(index++); caKeyStore.setCertificateEntry(certificateAlias, certificate); } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(caKeyStore); trustManagers = trustManagerFactory.getTrustManagers(); }
if (keyManagers != null || trustManagers != null) {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new
SecureRandom());
httpClient.setSslSocketFactory(sslContext.getSocketFactory()); } else { httpClient.setSslSocketFactory(null); } httpClient.setHostnameVerifier(hostnameVerifier); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }
private KeyStore newEmptyKeyStore(char[] password) throws
GeneralSecurityException { try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, password); return keyStore; } catch (IOException e) { throw new AssertionError(e); } } }
And, I am calling somewhere like this but it's not carrying the authentication. I tried couple of approaches-
1)ApiClient apiClient = new ApiClient();
hba.setUsername("*");
hba.setPassword("**")
AddressesApi customerApi = new AddressesApi(apiClient);
ApiResponse<List
2)apiClient.addDefaultHeader("Authorization", "Authorization:Basic base64EncodedUser:Pass"); Did not work even I changed buildCall and added this.
String authNames2[] = {"basic"}; updateParamsForAuth(authNames2, queryParams, headerParams);
I am going clueless as how to pass credentials using swagger if producer does not define the securityConfig in swagger schema but still except a credentials to call its operations.
Please assist.
On Wed, May 31, 2017 at 11:00 PM, Paŭlo Ebermann notifications@github.com wrote:
Sorry, your issue fails to give any details which could be used to help you.
For which language are you generating stuff? (Please post the full command line, or maven plugin configuration, and the Swagger-Codegen version number.) Also, please include or link the API definition file (swagger/OpenAPI), either the full one or a reduced which still allows reproducing your problem. Then, please include the full code which is creating, setting up and using the client.
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/swagger-api/swagger-codegen/issues/5743#issuecomment-305259517, or mute the thread https://github.com/notifications/unsubscribe-auth/AaFtbITkM2eWcLhOUNnyKVUqWEosjZQAks5r_aOtgaJpZM4Nrpgw .
I have the same problem like above. Genereated code for java, using: java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -i https://developer.allegro.pl/swagger.yaml -g java -o samples/client/allegro -p pl.com.kams
Hi Team,
Consuming a restful service using swagger codegen 2.0 But its failing the authentication.
"swagger": "2.0", "info": { "version": "2.1.0", "title": "GeoES"
Schema does not have securityDefinitions: basic: type: basic description: HTTP Basic Authentication.
So, I tried changing Apiclient authantications map and added manually credentials. But no luck. HttpBasicAuth hba= new HttpBasicAuth();
I changed buildCall to allow but still It's not getting authenticated. Need Help !! String authNames2[] = {"basic"}; updateParamsForAuth(authNames2, queryParams, headerParams);
Thank you