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
18 changes: 8 additions & 10 deletions cwms-data-api/src/main/java/cwms/cda/ApiServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@

package cwms.cda;

import cwms.cda.api.PublishedController;
import static cwms.cda.api.Controllers.CONTRACT_NAME;
import static cwms.cda.api.Controllers.LOCATION_ID;
import static cwms.cda.api.Controllers.NAME;
import static cwms.cda.api.Controllers.OFFICE;
import static cwms.cda.api.Controllers.PROJECT_ID;
import static cwms.cda.api.Controllers.RATING_ID;
import static cwms.cda.api.Controllers.WATER_USER;
import static cwms.cda.openapi.ExampleUtils.addEndpointExamples;
import static io.javalin.apibuilder.ApiBuilder.crud;
import static io.javalin.apibuilder.ApiBuilder.delete;
import static io.javalin.apibuilder.ApiBuilder.get;
Expand Down Expand Up @@ -78,13 +78,13 @@
import cwms.cda.api.PoolController;
import cwms.cda.api.ProjectController;
import cwms.cda.api.PropertyController;
import cwms.cda.api.PublishedController;
import cwms.cda.api.SpecifiedLevelController;
import cwms.cda.api.StandardTextController;
import cwms.cda.api.StateController;
import cwms.cda.api.StreamController;
import cwms.cda.api.StreamLocationController;
import cwms.cda.api.StreamReachController;
import cwms.cda.api.VerticalDatumController;
import cwms.cda.api.TextTimeSeriesController;
import cwms.cda.api.TextTimeSeriesValueController;
import cwms.cda.api.TimeSeriesCategoryController;
Expand All @@ -100,6 +100,7 @@
import cwms.cda.api.TurbineController;
import cwms.cda.api.UnitsController;
import cwms.cda.api.UpstreamLocationsGetController;
import cwms.cda.api.VerticalDatumController;
import cwms.cda.api.auth.ApiKeyController;
import cwms.cda.api.auth.users.UserProfileController;
import cwms.cda.api.auth.users.UsersController;
Expand Down Expand Up @@ -169,12 +170,16 @@
import cwms.cda.api.watersupply.WaterUserUpdateController;
import cwms.cda.data.dao.JooqDao;
import cwms.cda.data.dao.rss.QueueManager;
import cwms.cda.data.dto.csv.CwmsCsvDTO;
import cwms.cda.formatters.Formats;
import cwms.cda.formatters.csv.CsvExampleGenerator;
import cwms.cda.security.Authenticator;
import cwms.cda.security.CdaAccessManager;
import cwms.cda.security.DataApiPrincipal;
import cwms.cda.security.MissingRolesException;
import cwms.cda.security.Role;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;
import io.javalin.Javalin;
import io.javalin.apibuilder.CrudFunction;
import io.javalin.apibuilder.CrudHandler;
Expand All @@ -185,10 +190,7 @@
import io.javalin.core.validation.JavalinValidation;
import io.javalin.http.BadRequestResponse;
import io.javalin.http.Handler;
import io.javalin.http.HttpResponseException;
import io.javalin.http.JavalinServlet;
import cwms.cda.data.dto.csv.CwmsCsvDTO;
import cwms.cda.formatters.csv.CsvExampleGenerator;
import io.javalin.plugin.openapi.OpenApiOptions;
import io.javalin.plugin.openapi.OpenApiPlugin;
import io.opentelemetry.api.trace.Span;
Expand Down Expand Up @@ -224,14 +226,11 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.http.entity.ContentType;
import org.jetbrains.annotations.NotNull;
import org.jooq.exception.DataAccessException;
import org.owasp.html.HtmlPolicyBuilder;
import org.owasp.html.PolicyFactory;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;


/**
Expand Down Expand Up @@ -1008,8 +1007,8 @@ private void getOpenApiOptions(JavalinConfig config) {
);
})
.activateAnnotationScanningFor("cwms.cda.api");
addEndpointExamples(ops);
config.registerPlugin(new OpenApiPlugin(ops));

}

private static void setSecurityRequirements(String key, PathItem path,List<SecurityRequirement> secReqs) {
Expand Down Expand Up @@ -1062,5 +1061,4 @@ public static String officeFromContext(String contextPath) {
}
return System.getProperty(DEFAULT_OFFICE_KEY, office).toUpperCase();
}

}
132 changes: 132 additions & 0 deletions cwms-data-api/src/main/java/cwms/cda/openapi/ExampleUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
*
* MIT License
*
* Copyright (c) 2026 Hydrologic Engineering Center
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE
* SOFTWARE.
*/

package cwms.cda.openapi;

import cwms.cda.ApiServlet;
import cwms.cda.data.dto.CwmsDTOBase;
import cwms.cda.data.dto.locationlevel.ConstantLocationLevel;
import cwms.cda.data.dto.locationlevel.LocationLevel;
import cwms.cda.data.dto.locationlevel.SeasonalLocationLevel;
import cwms.cda.data.dto.locationlevel.TimeSeriesLocationLevel;
import cwms.cda.data.dto.locationlevel.VirtualLocationLevel;
import cwms.cda.formatters.Formats;
import io.javalin.plugin.openapi.OpenApiOptions;
import io.swagger.v3.oas.models.examples.Example;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.IOUtils;

public final class ExampleUtils {
private ExampleUtils() {
throw new IllegalStateException("Utility class");
}

/**
* Method to add specific input examples to API endpoints as defaults.
* Can be overridden with controller annotations.
* Primarily for use with endpoints that accept multiple classes as input and cannot be represented via annotations.
* Current annotation limitations are due to legacy Javalin library.
*
* @param ops the OpenApiOptions object to add the examples to.
*/
public static void addEndpointExamples(OpenApiOptions ops) {
String swaggerPath = "/swagger-docs";
for (EndpointExamples endpoint : EndpointExamples.values()) {
endpoint.getExamples().forEach(config ->
ops.path(swaggerPath)
.addExample(config.targetClass, config.displayName,
buildExample(config.exampleClass, config.resourcePath))
);
}
}

/**
* Builds an example object for the given class and resource path.
* @param exampleClass the class of the example object
* @param path the path to the example resource
* @return Example object
*/
private static Example buildExample(Class<? extends CwmsDTOBase> exampleClass, String path) {
cwms.cda.formatters.ContentType contentType = Formats.parseHeader(Formats.JSON, exampleClass);
Example example = new Example();
try (InputStream stream = ApiServlet.class.getClassLoader().getResourceAsStream(path)) {
if (stream == null) {
throw new IllegalArgumentException("Unable to find example file: " + path);
}
String ex = IOUtils.toString(stream, StandardCharsets.UTF_8);
ex = Formats.format(contentType, Formats.parseContent(contentType, ex, exampleClass));
example.value(ex);
} catch (IOException ex) {
throw new IllegalStateException("Unable to load example file: " + path, ex);
}
return example;
}

// Enum to define example configurations by endpoint
// Add examples here for other endpoints
private enum EndpointExamples {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is certainly fine for now... but let's all agree this will grow insanely and longer term we probably want something like annotations on the DTOs that can be looked up and contain links to relevant data.

LEVELS(Arrays.asList(
new ExampleConfig(LocationLevel.class, "Constant Location Level",
ConstantLocationLevel.class, "cwms/cda/data/levels/levels_constant_create.json"),
new ExampleConfig(LocationLevel.class, "Seasonal Location Level",
SeasonalLocationLevel.class, "cwms/cda/data/levels/levels_seasonal_create.json"),
new ExampleConfig(LocationLevel.class, "Timeseries Location Level",
TimeSeriesLocationLevel.class, "cwms/cda/data/levels/levels_timeseries_create.json"),
new ExampleConfig(LocationLevel.class, "Virtual Location Level",
VirtualLocationLevel.class, "cwms/cda/data/levels/levels_virtual_create.json")
));
// Add more endpoints as needed

private final List<ExampleConfig> examples;

EndpointExamples(List<ExampleConfig> examples) {
this.examples = examples;
}

private List<ExampleConfig> getExamples() {
return examples;
}
}

private static class ExampleConfig {
private final Class<? extends CwmsDTOBase> targetClass;
private final String displayName;
private final Class<? extends CwmsDTOBase> exampleClass;
private final String resourcePath;

private ExampleConfig(Class<? extends CwmsDTOBase> targetClass, String displayName,
Class<? extends CwmsDTOBase> exampleClass, String resourcePath) {
this.targetClass = targetClass;
this.displayName = displayName;
this.exampleClass = exampleClass;
this.resourcePath = resourcePath;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"constant-value": 10,
"level-units-id": "ft",
"level-date": "2008-12-03T10:15:30+01:00[UTC]",
"level-comment": "Lowest Point",
"interpolate-string": "F",
"location-level-id": "Sacramento.Elev.Inst.0.Bottom of Inlet",
"office-id": "LRL"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"seasonal-values": [
{
"value": 10,
"offset-minutes": 0,
"offset-months": 0
}, {
"value": 15,
"offset-minutes": 0,
"offset-months": 1
}
],
"level-units-id": "ft",
"level-date": "2008-12-03T10:15:30+01:00[UTC]",
"level-comment": "Lowest Point",
"interval-origin": "2008-12-03T10:15:30+01:00[UTC]",
"interval-months": 1,
"interpolate-string": "F",
"location-level-id": "Sacramento.Elev.Inst.0.Bottom of Inlet",
"office-id": "LRL"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"seasonal-time-series-id": "Sacramento.Stage.Inst.5Minutes.0.Bottom of Inlet",
"level-units-id": "ft",
"level-date": "2008-12-03T10:15:30+01:00[UTC]",
"level-comment": "Bottom of Inlet, lowest level",
"interpolate-string": "F",
"location-level-id": "Sacramento.Elev.Inst.0.Bottom of Inlet",
"office-id": "LRL"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"office-id": "SPK",
"location-level-id": "Sacramento.Stage.Ave.1Day.Top of Normal",
"specified-level-id": "Top of Normal",
"parameter-id": "Stage",
"attribute-value": 12.5,
"attribute-units-id": "ft",
"attribute-parameter-id": "Stage",
"attribute-parameter-type-id": "Inst",
"level-units-id": "ft",
"level-date": "2023-06-01T00:00:00-07:00",
"expiration-date": "2025-06-01T00:00:00-07:00",
"constituents": [
{
"type": "LOCATION_LEVEL",
"abbr": "L1",
"name": "Sonoma.Stage.Ave.1Day.Top of Normal",
"attribute-id": "Stage",
"attribute-value": 16.5
},
{
"type": "RATING",
"abbr": "R1",
"name": "Sacramento.Stage;Flow.COE.Production"
}
],
"constituent-connections": "L1=R1I1"
}
Loading