swagger3 default value of request header - swagger-3.0

I have a problem using springboot2.7.3 to integrate swagger3.0.0
I'm trying to set the request header to include a default value, but it didn't work anyway, can you help me?
Below is my configuration:
List<RequestParameter> globalRequestParameters = new ArrayList<RequestParameter>() {{
add(new RequestParameterBuilder()
.name("a")
.description("Token")
.in(ParameterType.HEADER)
.required(true)
.example(new ExampleBuilder()
.externalValue("a")
.summary("default-value-2")
.value("default-value-3").build())
.build());
add(new RequestParameterBuilder()
.name("b")
.query(q -> q.model(n -> n.scalarModel(ScalarType.STRING)).defaultValue("default-value"))
.description("Token")
.in(ParameterType.HEADER)
.required(true)
.build());
}};
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.groupName("Normal")
.enable(true)
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
//.apis(RequestHandlerSelectors.basePackage("com.tcoding.demo.helloworld.controller"))
.paths(PathSelectors.any())
.build()
.globalRequestParameters(globalRequestParameters);
enter image description here

Related

Updating Data on a OneNote Page Error, "Timeouts are not supported on this stream"

I have the goal of being able to programmatically update OneNote page data using C#. The Microsoft Graph API reference documentation suggests this can only be done by page element, not by page, and gives the following C# Graph SDK example:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(#"[
{
'target':'#para-id',
'action':'insert',
'position':'before',
'content':'<img src=""image-url-or-part-name"" alt=""image-alt-text"" />'
},
{
'target':'#list-id',
'action':'append',
'content':'<li>new-page-content</li>'
}
]
"));
var pages = new OnenotePage();
pages.Content = stream;
await graphClient.Me.Onenote.Pages["{onenotePage-id}"]
.Request()
.UpdateAsync(pages);
Below is the relevant snippet of my code:
GraphServiceClient client; // authenticated service client
CancellationToken cancellationToken; // a cancellation token
string userId; // identifier of user whose page contains the paragraph to be updated
string pageId; // identifier of page containing paragraph to be updated
string paragraphId; // identifier of paragraph to be updated
string filePath; // location of text file containing updated paragraph data
await client.Users[userId].Onenote.Pages[pageId]
.Request()
.UpdateAsync(new OnenotePage
{
Content = new MemoryStream(Encoding.UTF8.GetBytes(
// [
// {
// 'target':'{paragraphId}',
// 'action':'replace',
// 'content':'<p>{File.ReadAllText(filePath)}</p>'
// }
// ]
$"[{{'target':'{paragraphId}','action':'replace','content':'<p>{File.ReadAllText(filePath)}</p>'}}]"))
}, cancellationToken);
Microsoft's REST documentation includes PATCH /users/{id | userPrincipalName}/onenote/pages/{id}/content as a valid HTTP request, so my above code seems like it should work, even though it doesn't use the .Me option as in their example. For some reason, however, my code keeps throwing an InvalidOperationException, declaring that, "Timeouts are not supported on this stream," whenever it tries to execute the await command. Below are the details of the exception:
System.InvalidOperationException
HResult=0x80131509
Message=Timeouts are not supported on this stream.
Source=System.Private.CoreLib
StackTrace:
at System.IO.Stream.get_ReadTimeout()
When I try to run the raw REST command on the official Graph Explorer, I get a No Content - 204 message, confirming that the PATCH worked. Please note again, however, that I am instead simply using the C# MS Graph SDK.
Where am I going wrong? How can I accomplish my goal?
EDIT: I still don't have a solution to the SDK throwing InvalidOperationExceptions at me, and thus do not consider this matter resolved, but since the API seems to be working just fine, I went ahead and found a workaround to accomplish my goal. Posted here, in case anyone else encounters my same issue and needs something that works.
GraphServiceClient client; // authenticated service client
CancellationToken cancellationToken; // a cancellation token
string userId; // identifier of user whose page contains the paragraph to be updated
string pageId; // identifier of page containing paragraph to be updated
string paragraphId; // identifier of paragraph to be updated
string filePath; // location of text file containing updated paragraph data
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Patch,
client.Users[userId].Onenote.Pages[pageId].Content
.Request()
.RequestUrl)
{
Content = new StringContent(
// [
// {
// 'target':'{paragraphId}',
// 'action':'replace',
// 'content':'<p>{File.ReadAllText(filePath)}</p>'
// }
// ]
$"[{{'target':'{paragraphId}','action':'replace','content':'<p>{File.ReadAllText(filePath)}</p>'}}]",
Encoding.UTF8,
"application/json")
};
await client.AuthenticationProvider.AuthenticateRequestAsync(request);
await client.HttpProvider.SendAsync(request);

Google OAuth2 Java code asking permissions every time

I am using the following with a google-client-secret.json file and trying to run this as just a java application in eclipse. I want to store the permissions so once I accept the permissions it doesn't ask again. Right now it is prompting everytime. After that everything works as expected and writes to my google sheets.
public static Credential authorizeSHEETS() throws IOException, GeneralSecurityException {
File fileIn = new File("src/jg/sos/orders/google-sheets-client-secret.json");
// InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("src/jg/sos/orders/google-sheets-client-secret.json");
InputStream in = new FileInputStream(fileIn);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory())
.setAccessType("offline").setApprovalPrompt("auto").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return credential;
}
Any ideas on how to only have this prompt me the first time for permissions, then the next time I run this it will not?
Thanks for the help!
JJ
So found an answer to this in case anyone comes across. I used a service account instead, and downloaded the json file for it and placed in my project.
Then I just referenced it instead, and saved the token using DataStoreFactory as below:
public static Credential authorizeSHEETS() throws IOException, GeneralSecurityException {
File fileIn = new File("src/jg/sos/orders/google-sheets-client-secret.json");
// InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("src/jg/sos/orders/google-sheets-client-secret.json");
InputStream in = new FileInputStream(fileIn);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new File("src/jg/sos/orders"));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes)
.setDataStoreFactory(dataStoreFactory)
.setAccessType("offline").setApprovalPrompt("auto").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
System.out.println("token" + credential.getAccessToken());
return credential;
}

How can i set credential charset with httpclient 4.3

AuthPNames.CREDENTIAL_CHARSET is deprecated!?
I don't know how to interpret:
(4.3) use RequestConfig and constructor parameters of
AuthSchemeProviders.
From the documentation.
Can anyone give me an example?
Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactory(Consts.UTF_8))
.register(AuthSchemes.DIGEST, new DigestSchemeFactory(Consts.UTF_8))
.register(AuthSchemes.NTLM, new NTLMSchemeFactory())
.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory())
.build();
CloseableHttpClient client = HttpClients.custom()
.setDefaultAuthSchemeRegistry(authSchemeRegistry)
.build();

Xamarin iOS add Content-Length header to HttpClient throws error

I am attempting to use HttpClient to upload a file to Microsoft Azure Blob Storage via their REST api in Xamarin.iOS. It's been going alright until now. Every time I try to add Content-Length header to the client I get this error:
System.InvalidOperationException: Content-Length\n at System.Net.Http.Headers.HttpHeaders.CheckName (System.String name) [0x0005f] in /Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs:253 \n at System.Net.Http.Headers.HttpHeaders.Add (System.String name, IEnumerable`1 values) [0x00011] in /Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs:171 \n at System.Net.Http.Headers.HttpHeaders.Add (System.String name, System.String value) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs:163
This is my code for creating the HttpClient
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-Length", blobLength.ToString()); // Error here
client.DefaultRequestHeaders.Add("x-ms-date", dateInRfc1123Format);
client.DefaultRequestHeaders.Add("x-ms-version", msVersion);
Debug.WriteLine("Added all headers except Authorization");
client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
Debug.WriteLine("Added Authorization header");
//logRequest(requestContent, uri);
Debug.WriteLine("created new http client");
HttpContent requestContent = new ByteArrayContent(blobckContent);
HttpResponseMessage response = await client.PutAsync(uri, requestContent);
I tried using TryAddWithoutValidation instead of Add:
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Length", blobLength.ToString());
The error doesn't get thrown but the header still doesn't get added.
Any help would be great.
Here's the inner workings of CheckName(), which is throwing the exception. You can find the source here: https://github.com/mono/mono/blob/master/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs
HeaderInfo CheckName (string name)
{
if (string.IsNullOrEmpty (name))
throw new ArgumentException ("name");
Parser.Token.Check (name);
HeaderInfo headerInfo;
if (known_headers.TryGetValue (name, out headerInfo) && (headerInfo.HeaderKind & HeaderKind) == 0) {
if (HeaderKind != HttpHeaderKind.None && ((HeaderKind | headerInfo.HeaderKind) & HttpHeaderKind.Content) != 0)
throw new InvalidOperationException (name);
return null;
}
return headerInfo;
}
After looking at the full source file:
It looks like Content-Length is in the collection of known_headers.
Also looks like the internal type of the Content-Length header value is a long. But the Add() method only take a string for the value, which get's parsed to a long. Is the string value that you're passing for the Content-Length value a valid long?

'identity.api.rackspacecloud.com' randomly throws 'The remote name could not be resolved' exception

I am accessing Rackspace Cloud APIs.
I have one api call which authenticates me on the rackspace cloud.
The method works perfectly, however, from time to time, i get this exception, randomly :
The remote name could not be resolved: 'identity.api.rackspacecloud.com'
When i am not getting this exception, the method returns the expected result, as it should be.
Is there any specific reason why it does this?
Here is my .net code:
private async Task<XDocument> AuthenticateAsync()
{
XNamespace ns = "http://docs.rackspace.com/identity/api/ext/RAX-KSKEY/v1.0";
XDocument doc =
new XDocument(
new XDeclaration("1.0", "UTF-8", "Yes"),
new XElement("auth",
new XElement(ns + "apiKeyCredentials",
new XAttribute("username", "the userName"),
new XAttribute("apiKey", "the apiKey")
)
)
);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
StringContent content = new StringContent(doc.ToString(), Encoding.UTF8, "application/xml");
// i randomly get "The remote name could not be resolved" exception
HttpResponseMessage response = await client.PostAsync("https://identity.api.rackspacecloud.com/v2.0/tokens", content);
response.EnsureSuccessStatusCode();
string stringResponse = await response.Content.ReadAsStringAsync();
return XDocument.Parse(stringResponse);
}
}
This certainly sounds like a DNS failure. Can you configure your machine to use the Google DNS servers and try again?

Resources