Skip to content

Feature/rate function #1082

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 8 commits into
base: develop
Choose a base branch
from
Draft
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
53 changes: 38 additions & 15 deletions cwms-data-api/src/main/java/cwms/cda/ApiServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
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 cwms.cda.api.MeasurementTimeExtentsGetController;
import static io.javalin.apibuilder.ApiBuilder.crud;
Expand Down Expand Up @@ -71,11 +72,14 @@
import cwms.cda.api.PoolController;
import cwms.cda.api.ProjectController;
import cwms.cda.api.PropertyController;
import cwms.cda.api.RatingController;
import cwms.cda.api.RatingLatestController;
import cwms.cda.api.RatingMetadataController;
import cwms.cda.api.RatingSpecController;
import cwms.cda.api.RatingTemplateController;
import cwms.cda.api.errors.RateException;
import cwms.cda.api.rating.RateTimeSeriesController;
import cwms.cda.api.rating.RateValuesController;
import cwms.cda.api.rating.RatingController;
import cwms.cda.api.rating.RatingLatestController;
import cwms.cda.api.rating.RatingMetadataController;
import cwms.cda.api.rating.RatingSpecController;
import cwms.cda.api.rating.RatingTemplateController;
import cwms.cda.api.SpecifiedLevelController;
import cwms.cda.api.StandardTextController;
import cwms.cda.api.StateController;
Expand Down Expand Up @@ -109,7 +113,6 @@
import cwms.cda.api.location.kind.GateChangeCreateController;
import cwms.cda.api.location.kind.GateChangeDeleteController;
import cwms.cda.api.location.kind.GateChangeGetAllController;
import cwms.cda.api.location.kind.GateChangeCreateController;
import cwms.cda.api.location.kind.LockController;
import cwms.cda.api.location.kind.OutletController;
import cwms.cda.api.location.kind.VirtualOutletController;
Expand All @@ -125,6 +128,8 @@
import cwms.cda.api.project.ProjectPublishStatusUpdate;
import cwms.cda.api.project.RemoveAllLockRevokerRights;
import cwms.cda.api.project.UpdateLockRevokerRights;
import cwms.cda.api.rating.ReverseRateTimeSeriesController;
import cwms.cda.api.rating.ReverseRateValuesController;
import cwms.cda.api.watersupply.AccountingCatalogController;
import cwms.cda.api.watersupply.AccountingCreateController;
import cwms.cda.api.timeseriesprofile.TimeSeriesProfileCatalogController;
Expand Down Expand Up @@ -320,6 +325,7 @@ public void init() {
PolicyFactory sanitizer = new HtmlPolicyBuilder().disallowElements("<script>").toFactory();
APP_CONTEXT = this.getServletContext().getContextPath();
javalin = Javalin.createStandalone(config -> {
config.enableDevLogging();
config.defaultContentType = "application/json";
getOpenApiOptions(config);
config.autogenerateEtags = true;
Expand Down Expand Up @@ -402,6 +408,11 @@ public void init() {
logger.atInfo().withCause(e).log(re.toString());
ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re);
})
.exception(RateException.class, (e, ctx) -> {
CdaError re = new CdaError("Error performing rate function: " + e.getMessage());
logger.atInfo().withCause(e).log(re.toString());
ctx.status(HttpServletResponse.SC_BAD_REQUEST).json(re);
})
.exception(FieldException.class, (e, ctx) -> {
CdaError re = new CdaError(e.getMessage(), e.getDetails(), true);
ctx.status(HttpServletResponse.SC_BAD_REQUEST).json(re);
Expand Down Expand Up @@ -574,15 +585,7 @@ protected void configureRoutes() {
new TimeSeriesGroupController(metrics), requiredRoles,5, TimeUnit.MINUTES);
cdaCrudCache("/timeseries/{timeseries}",
new TimeSeriesController(metrics), requiredRoles,5, TimeUnit.MINUTES);
cdaCrudCache("/ratings/template/{template-id}",
new RatingTemplateController(metrics), requiredRoles,5, TimeUnit.MINUTES);
cdaCrudCache("/ratings/spec/{rating-id}",
new RatingSpecController(metrics), requiredRoles,5, TimeUnit.MINUTES);
cdaCrudCache("/ratings/metadata/{rating-id}",
new RatingMetadataController(metrics), requiredRoles,5, TimeUnit.MINUTES);
get("/ratings/{rating-id}/latest", new RatingLatestController(metrics));
cdaCrudCache("/ratings/{rating-id}",
new RatingController(metrics), requiredRoles,5, TimeUnit.MINUTES);
addRatingHandlers(requiredRoles);
cdaCrudCache("/catalog/{dataset}",
new CatalogController(metrics), requiredRoles,5, TimeUnit.MINUTES);
cdaCrudCache("/basins/{name}",
Expand Down Expand Up @@ -675,6 +678,26 @@ protected void configureRoutes() {
addProjectLockRightsHandlers("/project-lock-rights/{project-id}", requiredRoles);
}

private void addRatingHandlers(RouteRole[] requiredRoles) {
post(format("/ratings/rate-values/{%s}/{%s}", OFFICE, RATING_ID),
new RateValuesController(metrics), requiredRoles);
post(format("/ratings/rate-ts/{%s}/{%s}", OFFICE, RATING_ID),
new RateTimeSeriesController(metrics), requiredRoles);
post(format("/ratings/reverse-rate-values/{%s}/{%s}", OFFICE, RATING_ID),
new ReverseRateValuesController(metrics), requiredRoles);
post(format("/ratings/reverse-rate-ts/{%s}/{%s}", OFFICE, RATING_ID),
new ReverseRateTimeSeriesController(metrics), requiredRoles);
cdaCrudCache("/ratings/template/{template-id}",
new RatingTemplateController(metrics), requiredRoles,5, TimeUnit.MINUTES);
cdaCrudCache("/ratings/spec/{rating-id}",
new RatingSpecController(metrics), requiredRoles,5, TimeUnit.MINUTES);
cdaCrudCache("/ratings/metadata/{rating-id}",
new RatingMetadataController(metrics), requiredRoles,5, TimeUnit.MINUTES);
get("/ratings/{rating-id}/latest", new RatingLatestController(metrics));
cdaCrudCache("/ratings/{rating-id}",
new RatingController(metrics), requiredRoles,5, TimeUnit.MINUTES);
}

private void addAccountingHandlers(String path, RouteRole[] requiredRoles) {
get(path, new AccountingCatalogController(metrics));
post(path, new AccountingCreateController(metrics), requiredRoles);
Expand Down
3 changes: 2 additions & 1 deletion cwms-data-api/src/main/java/cwms/cda/api/Controllers.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ public final class Controllers {
public static final String STATUS_404 = "404";
public static final String STATUS_501 = "501";
public static final String STATUS_400 = "400";
public static final String STATUS_401 = "401";
public static final String TEXT_MASK = "text-mask";
public static final String DELETE_MODE = "delete-mode";
public static final String STANDARD_TEXT_ID_MASK = "standard-text-id-mask";
Expand Down Expand Up @@ -465,7 +466,7 @@ public static Instant requiredInstant(Context ctx, String param) {
return retval;
}

static void addDeprecatedContentTypeWarning(Context ctx, ContentType type) {
public static void addDeprecatedContentTypeWarning(Context ctx, ContentType type) {
if (type.getType().equalsIgnoreCase(Formats.TAB)) {
ctx.res.addHeader(DEPRECATED_HEADER, DEPRECATED_TAB);
} else if (type.getType().equalsIgnoreCase(Formats.CSV)) {
Expand Down
34 changes: 34 additions & 0 deletions cwms-data-api/src/main/java/cwms/cda/api/errors/RateException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* MIT License
*
* Copyright (c) 2025 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.api.errors;

import java.sql.SQLException;

public final class RateException extends RuntimeException {

public RateException(String message, SQLException cause) {
super(message, cause);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* MIT License
*
* Copyright (c) 2025 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.api.rating;

import static cwms.cda.api.Controllers.OFFICE;
import static cwms.cda.api.Controllers.RATING_ID;
import static cwms.cda.api.Controllers.STATUS_200;
import static cwms.cda.api.Controllers.STATUS_400;
import static cwms.cda.api.Controllers.STATUS_401;
import static cwms.cda.api.Controllers.STATUS_404;
import static cwms.cda.api.Controllers.STATUS_501;
import static cwms.cda.data.dao.JooqDao.getDslContext;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import cwms.cda.api.BaseHandler;
import cwms.cda.data.dao.RateDao;
import cwms.cda.data.dto.rating.RateInputTimeSeries;
import cwms.cda.data.dto.rating.RatedOutput;
import cwms.cda.data.dto.rating.RatedOutputTimeSeries;
import cwms.cda.formatters.ContentType;
import cwms.cda.formatters.Formats;
import io.javalin.core.util.Header;
import io.javalin.http.Context;
import io.javalin.plugin.openapi.annotations.HttpMethod;
import io.javalin.plugin.openapi.annotations.OpenApi;
import io.javalin.plugin.openapi.annotations.OpenApiContent;
import io.javalin.plugin.openapi.annotations.OpenApiParam;
import io.javalin.plugin.openapi.annotations.OpenApiRequestBody;
import io.javalin.plugin.openapi.annotations.OpenApiResponse;
import io.javalin.plugin.openapi.annotations.OpenApiSecurity;
import javax.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.jooq.DSLContext;

public final class RateTimeSeriesController extends BaseHandler {

static final String TAG = "Ratings";
private static final String RATE = "Rate";

public RateTimeSeriesController(MetricRegistry metrics) {
super(metrics);
}

@OpenApi(
pathParams = {
@OpenApiParam(name = OFFICE, description = "Office owning the rating"),
@OpenApiParam(name = RATING_ID, description = "Rating Specification identifier"),
},
requestBody = @OpenApiRequestBody(content = {
@OpenApiContent(type = Formats.JSON, from = RateInputTimeSeries.class),
@OpenApiContent(type = Formats.JSONV1, from = RateInputTimeSeries.class)
}, required = true),
responses = {
@OpenApiResponse(status = STATUS_200, content = {
@OpenApiContent(type = Formats.JSON, from = RatedOutputTimeSeries.class),
@OpenApiContent(type = Formats.JSONV1, from = RatedOutputTimeSeries.class)
}),
@OpenApiResponse(status = STATUS_400, description = "Invalid input parameters."),
@OpenApiResponse(status = STATUS_401, description = "Client is not authorized."),
@OpenApiResponse(status = STATUS_404, description = "The rating curve was not found."),
@OpenApiResponse(status = STATUS_501, description = "Requested format is not implemented")
},
security = {
@OpenApiSecurity(name = "gets overridden allows lock icon.")
},
description = "Rates input values using CWMS ratings. The input format `RateInputTimeSeries` DTO " +
"supports an array of CWMS time series ids, " +
"each corresponding to an independent parameter in the rating curve." +
"The output format `RatedOutputTimeSeries` will contain a singular double array corresponding to the " +
"dependent parameter of the rating curve. ",
method = HttpMethod.POST,
tags = {TAG}
)
@Override
public void handle(@NotNull Context ctx) throws Exception {
try (final Timer.Context ignored = markAndTime(RATE)) {
DSLContext dsl = getDslContext(ctx);
RateDao ratingDao = new RateDao(dsl);
String office = ctx.pathParam(OFFICE);
String ratingId = ctx.pathParam(RATING_ID);
String contentTypeHeader = ctx.req.getContentType();
String body = ctx.body();
ContentType contentType = Formats.parseHeader(contentTypeHeader, RateInputTimeSeries.class);
RateInputTimeSeries input = Formats.parseContent(contentType, body, RateInputTimeSeries.class);
RatedOutput output = ratingDao.rate(office, ratingId, input);
String acceptFormatHeader = ctx.header(Header.ACCEPT);
ContentType acceptContentType = Formats.parseHeader(acceptFormatHeader, RatedOutputTimeSeries.class);
String result = Formats.format(acceptContentType, output);
ctx.status(HttpServletResponse.SC_OK).result(result);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* MIT License
*
* Copyright (c) 2025 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.api.rating;

import static cwms.cda.api.Controllers.OFFICE;
import static cwms.cda.api.Controllers.RATING_ID;
import static cwms.cda.api.Controllers.STATUS_200;
import static cwms.cda.api.Controllers.STATUS_400;
import static cwms.cda.api.Controllers.STATUS_401;
import static cwms.cda.api.Controllers.STATUS_404;
import static cwms.cda.api.Controllers.STATUS_501;
import static cwms.cda.data.dao.JooqDao.getDslContext;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import cwms.cda.api.BaseHandler;
import cwms.cda.data.dao.RateDao;
import cwms.cda.data.dto.rating.RateInputValues;
import cwms.cda.data.dto.rating.RatedOutput;
import cwms.cda.data.dto.rating.RatedOutputValues;
import cwms.cda.formatters.ContentType;
import cwms.cda.formatters.Formats;
import io.javalin.core.util.Header;
import io.javalin.http.Context;
import io.javalin.plugin.openapi.annotations.HttpMethod;
import io.javalin.plugin.openapi.annotations.OpenApi;
import io.javalin.plugin.openapi.annotations.OpenApiContent;
import io.javalin.plugin.openapi.annotations.OpenApiParam;
import io.javalin.plugin.openapi.annotations.OpenApiRequestBody;
import io.javalin.plugin.openapi.annotations.OpenApiResponse;
import io.javalin.plugin.openapi.annotations.OpenApiSecurity;
import javax.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.jooq.DSLContext;

public final class RateValuesController extends BaseHandler {

static final String TAG = "Ratings";
private static final String RATE = "Rate";

public RateValuesController(MetricRegistry metrics) {
super(metrics);
}

@OpenApi(
pathParams = {
@OpenApiParam(name = OFFICE, description = "Office owning the rating"),
@OpenApiParam(name = RATING_ID, description = "Rating Specification identifier"),
},
requestBody = @OpenApiRequestBody(content = {
@OpenApiContent(type = Formats.JSON, from = RateInputValues.class),
@OpenApiContent(type = Formats.JSONV1, from = RateInputValues.class)
}, required = true),
responses = {
@OpenApiResponse(status = STATUS_200, content = {
@OpenApiContent(type = Formats.JSON, from = RatedOutputValues.class),
@OpenApiContent(type = Formats.JSONV1, from = RatedOutputValues.class)
}),
@OpenApiResponse(status = STATUS_400, description = "Invalid input parameters."),
@OpenApiResponse(status = STATUS_401, description = "Client is not authorized."),
@OpenApiResponse(status = STATUS_404, description = "The rating curve was not found."),
@OpenApiResponse(status = STATUS_501, description = "Requested format is not implemented")
},
security = {
@OpenApiSecurity(name = "gets overridden allows lock icon.")
},
description = "Rates input values using CWMS ratings. The input format `RatingInputValues` includes " +
"a two dimensional array with each dimension corresponding to an independent parameter " +
"in the rating curve. " +
"The output format `RatedOutputTimeSeries` will contain a singular double array corresponding to the " +
"dependent parameter of the rating curve. ",
method = HttpMethod.POST,
tags = {TAG}
)
@Override
public void handle(@NotNull Context ctx) throws Exception {
try (final Timer.Context ignored = markAndTime(RATE)) {
DSLContext dsl = getDslContext(ctx);
RateDao ratingDao = new RateDao(dsl);
String office = ctx.pathParam(OFFICE);
String ratingId = ctx.pathParam(RATING_ID);
String contentTypeHeader = ctx.req.getContentType();
String body = ctx.body();
ContentType contentType = Formats.parseHeader(contentTypeHeader, RateInputValues.class);
RateInputValues input = Formats.parseContent(contentType, body, RateInputValues.class);
RatedOutput output = ratingDao.rate(office, ratingId, input);
String acceptFormatHeader = ctx.header(Header.ACCEPT);
ContentType acceptContentType = Formats.parseHeader(acceptFormatHeader, RatedOutputValues.class);
String result = Formats.format(acceptContentType, output);
ctx.status(HttpServletResponse.SC_OK).result(result);
}
}
}
Loading
Loading