Skip to content

Commit

Permalink
chore(citrus-openapi): review and code cleanup
Browse files Browse the repository at this point in the history
pr: #1224

`citrus-openapi` module.
  • Loading branch information
bbortt committed Oct 28, 2024
1 parent 18ae70b commit e8afc7b
Show file tree
Hide file tree
Showing 139 changed files with 7,323 additions and 7,608 deletions.
1 change: 0 additions & 1 deletion connectors/citrus-openapi/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
<dependency>
<groupId>com.atlassian.oai</groupId>
<artifactId>swagger-request-validator-core</artifactId>
<version>${swagger-request-validator.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package org.citrusframework.openapi;

public abstract class OpenApiConstants {
public final class OpenApiConstants {

public static final String TYPE_ARRAY = "array";
public static final String TYPE_BOOLEAN = "boolean";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package org.citrusframework.openapi;

import jakarta.annotation.Nullable;
import org.citrusframework.repository.BaseRepository;
import org.citrusframework.spi.Resource;
import org.slf4j.Logger;
Expand All @@ -25,11 +26,12 @@
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
* OpenApi repository holding a set of {@link OpenApiSpecification} known in the test scope.
*
Expand Down Expand Up @@ -60,50 +62,6 @@ public OpenApiRepository() {
super(DEFAULT_NAME);
}

public String getRootContextPath() {
return rootContextPath;
}

public void setRootContextPath(String rootContextPath) {
this.rootContextPath = rootContextPath;
}

public boolean isRequestValidationEnabled() {
return requestValidationEnabled;
}

public void setRequestValidationEnabled(boolean requestValidationEnabled) {
this.requestValidationEnabled = requestValidationEnabled;
}

public boolean isResponseValidationEnabled() {
return responseValidationEnabled;
}

public void setResponseValidationEnabled(boolean responseValidationEnabled) {
this.responseValidationEnabled = responseValidationEnabled;
}

/**
* Adds an OpenAPI Specification specified by the given resource to the repository.
* If an alias is determined from the resource name, it is added to the specification.
*
* @param openApiResource the resource to add as an OpenAPI specification
*/
@Override
public void addRepository(Resource openApiResource) {
OpenApiSpecification openApiSpecification = OpenApiSpecification.from(openApiResource);
determineResourceAlias(openApiResource).ifPresent(openApiSpecification::addAlias);
openApiSpecification.setApiRequestValidationEnabled(requestValidationEnabled);
openApiSpecification.setApiResponseValidationEnabled(responseValidationEnabled);
openApiSpecification.setRootContextPath(rootContextPath);

this.openApiSpecifications.add(openApiSpecification);

OpenApiSpecificationProcessor.lookup().values()
.forEach(processor -> processor.process(openApiSpecification));
}

/**
* @param openApiResource the OpenAPI resource from which to determine the alias
* @return an {@code Optional} containing the resource alias if it can be resolved, otherwise an empty {@code Optional}
Expand All @@ -117,7 +75,7 @@ static Optional<String> determineResourceAlias(Resource openApiResource) {
if (file != null) {
resourceAlias = file.getName();
int index = resourceAlias.lastIndexOf(".");
if (index != -1 && index != resourceAlias.length()-1) {
if (index != -1 && index != resourceAlias.length() - 1) {
resourceAlias = resourceAlias.substring(0, index);
}
return Optional.of(resourceAlias);
Expand All @@ -129,14 +87,14 @@ static Optional<String> determineResourceAlias(Resource openApiResource) {
try {
URL url = openApiResource.getURL();
if (url != null) {
String urlString = URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8).replace("\\","/");
String urlString = URLDecoder.decode(url.getPath(), UTF_8).replace("\\", "/");
int index = urlString.lastIndexOf("/");
resourceAlias = urlString;
if (index != -1 && index != urlString.length()-1) {
resourceAlias = resourceAlias.substring(index+1);
if (index != -1 && index != urlString.length() - 1) {
resourceAlias = resourceAlias.substring(index + 1);
}
index = resourceAlias.lastIndexOf(".");
if (index != -1 && index != resourceAlias.length()-1) {
if (index != -1 && index != resourceAlias.length() - 1) {
resourceAlias = resourceAlias.substring(0, index);
}

Expand All @@ -152,12 +110,60 @@ public List<OpenApiSpecification> getOpenApiSpecifications() {
return openApiSpecifications;
}

public String getRootContextPath() {
return rootContextPath;
}

public void setRootContextPath(String rootContextPath) {
this.rootContextPath = rootContextPath;
}

public boolean isRequestValidationEnabled() {
return requestValidationEnabled;
}

public void setRequestValidationEnabled(boolean requestValidationEnabled) {
this.requestValidationEnabled = requestValidationEnabled;
}

public boolean isResponseValidationEnabled() {
return responseValidationEnabled;
}

public void setResponseValidationEnabled(boolean responseValidationEnabled) {
this.responseValidationEnabled = responseValidationEnabled;
}

/**
* Adds an OpenAPI Specification specified by the given resource to the repository.
* If an alias is determined from the resource name, it is added to the specification.
*
* @param openApiResource the resource to add as an OpenAPI specification
*/
@Override
public void addRepository(Resource openApiResource) {
OpenApiSpecification openApiSpecification = OpenApiSpecification.from(openApiResource);
determineResourceAlias(openApiResource).ifPresent(openApiSpecification::addAlias);
openApiSpecification.setApiRequestValidationEnabled(requestValidationEnabled);
openApiSpecification.setApiResponseValidationEnabled(responseValidationEnabled);
openApiSpecification.setRootContextPath(rootContextPath);

this.openApiSpecifications.add(openApiSpecification);

OpenApiSpecificationProcessor.lookup()
.values()
.forEach(processor -> processor.process(openApiSpecification));
}

public OpenApiRepository locations(List<String> locations) {
setLocations(locations);
return this;
}

public OpenApiSpecification openApi(String alias) {
return getOpenApiSpecifications().stream().filter(spec -> spec.getAliases().contains(alias)).findFirst().orElse(null);
public @Nullable OpenApiSpecification openApi(String alias) {
return getOpenApiSpecifications().stream()
.filter(spec -> spec.getAliases().contains(alias))
.findFirst()
.orElse(null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,32 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import io.apicurio.datamodels.Library;
import io.apicurio.datamodels.openapi.models.OasDocument;
import java.io.InputStream;
import java.net.URLConnection;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.TrustAllStrategy;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.ssl.SSLContexts;
import org.citrusframework.exceptions.CitrusRuntimeException;
import org.citrusframework.spi.Resource;
import org.citrusframework.util.FileUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

import static javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier;
import static javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory;
import static org.apache.hc.core5.http.HttpHeaders.ACCEPT;
import static org.apache.hc.core5.http.Method.GET;
import static org.citrusframework.util.FileUtils.getFileResource;
import static org.citrusframework.util.FileUtils.readToString;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

/**
* Loads Open API specifications from different locations like file resource or web resource.
*/
Expand All @@ -63,15 +67,15 @@ private OpenApiResourceLoader() {
* Loads the specification from a file resource. Either classpath or file system resource path is supported.
*/
public static OasDocument fromFile(String resource) {
return fromFile(FileUtils.getFileResource(resource), OAS_RESOLVER);
return fromFile(getFileResource(resource), OAS_RESOLVER);
}

/**
* Loads the raw specification from a file resource. Either classpath or file system resource path is supported.
*/
public static String rawFromFile(String resource) {
return fromFile(FileUtils.getFileResource(resource),
RAW_RESOLVER);
return fromFile(getFileResource(resource),
RAW_RESOLVER);
}

/**
Expand All @@ -90,7 +94,7 @@ public static String rawFromFile(Resource resource) {

private static <T> T fromFile(Resource resource, Resolver<T> resolver) {
try {
return resolve(FileUtils.readToString(resource), resolver);
return resolve(readToString(resource), resolver);
} catch (IOException e) {
throw new IllegalStateException("Failed to parse Open API specification: " + resource, e);
}
Expand All @@ -111,30 +115,29 @@ public static String rawFromWebResource(URL url) {
}

private static <T> T fromWebResource(URL url, Resolver<T> resolver) {
URLConnection con = null;
URLConnection connection = null;
try {
con = url.openConnection();
connection = url.openConnection();

if (con instanceof HttpURLConnection httpURLConnection) {
httpURLConnection.setRequestMethod(HttpMethod.GET.name());
con.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
if (connection instanceof HttpURLConnection httpURLConnection) {
httpURLConnection.setRequestMethod(GET.name());
connection.setRequestProperty(ACCEPT, APPLICATION_JSON_VALUE);

int status = httpURLConnection.getResponseCode();
if (status > 299) {
throw new IllegalStateException(
"Failed to retrieve Open API specification: " + url,
new IOException(FileUtils.readToString(httpURLConnection.getErrorStream())));
"Failed to retrieve Open API specification: " + url,
new IOException(readToString(httpURLConnection.getErrorStream())));
}
}

try (InputStream inputStream = con.getInputStream()) {
return resolve(FileUtils.readToString(inputStream), resolver);
try (InputStream inputStream = connection.getInputStream()) {
return resolve(readToString(inputStream), resolver);
}

} catch (IOException e) {
throw new IllegalStateException("Failed to retrieve Open API specification: " + url, e);
} finally {
if (con instanceof HttpURLConnection httpURLConnection) {
if (connection instanceof HttpURLConnection httpURLConnection) {
httpURLConnection.disconnect();
}
}
Expand All @@ -157,34 +160,34 @@ public static String rawFromSecuredWebResource(URL url) {
private static <T> T fromSecuredWebResource(URL url, Resolver<T> resolver) {
Objects.requireNonNull(url);

HttpsURLConnection con = null;
HttpsURLConnection connection = null;
try {
SSLContext sslcontext = SSLContexts
.custom()
.loadTrustMaterial(TrustAllStrategy.INSTANCE)
.build();
.custom()
.loadTrustMaterial(TrustAllStrategy.INSTANCE)
.build();

HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);

con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod(HttpMethod.GET.name());
con.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod(GET.name());
connection.setRequestProperty(ACCEPT, APPLICATION_JSON_VALUE);

int status = con.getResponseCode();
int status = connection.getResponseCode();
if (status > 299) {
throw new IllegalStateException("Failed to retrieve Open API specification: " + url,
new IOException(FileUtils.readToString(con.getErrorStream())));
new IOException(readToString(connection.getErrorStream())));
} else {
return resolve(FileUtils.readToString(con.getInputStream()), resolver);
return resolve(readToString(connection.getInputStream()), resolver);
}
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new IllegalStateException("Failed to create https client for ssl connection", e);
} catch (IOException e) {
throw new IllegalStateException("Failed to retrieve Open API specification: " + url, e);
} finally {
if (con != null) {
con.disconnect();
if (connection != null) {
connection.disconnect();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,23 @@ private OpenApiSettings() {

public static boolean isGenerateOptionalFieldsGlobally() {
return parseBoolean(System.getProperty(GENERATE_OPTIONAL_FIELDS_PROPERTY, System.getenv(GENERATE_OPTIONAL_FIELDS_ENV) != null ?
System.getenv(GENERATE_OPTIONAL_FIELDS_ENV) : "true"));
System.getenv(GENERATE_OPTIONAL_FIELDS_ENV) : "true"));
}

public static boolean isValidateOptionalFieldsGlobally() {
return parseBoolean(System.getProperty(VALIDATE_OPTIONAL_FIELDS_PROPERTY, System.getenv(VALIDATE_OPTIONAL_FIELDS_ENV) != null ?
System.getenv(VALIDATE_OPTIONAL_FIELDS_ENV) : "true"));
System.getenv(VALIDATE_OPTIONAL_FIELDS_ENV) : "true"));
}

public static boolean isRequestValidationEnabledGlobally() {
return parseBoolean(System.getProperty(
REQUEST_VALIDATION_ENABLED_PROPERTY, System.getenv(REQUEST_VALIDATION_ENABLED_ENV) != null ?
System.getenv(REQUEST_VALIDATION_ENABLED_ENV) : "true"));
REQUEST_VALIDATION_ENABLED_PROPERTY, System.getenv(REQUEST_VALIDATION_ENABLED_ENV) != null ?
System.getenv(REQUEST_VALIDATION_ENABLED_ENV) : "true"));
}

public static boolean isResponseValidationEnabledGlobally() {
return parseBoolean(System.getProperty(
RESPONSE_VALIDATION_ENABLED_PROPERTY, System.getenv(RESPONSE_VALIDATION_ENABLED_ENV) != null ?
System.getenv(RESPONSE_VALIDATION_ENABLED_ENV) : "true"));
RESPONSE_VALIDATION_ENABLED_PROPERTY, System.getenv(RESPONSE_VALIDATION_ENABLED_ENV) != null ?
System.getenv(RESPONSE_VALIDATION_ENABLED_ENV) : "true"));
}
}
Loading

0 comments on commit e8afc7b

Please sign in to comment.