Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ public void execute(Template.Fragment fragment, Writer writer) throws IOExceptio
@Override
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
final CopyContent copyContent = new CopyContent();
final CacheLambda.CacheContent cacheContent = new CacheLambda.CacheContent();

return super.addMustacheLambdas()
.put("camelcase_sanitize_param", new CamelCaseAndSanitizeLambda().generator(this).escapeAsParamName(true))
Expand All @@ -454,6 +455,9 @@ protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
.put("copyText", new CopyLambda(copyContent, WhiteSpaceStrategy.Strip, WhiteSpaceStrategy.StripLineBreakIfPresent))
.put("paste", new PasteLambda(copyContent, false))
.put("pasteOnce", new PasteLambda(copyContent, true))
.put("cache", new CacheLambda(cacheContent))
.put("recall", new RecallLambda(cacheContent, false))
.put("recallOnce", new RecallLambda(cacheContent, true))
.put("uniqueLines", new UniqueLambda("\n", false))
.put("unique", new UniqueLambda("\n", true))
.put("camel_case", new CamelCaseLambda())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1143,6 +1143,9 @@ public void addGenericHostSupportingFiles(final String clientPackageDir, final S

supportingFiles.add(new SupportingFile("IApi.mustache", sourceFolder + File.separator + packageName + File.separator + apiPackage(), getInterfacePrefix() + "Api.cs"));

String loggingFolder = sourceFolder + File.separator + packageName + File.separator + "Logging";
supportingFiles.add(new SupportingFile("libraries" + File.separator + GENERICHOST + File.separator + "RestLogEvents.mustache", loggingFolder, "RestLogEvents.cs"));

// extensions
String extensionsFolder = sourceFolder + File.separator + packageName + File.separator + "Extensions";
supportingFiles.add(new SupportingFile("IHttpClientBuilderExtensions.mustache", extensionsFolder, "IHttpClientBuilderExtensions.cs"));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.openapitools.codegen.templating.mustache;

import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template.Fragment;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
* Caches rendered text by key.
*
* Syntax:
* {{#cacheScope}}key|rendered text{{/cacheScope}}
*/
public class CacheLambda implements Mustache.Lambda {
public static class CacheContent {
public final Map<String, String> contentByKey = new HashMap<>();
}

private final CacheContent cacheContent;

public CacheLambda(CacheContent cacheContent) {
this.cacheContent = cacheContent;
}

@Override
public void execute(Fragment fragment, Writer writer) throws IOException {
String content = fragment.execute();

// Accept either "key|content" or a multiline form where the first line is the key.
int separatorIndex = content.indexOf('|');
if (separatorIndex < 0) {
int lineBreakIndex = findFirstLineBreakIndex(content);
if (lineBreakIndex >= 0) {
separatorIndex = lineBreakIndex;
}
}

if (separatorIndex < 0) {
throw new IllegalArgumentException("cacheScope requires 'key|content' or 'key\\ncontent'");
}

String key = content.substring(0, separatorIndex).trim();
if (key.isEmpty()) {
throw new IllegalArgumentException("cacheScope key cannot be empty");
}

int contentStartIndex = separatorIndex + 1;
// For CRLF, skip both '\r' and '\n'. For LF-only/CR-only, skip just one character.
if (separatorIndex < content.length() && content.charAt(separatorIndex) == '\r') {
if (contentStartIndex < content.length() && content.charAt(contentStartIndex) == '\n') {
contentStartIndex++;
}
}

this.cacheContent.contentByKey.put(key, content.substring(contentStartIndex));
}

private int findFirstLineBreakIndex(String content) {
// Keep this simple and cross-platform by checking all common line endings.
int unix = content.indexOf('\n');
int windows = content.indexOf('\r');

if (unix < 0) {
return windows;
}

if (windows < 0) {
return unix;
}

return Math.min(unix, windows);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.openapitools.codegen.templating.mustache;

import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template.Fragment;
import org.openapitools.codegen.templating.mustache.CacheLambda.CacheContent;

import java.io.IOException;
import java.io.Writer;

/**
* Writes rendered text that was previously cached by key.
*
* Syntax:
* {{#recallScope}}key{{/recallScope}}
*/
public class RecallLambda implements Mustache.Lambda {
private final CacheContent cacheContent;
private final boolean clear;

public RecallLambda(CacheContent cacheContent, boolean clear) {
this.cacheContent = cacheContent;
this.clear = clear;
}

@Override
public void execute(Fragment fragment, Writer writer) throws IOException {
String key = fragment.execute().trim();
if (key.isEmpty()) {
throw new IllegalArgumentException("recallScope key cannot be empty");
}

String content = this.cacheContent.contentByKey.get(key);
if (content == null) {
return;
}

if (this.clear) {
this.cacheContent.contentByKey.remove(key);
}

writer.write(content);
}
}
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
if (!suppressDefaultLog)
Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path);
Logger.LogInformation(RestLogEvents.ApiRequestCompleted, "{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path);
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
if (!suppressDefaultLog)
Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode);
Logger.LogError(RestLogEvents.ApiDeserializationFailed, exception, "An error occurred while deserializing the {code} response.", httpStatusCode);
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
if (!suppressDefaultLogLocalVar)
Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server.");
Logger.LogError(RestLogEvents.ApiRequestFailed, exceptionLocalVar, "An error occurred while sending the request to the server.");
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.Extensions.Logging;

namespace {{packageName}}.Logging
{
internal static partial class RestLogEvents
{
// 3000-3099: REST API transport and response processing
internal static readonly EventId ApiRequestCompleted = new EventId(3000, nameof(ApiRequestCompleted));
internal static readonly EventId ApiRequestFailed = new EventId(3001, nameof(ApiRequestFailed));
internal static readonly EventId ApiDeserializationFailed = new EventId(3002, nameof(ApiDeserializationFailed));
internal static readonly EventId ApiForbiddenWarning = new EventId(3003, nameof(ApiForbiddenWarning));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using {{packageName}}.{{clientPackage}};
using {{packageName}}.Logging;
{{#hasImport}}
using {{packageName}}.{{modelPackage}};
{{/hasImport}}
Expand Down Expand Up @@ -165,11 +166,6 @@ namespace {{packageName}}.{{apiPackage}}
{
private JsonSerializerOptions _jsonSerializerOptions;

/// <summary>
/// The logger factory
/// </summary>
public ILoggerFactory LoggerFactory { get; }

/// <summary>
/// The logger
/// </summary>
Expand Down Expand Up @@ -227,7 +223,7 @@ namespace {{packageName}}.{{apiPackage}}
/// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// </summary>
/// <returns></returns>
public {{classname}}(ILogger<{{classname}}> logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, {{classname}}Events {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}}{{#hasApiKeyMethods}},
public {{classname}}(ILogger<{{classname}}> logger, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, {{classname}}Events {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}}{{#hasApiKeyMethods}},
TokenProvider<ApiKeyToken> apiKeyProvider{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}},
TokenProvider<BearerToken> bearerTokenProvider{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}},
TokenProvider<BasicToken> basicTokenProvider{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}},
Expand All @@ -236,8 +232,7 @@ namespace {{packageName}}.{{apiPackage}}
{{packageName}}.{{clientPackage}}.CookieContainer cookieContainer{{/vendorExtensions.x-set-cookie}}{{/lambda.uniqueLines}}{{/operation}}{{/net80OrLater}})
{
_jsonSerializerOptions = jsonSerializerOptionsProvider.Options;
LoggerFactory = loggerFactory;
Logger = LoggerFactory.CreateLogger<{{classname}}>();
Logger = logger;
HttpClient = httpClient;
Events = {{#lambda.camelcase_sanitize_param}}{{classname}}Events{{/lambda.camelcase_sanitize_param}};{{#hasApiKeyMethods}}
ApiKeyProvider = apiKeyProvider;{{/hasApiKeyMethods}}{{#hasHttpBearerMethods}}
Expand Down Expand Up @@ -721,7 +716,6 @@ namespace {{packageName}}.{{apiPackage}}

using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false))
{
ILogger<{{#vendorExtensions.x-duplicates}}{{classname}}{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse> apiResponseLoggerLocalVar = LoggerFactory.CreateLogger<{{#vendorExtensions.x-duplicates}}{{classname}}{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse>();
{{#vendorExtensions.x-duplicates}}{{classname}}{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse apiResponseLocalVar;

switch ((int)httpResponseMessageLocalVar.StatusCode) {
Expand All @@ -736,7 +730,7 @@ namespace {{packageName}}.{{apiPackage}}
{
byte[] responseBytesArrayLocalVar = await httpResponseMessageLocalVar.Content.ReadAsByteArrayAsync({{#net60OrLater}}cancellationToken{{/net60OrLater}}).ConfigureAwait(false);
System.IO.Stream responseContentStreamLocalVar = new System.IO.MemoryStream(responseBytesArrayLocalVar);
apiResponseLocalVar = new{{^net60OrLater}} {{#vendorExtensions.x-duplicates}}{{classname}}{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse{{/net60OrLater}}(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentStreamLocalVar, "{{{path}}}", requestedAtLocalVar, _jsonSerializerOptions);
apiResponseLocalVar = new{{^net60OrLater}} {{#vendorExtensions.x-duplicates}}{{classname}}{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse{{/net60OrLater}}(Logger, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentStreamLocalVar, "{{{path}}}", requestedAtLocalVar, _jsonSerializerOptions);

break;
}
Expand All @@ -745,7 +739,7 @@ namespace {{packageName}}.{{apiPackage}}
{{/responses}}
default: {
string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync({{#net60OrLater}}cancellationToken{{/net60OrLater}}).ConfigureAwait(false);
apiResponseLocalVar = new{{^net60OrLater}} {{#vendorExtensions.x-duplicates}}{{classname}}{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse{{/net60OrLater}}(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "{{{path}}}", requestedAtLocalVar, _jsonSerializerOptions);
apiResponseLocalVar = new{{^net60OrLater}} {{#vendorExtensions.x-duplicates}}{{classname}}{{/vendorExtensions.x-duplicates}}{{operationId}}ApiResponse{{/net60OrLater}}(Logger, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "{{{path}}}", requestedAtLocalVar, _jsonSerializerOptions);

break;
}
Expand Down Expand Up @@ -815,6 +809,12 @@ namespace {{packageName}}.{{apiPackage}}
{{/vendorExtensions.x-duplicates}}
{{/lambda.trim}}
{{/lambda.copy}}
{{#lambda.cache}}
classname
{{#lambda.trim}}
{{classname}}
{{/lambda.trim}}
{{/lambda.cache}}
{{#responses}}
{{#-first}}

Expand All @@ -826,7 +826,7 @@ namespace {{packageName}}.{{apiPackage}}
/// <summary>
/// The logger
/// </summary>
public ILogger<{{#lambda.paste}}{{/lambda.paste}}{{operationId}}ApiResponse> Logger { get; }
public ILogger<{{#lambda.recall}}classname{{/lambda.recall}}> Logger { get; }

/// <summary>
/// The <see cref="{{#lambda.paste}}{{/lambda.paste}}{{operationId}}ApiResponse"/>
Expand All @@ -838,7 +838,7 @@ namespace {{packageName}}.{{apiPackage}}
/// <param name="path"></param>
/// <param name="requestedAt"></param>
/// <param name="jsonSerializerOptions"></param>
public {{#lambda.paste}}{{/lambda.paste}}{{operationId}}ApiResponse(ILogger<{{#lambda.paste}}{{/lambda.paste}}{{operationId}}ApiResponse> logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions)
public {{#lambda.paste}}{{/lambda.paste}}{{operationId}}ApiResponse(ILogger<{{classname}}> logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions)
{
Logger = logger;
OnCreated(httpRequestMessage, httpResponseMessage);
Expand All @@ -854,7 +854,7 @@ namespace {{packageName}}.{{apiPackage}}
/// <param name="path"></param>
/// <param name="requestedAt"></param>
/// <param name="jsonSerializerOptions"></param>
public {{#lambda.paste}}{{/lambda.paste}}{{operationId}}ApiResponse(ILogger<{{#lambda.paste}}{{/lambda.paste}}{{operationId}}ApiResponse> logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions)
public {{#lambda.paste}}{{/lambda.paste}}{{operationId}}ApiResponse(ILogger<{{classname}}> logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions)
{
Logger = logger;
OnCreated(httpRequestMessage, httpResponseMessage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ src/Org.OpenAPITools/Client/TokenProvider`1.cs
src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs
src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs
src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs
src/Org.OpenAPITools/Logging/RestLogEvents.cs
src/Org.OpenAPITools/Model/AreaCode.cs
src/Org.OpenAPITools/Model/MarineAreaCode.cs
src/Org.OpenAPITools/Model/StateTerritoryCode.cs
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.Extensions.Logging;

namespace Org.OpenAPITools.Logging
{
internal static partial class RestLogEvents
{
// 3000-3099: REST API transport and response processing
internal static readonly EventId ApiRequestCompleted = new EventId(3000, nameof(ApiRequestCompleted));
internal static readonly EventId ApiRequestFailed = new EventId(3001, nameof(ApiRequestFailed));
internal static readonly EventId ApiDeserializationFailed = new EventId(3002, nameof(ApiDeserializationFailed));
internal static readonly EventId ApiForbiddenWarning = new EventId(3003, nameof(ApiForbiddenWarning));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ src/Org.OpenAPITools/Client/TokenProvider`1.cs
src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs
src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs
src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs
src/Org.OpenAPITools/Logging/RestLogEvents.cs
src/Org.OpenAPITools/Model/HelloWorldPostRequest.cs
src/Org.OpenAPITools/Org.OpenAPITools.csproj
src/Org.OpenAPITools/README.md
Loading
Loading