Skip to content
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

Issue 693 - Rating curve retrieval #909

Merged
merged 11 commits into from
Dec 19, 2024
2 changes: 2 additions & 0 deletions cwms-data-api/src/main/java/cwms/cda/ApiServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
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;
Expand Down Expand Up @@ -504,6 +505,7 @@ protected void configureRoutes() {
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);
cdaCrudCache("/catalog/{dataset}",
Expand Down
42 changes: 23 additions & 19 deletions cwms-data-api/src/main/java/cwms/cda/api/RatingController.java
adamkorynta marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -296,19 +296,16 @@ public void getAll(@NotNull Context ctx) {

ContentType contentType = Formats.parseHeaderAndQueryParm(header, format, RatingAliasMarker.class);

if (format.isEmpty())
{
if (format.isEmpty()) {
//Use the full content type here (i.e. application/json;version=2)
ctx.contentType(contentType.toString());
}
else
{
} else {
//Legacy content type only includes the basic type (i.e. application/json)
ctx.contentType(contentType.getType());
}

//At the moment, we still use the legacy formatting here, since we don't have a newer API for serializing/deserializing
//a collection of rating sets - unlike getOne.
//At the moment, we still use the legacy formatting here, since we don't have a newer API for
// serializing/deserializing a collection of rating sets - unlike getOne.
String legacyFormat = Formats.getLegacyTypeFromContentType(contentType);
String results = ratingDao.retrieveRatings(legacyFormat, names, unit, datum, office, start,
end, timezone);
Expand All @@ -322,7 +319,8 @@ public void getAll(@NotNull Context ctx) {

@OpenApi(
pathParams = {
@OpenApiParam(name = RATING_ID, required = true, description = "The rating-id of the effective dates to be retrieve. "),
@OpenApiParam(name = RATING_ID, required = true, description = "The rating-id of the effective "
+ "dates to be retrieve. "),
},
queryParams = {
@OpenApiParam(name = OFFICE, required = true, description =
Expand Down Expand Up @@ -354,7 +352,7 @@ public void getAll(@NotNull Context ctx) {
public void getOne(@NotNull Context ctx, @NotNull String rating) {

try (final Timer.Context ignored = markAndTime(GET_ONE)) {
String officeId = ctx.queryParam(OFFICE);

String timezone = ctx.queryParamAsClass(TIMEZONE, String.class).getOrDefault("UTC");

Instant beginInstant = null;
Expand All @@ -369,23 +367,24 @@ public void getOne(@NotNull Context ctx, @NotNull String rating) {
endInstant = DateUtils.parseUserDate(end, timezone).toInstant();
}

String officeId = ctx.queryParam(OFFICE);

RatingSet.DatabaseLoadMethod method = ctx.queryParamAsClass(METHOD,
RatingSet.DatabaseLoadMethod.class)
.getOrDefault(RatingSet.DatabaseLoadMethod.EAGER);

String body = getRatingSetString(ctx, method, officeId, rating, beginInstant, endInstant);
String body = getRatingSetString(ctx, method, officeId, rating, beginInstant, endInstant, false);
adamkorynta marked this conversation as resolved.
Show resolved Hide resolved
if (body != null) {
ctx.result(body);
ctx.status(HttpCode.OK);
}
}
}


@Nullable
private String getRatingSetString(Context ctx, RatingSet.DatabaseLoadMethod method,
protected String getRatingSetString(Context ctx, RatingSet.DatabaseLoadMethod method,
String officeId, String rating, Instant begin,
Instant end) {
Instant end, boolean latest) {
String retval = null;

try (final Timer.Context ignored = markAndTime("getRatingSetString")) {
Expand All @@ -398,7 +397,8 @@ private String getRatingSetString(Context ctx, RatingSet.DatabaseLoadMethod meth
if (isJson || isXml) {
ctx.contentType(contentType.toString());
try {
RatingSet ratingSet = getRatingSet(ctx, method, officeId, rating, begin, end);
RatingSet ratingSet = null;
ratingSet = getRatingSet(ctx, method, officeId, rating, begin, end, latest);
if (ratingSet != null) {
if (isJson) {
retval = JsonRatingUtils.toJson(ratingSet);
Expand All @@ -424,8 +424,7 @@ private String getRatingSetString(Context ctx, RatingSet.DatabaseLoadMethod meth
} else {
CdaError re = new CdaError("Currently supporting only: " + Formats.JSONV2
+ " and " + Formats.XMLV2);
logger.log(Level.WARNING, "Provided accept header not recognized:"
+ acceptHeader, re);
logger.log(Level.WARNING, String.format("Provided accept header not recognized: %s", acceptHeader), re);
ctx.status(HttpServletResponse.SC_NOT_IMPLEMENTED);
ctx.json(CdaError.notImplemented());
}
Expand All @@ -437,13 +436,18 @@ private String getRatingSetString(Context ctx, RatingSet.DatabaseLoadMethod meth

private RatingSet getRatingSet(Context ctx, RatingSet.DatabaseLoadMethod method,
String officeId, String rating, Instant begin,
Instant end) throws IOException, RatingException {
RatingSet ratingSet;
Instant end, boolean latest) throws IOException, RatingException {
adamkorynta marked this conversation as resolved.
Show resolved Hide resolved
RatingSet ratingSet = null;
try (final Timer.Context ignored = markAndTime("getRatingSet")) {
DSLContext dsl = getDslContext(ctx);

RatingDao ratingDao = getRatingDao(dsl);
ratingSet = ratingDao.retrieve(method, officeId, rating, begin, end);

if (latest) {
ratingSet = ratingDao.retrieveLatest(method, officeId, rating);
} else {
ratingSet = ratingDao.retrieve(method, officeId, rating, begin, end);
}
}

return ratingSet;
Expand Down
133 changes: 133 additions & 0 deletions cwms-data-api/src/main/java/cwms/cda/api/RatingLatestController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
*
* MIT License
*
* Copyright (c) 2024 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;

import static cwms.cda.api.Controllers.BEGIN;
import static cwms.cda.api.Controllers.END;
import static cwms.cda.api.Controllers.GET_ONE;
import static cwms.cda.api.Controllers.METHOD;
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.TIMEZONE;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import cwms.cda.data.dao.RatingDao;
import cwms.cda.data.dao.RatingSetDao;
import cwms.cda.formatters.Formats;
import cwms.cda.helpers.DateUtils;
import hec.data.cwmsRating.RatingSet;
import io.javalin.http.Context;
import io.javalin.http.Handler;
import io.javalin.http.HttpCode;
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.OpenApiResponse;
import java.time.Instant;
import org.jetbrains.annotations.NotNull;
import org.jooq.DSLContext;


public class RatingLatestController extends RatingController implements Handler {
adamkorynta marked this conversation as resolved.
Show resolved Hide resolved
private static final String TAG = "Ratings";
private final MetricRegistry metrics;

public RatingLatestController(MetricRegistry metrics) {
super(metrics);
this.metrics = metrics;
}

private Timer.Context markAndTime(String subject) {
return Controllers.markAndTime(metrics, getClass().getName(), subject);
}

@NotNull
@Override
protected RatingDao getRatingDao(DSLContext dsl) {
return new RatingSetDao(dsl);
}

@OpenApi(
pathParams = {
@OpenApiParam(name = RATING_ID, required = true, description = "The rating-id of the effective "
+ "dates to be retrieve. "),
},
queryParams = {
@OpenApiParam(name = OFFICE, required = true, description =
"Specifies the owning office of the ratingset to be included in the "
+ "response."),
@OpenApiParam(name = TIMEZONE, description = "Specifies "
adamkorynta marked this conversation as resolved.
Show resolved Hide resolved
+ "the time zone of the values of the begin and end fields (unless "
+ "otherwise specified), as well as the time zone of any times in the"
+ " response. If this field is not specified, the default time zone "
+ "of UTC shall be used."),
@OpenApiParam(name = METHOD, description = "Specifies "
+ "the retrieval method used. If no method is provided EAGER will be used.",
type = RatingSet.DatabaseLoadMethod.class),
},
responses = {
@OpenApiResponse(status = STATUS_200, content = {
@OpenApiContent(type = Formats.JSONV2),
@OpenApiContent(type = Formats.XMLV2)})},
description = "Returns CWMS Rating Data",
tags = {TAG})
@Override
public void handle(@NotNull Context ctx) throws Exception {
try (final Timer.Context ignored = markAndTime(GET_ONE)) {
String rating = ctx.pathParam(RATING_ID);

String timezone = ctx.queryParamAsClass(TIMEZONE, String.class).getOrDefault("UTC");

Instant beginInstant = null;
String begin = ctx.queryParam(BEGIN);
if (begin != null) {
beginInstant = DateUtils.parseUserDate(begin, timezone).toInstant();
}

Instant endInstant = null;
String end = ctx.queryParam(END);
if (end != null) {
endInstant = DateUtils.parseUserDate(end, timezone).toInstant();
}

String officeId = ctx.queryParam(OFFICE);

RatingSet.DatabaseLoadMethod method = ctx.queryParamAsClass(METHOD,
RatingSet.DatabaseLoadMethod.class)
.getOrDefault(RatingSet.DatabaseLoadMethod.EAGER);

String body = getRatingSetString(ctx, method, officeId, rating, beginInstant, endInstant, true);
if (body != null) {
ctx.result(body);
ctx.status(HttpCode.OK);
}
}

}
}
8 changes: 5 additions & 3 deletions cwms-data-api/src/main/java/cwms/cda/data/dao/RatingDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,23 @@

import hec.data.RatingException;
import hec.data.cwmsRating.RatingSet;

import java.io.IOException;
import java.time.Instant;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public interface RatingDao {

static final Pattern officeMatcher = Pattern.compile(".*office-id=\"(.*?)\"");
Pattern officeMatcher = Pattern.compile(".*office-id=\"(.*?)\"");

void create(String ratingSet, boolean storeTemplate) throws IOException, RatingException;

RatingSet retrieve(RatingSet.DatabaseLoadMethod method, String officeId, String specificationId,
Instant start, Instant end) throws IOException, RatingException;

RatingSet retrieveLatest(RatingSet.DatabaseLoadMethod method, String officeId, String specificationId)
throws IOException, RatingException;

String retrieveRatings(String format, String names, String unit, String datum, String office,
String start, String end, String timezone);

Expand All @@ -52,7 +54,7 @@ String retrieveRatings(String format, String names, String unit, String datum, S
static String extractOfficeFromXml(String xml) {
Matcher officeMatch = officeMatcher.matcher(xml);

if(officeMatch.find()) {
if (officeMatch.find()) {
return officeMatch.group(1);
} else {
throw new RuntimeException("Unable to determine office for data set");
Expand Down
Loading
Loading