Skip to content

Commit 118933c

Browse files
authored
add RSS feed endpoint for querying AQ message views (#1512)
Alternate considerations: - Looked into using a third-party RSS library for building up the XML. Seemed like the only somewhat maintained library is Rome, but that hasn't been updated since 2023 and contains the jdom2 dependency which has a known vulnerability (wouldn't really matter to our use-case of producing XML only, but would matter on the client). didn't seem too much a lift to just use our own DTO's and jackson serialization. If this ends up being a burden, it also wouldn't be too hard to update to something else in the future. - opted to not set the atom links for self or previous as those would be moving targets given the week lookback limit. We do need a next cursor so the fact that the URL would not be reproducible after a time period is unavoidable. We could also throw out the cursor and only use the `since` field. - don't search for messages older than a week. This could be shortened as needed.
1 parent 23d2a6a commit 118933c

File tree

16 files changed

+1082
-7
lines changed

16 files changed

+1082
-7
lines changed

cwms-data-api/src/main/java/cwms/cda/ApiServlet.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@
133133
import cwms.cda.api.rating.RatingTemplateController;
134134
import cwms.cda.api.rating.ReverseRateTimeSeriesController;
135135
import cwms.cda.api.rating.ReverseRateValuesController;
136+
import cwms.cda.api.rss.RssHandler;
136137
import cwms.cda.api.timeseriesprofile.TimeSeriesProfileCatalogController;
137138
import cwms.cda.api.timeseriesprofile.TimeSeriesProfileController;
138139
import cwms.cda.api.timeseriesprofile.TimeSeriesProfileCreateController;
@@ -254,7 +255,8 @@
254255
"/user/*",
255256
"/users/*",
256257
"/roles/*",
257-
"/version/*"
258+
"/version/*",
259+
"/rss/*"
258260
})
259261
public class ApiServlet extends HttpServlet {
260262

@@ -599,6 +601,7 @@ protected void configureRoutes() {
599601
addUserManagementHandlers();
600602

601603
get("/version/", new CdaVersionHandler(metrics), requiredRoles);
604+
get(format("/rss/{%s}/{%s}", Controllers.OFFICE, Controllers.NAME), new RssHandler(metrics), requiredRoles);
602605
}
603606

604607
private void addUserManagementHandlers() {

cwms-data-api/src/main/java/cwms/cda/api/Controllers.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ public final class Controllers {
9696
public static final String NAME = "name";
9797
public static final String CASCADE_DELETE = "cascade-delete";
9898
public static final String DATUM = "datum";
99+
public static final String SINCE = "since";
99100
public static final String BEGIN = "begin";
100101
public static final String END = "end";
101102
public static final String TIMEZONE = "timezone";
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
/*
2+
* MIT License
3+
*
4+
* Copyright (c) 2025 Hydrologic Engineering Center
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining a copy
7+
* of this software and associated documentation files (the "Software"), to deal
8+
* in the Software without restriction, including without limitation the rights
9+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
* copies of the Software, and to permit persons to whom the Software is
11+
* furnished to do so, subject to the following conditions:
12+
*
13+
* The above copyright notice and this permission notice shall be included in all
14+
* copies or substantial portions of the Software.
15+
*
16+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
* SOFTWARE.
23+
*/
24+
25+
package cwms.cda.api.rss;
26+
27+
import static cwms.cda.api.Controllers.CURSOR;
28+
import static cwms.cda.api.Controllers.GET_ALL;
29+
import static cwms.cda.api.Controllers.NAME;
30+
import static cwms.cda.api.Controllers.OFFICE;
31+
import static cwms.cda.api.Controllers.PAGE;
32+
import static cwms.cda.api.Controllers.PAGE_SIZE;
33+
import static cwms.cda.api.Controllers.SINCE;
34+
import static cwms.cda.api.Controllers.STATUS_200;
35+
import static cwms.cda.api.Controllers.STATUS_400;
36+
import static cwms.cda.api.Controllers.STATUS_404;
37+
import static cwms.cda.api.Controllers.queryParamAsClass;
38+
import static cwms.cda.api.Controllers.queryParamAsInstant;
39+
import static cwms.cda.data.dao.JooqDao.getDslContext;
40+
41+
import com.codahale.metrics.MetricRegistry;
42+
import com.codahale.metrics.Timer;
43+
import cwms.cda.api.BaseHandler;
44+
import cwms.cda.api.errors.CdaError;
45+
import cwms.cda.data.dao.rss.MessageDao;
46+
import cwms.cda.data.dto.CwmsDTOPaginated;
47+
import cwms.cda.data.dto.rss.RssFeed;
48+
import cwms.cda.formatters.ContentType;
49+
import cwms.cda.formatters.Formats;
50+
import cwms.cda.helpers.ReplaceUtils;
51+
import io.javalin.core.util.Header;
52+
import io.javalin.http.Context;
53+
import io.javalin.http.HttpCode;
54+
import io.javalin.plugin.openapi.annotations.OpenApi;
55+
import io.javalin.plugin.openapi.annotations.OpenApiContent;
56+
import io.javalin.plugin.openapi.annotations.OpenApiParam;
57+
import io.javalin.plugin.openapi.annotations.OpenApiResponse;
58+
import java.net.URISyntaxException;
59+
import java.net.URLDecoder;
60+
import java.net.URLEncoder;
61+
import java.nio.charset.StandardCharsets;
62+
import java.time.Instant;
63+
import java.util.function.UnaryOperator;
64+
import org.apache.http.client.utils.URIBuilder;
65+
import org.jetbrains.annotations.NotNull;
66+
import org.jooq.DSLContext;
67+
68+
public final class RssHandler extends BaseHandler {
69+
70+
private static final int DEFAULT_PAGE_SIZE = 500;
71+
private static final String TAG = "RSS";
72+
73+
public RssHandler(MetricRegistry metrics) {
74+
super(metrics);
75+
}
76+
77+
@OpenApi(
78+
pathParams = {
79+
@OpenApiParam(name = OFFICE, required = true, description = "Office id for feed."),
80+
@OpenApiParam(name = NAME, required = true, description = "Specifies the name of the feed. " +
81+
"eg TS_STORED, STATUS, REALTIME_OPS")
82+
},
83+
queryParams = {
84+
@OpenApiParam(name = SINCE, description = "The start the feed time window. " +
85+
"The endpoint will not retrieve more than the last week of messages."),
86+
@OpenApiParam(name = PAGE_SIZE, type = Integer.class, description = "The number of feed items to include."),
87+
@OpenApiParam(name = PAGE, description = "This end point can return a lot of data, this "
88+
+ "identifies where in the request you are. This is an opaque"
89+
+ " value, and can be obtained from the 'next-page' value in "
90+
+ "the response.")
91+
},
92+
responses = {
93+
@OpenApiResponse(status = STATUS_200, content = {
94+
@OpenApiContent(from = RssFeed.class, type = Formats.RSS)
95+
}),
96+
@OpenApiResponse(status = STATUS_404, description = "Unknown Feed")
97+
},
98+
description = "Returns RSS feed items limited to the last week.",
99+
tags = {TAG}
100+
)
101+
@Override
102+
public void handle(@NotNull Context ctx) throws Exception {
103+
try (final Timer.Context ignored = markAndTime(GET_ALL)) {
104+
DSLContext dsl = getDslContext(ctx);
105+
String office = ctx.pathParam(OFFICE).toUpperCase();
106+
String name = ctx.pathParam(NAME);
107+
String formatHeader = ctx.header(Header.ACCEPT);
108+
ContentType contentType = Formats.parseHeader(formatHeader, RssFeed.class);
109+
String cursor = URLDecoder.decode(queryParamAsClass(ctx, new String[]{PAGE, CURSOR}, String.class, ""),
110+
StandardCharsets.UTF_8);
111+
if (!CwmsDTOPaginated.CURSOR_CHECK.invoke(cursor)) {
112+
ctx.json(new CdaError("cursor or page passed in but failed validation"))
113+
.status(HttpCode.BAD_REQUEST);
114+
return;
115+
}
116+
Instant since = queryParamAsInstant(ctx, SINCE);
117+
int pageSize = queryParamAsClass(ctx, new String[]{PAGE_SIZE}, Integer.class, DEFAULT_PAGE_SIZE);
118+
MessageDao dao = new MessageDao(dsl);
119+
RssFeed feed = dao.retrieveFeed(cursor, pageSize, office, name, since, newLinkTemplate(ctx));
120+
String result = Formats.format(contentType, feed);
121+
ctx.result(result);
122+
ctx.contentType(contentType.toString());
123+
}
124+
}
125+
126+
private static String getHost(Context ctx) {
127+
String scheme = ctx.header("X-Forwarded-Proto");
128+
if (scheme == null) {
129+
scheme = "https";
130+
}
131+
String host = ctx.header("X-Forwarded-Host");
132+
if (host == null) {
133+
host = ctx.host();
134+
}
135+
String path = ctx.path();
136+
return scheme + "://" + host + path;
137+
}
138+
139+
private UnaryOperator<String> newLinkTemplate(Context ctx)
140+
throws URISyntaxException {
141+
String pageToken = "{page_token}";
142+
String url = new URIBuilder(getHost(ctx))
143+
.addParameter(PAGE, pageToken)
144+
.build()
145+
.toString();
146+
return new ReplaceUtils.OperatorBuilder()
147+
.withTemplate(url)
148+
.withOperatorKey(URLEncoder.encode(pageToken, StandardCharsets.UTF_8))
149+
.build();
150+
}
151+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* MIT License
3+
*
4+
* Copyright (c) 2025 Hydrologic Engineering Center
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining a copy
7+
* of this software and associated documentation files (the "Software"), to deal
8+
* in the Software without restriction, including without limitation the rights
9+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
* copies of the Software, and to permit persons to whom the Software is
11+
* furnished to do so, subject to the following conditions:
12+
*
13+
* The above copyright notice and this permission notice shall be included in all
14+
* copies or substantial portions of the Software.
15+
*
16+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
* SOFTWARE.
23+
*/
24+
25+
package cwms.cda.data.dao.rss;
26+
27+
enum AqTable {
28+
TS_STORED,
29+
STATUS,
30+
REALTIME_OPS
31+
}
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
/*
2+
* MIT License
3+
*
4+
* Copyright (c) 2025 Hydrologic Engineering Center
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining a copy
7+
* of this software and associated documentation files (the "Software"), to deal
8+
* in the Software without restriction, including without limitation the rights
9+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
* copies of the Software, and to permit persons to whom the Software is
11+
* furnished to do so, subject to the following conditions:
12+
*
13+
* The above copyright notice and this permission notice shall be included in all
14+
* copies or substantial portions of the Software.
15+
*
16+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
* SOFTWARE.
23+
*/
24+
25+
package cwms.cda.data.dao.rss;
26+
27+
import static java.util.stream.Collectors.toList;
28+
import static org.jooq.impl.DSL.currentTimestamp;
29+
import static org.jooq.impl.DSL.field;
30+
import static org.jooq.impl.DSL.name;
31+
import static org.jooq.impl.DSL.partitionBy;
32+
import static org.jooq.impl.DSL.rowNumber;
33+
import static org.jooq.impl.DSL.select;
34+
import static org.jooq.impl.DSL.table;
35+
36+
import cwms.cda.api.errors.NotFoundException;
37+
import cwms.cda.data.dao.JooqDao;
38+
import cwms.cda.data.dto.CwmsDTOPaginated;
39+
import cwms.cda.data.dto.rss.AtomLink;
40+
import cwms.cda.data.dto.rss.RssChannel;
41+
import cwms.cda.data.dto.rss.RssFeed;
42+
import cwms.cda.data.dto.rss.RssItem;
43+
import java.sql.Timestamp;
44+
import java.time.Instant;
45+
import java.time.ZoneOffset;
46+
import java.time.ZonedDateTime;
47+
import java.time.temporal.ChronoUnit;
48+
import java.util.Optional;
49+
import java.util.function.UnaryOperator;
50+
import org.jooq.DSLContext;
51+
import org.jooq.Field;
52+
import org.jooq.Record;
53+
import org.jooq.Result;
54+
import org.jooq.Table;
55+
56+
public final class MessageDao extends JooqDao<RssFeed> {
57+
58+
59+
public MessageDao(DSLContext dsl) {
60+
super(dsl);
61+
}
62+
63+
public RssFeed retrieveFeed(String cursor, int pageSize, String office, String name,
64+
Instant since, UnaryOperator<String> urlBuilder) {
65+
AqTable aqTable = getAqTable(name);
66+
String[] cursorSplit = CwmsDTOPaginated.decodeCursor(cursor);
67+
int offset = 0;
68+
if(cursorSplit.length == 2) {
69+
offset = Integer.parseInt(cursorSplit[0]);
70+
pageSize = Integer.parseInt(cursorSplit[1]);
71+
since = null;
72+
}
73+
var items = retrieveMessages(offset, pageSize, since, office, aqTable)
74+
.map(record -> {
75+
Object userData = record.get("USER_DATA");
76+
return MessageUtil.extractPayload(userData).map(p -> rssItem(record, p));
77+
}).stream()
78+
.filter(Optional::isPresent)
79+
.map(Optional::get)
80+
.collect(toList());
81+
AtomLink nextLink = null;
82+
if(items.size() == pageSize) {
83+
String nextCursor = CwmsDTOPaginated.encodeCursor(items.size() + offset, pageSize);
84+
nextLink = new AtomLink("next", urlBuilder.apply(nextCursor));
85+
}
86+
String description;
87+
switch(aqTable) {
88+
case TS_STORED:
89+
description = " CWMS messages about time series operations, such as data stored and deleted";
90+
break;
91+
case STATUS:
92+
description = " CWMS general system and application status messages";
93+
break;
94+
case REALTIME_OPS:
95+
description = " CWMS application operational messages";
96+
break;
97+
default:
98+
description = null;
99+
}
100+
RssChannel channel = new RssChannel(name, nextLink, description, items);
101+
return new RssFeed(channel);
102+
}
103+
104+
private static AqTable getAqTable(String name) {
105+
try {
106+
return AqTable.valueOf(name.toUpperCase());
107+
} catch (IllegalArgumentException e) {
108+
throw new NotFoundException(e);
109+
}
110+
}
111+
112+
private static RssItem rssItem(Record record, String p) {
113+
ZonedDateTime enqTimestamp = record.get("ENQ_TIMESTAMP", Timestamp.class)
114+
.toInstant().atZone(ZoneOffset.UTC);
115+
String msgId = record.get("MSG_ID", String.class);
116+
return new RssItem(p, enqTimestamp, msgId);
117+
}
118+
119+
private Result<?> retrieveMessages(int offset, int pageSize, Instant since, String office, AqTable name) {
120+
Timestamp sinceTimestamp = since == null ? null : Timestamp.from(since);
121+
Table<?> t = table(name("CWMS_20", "AQ$" + office + "_" + name.name() + "_TABLE")).as("t");
122+
123+
Field<String> MSG_ID = field("MSG_ID", String.class);
124+
Field<Timestamp> ENQ_TS = field("ENQ_TIMESTAMP", Timestamp.class);
125+
Field<Object> USER_DATA = field("USER_DATA", Object.class);
126+
Field<Integer> rn = rowNumber()
127+
.over(partitionBy(MSG_ID).orderBy(ENQ_TS.desc()))
128+
.as("rn");
129+
var condition = ENQ_TS.ge(currentTimestamp().minus(7));
130+
if (sinceTimestamp != null) {
131+
condition = condition.and(ENQ_TS.gt(sinceTimestamp));
132+
}
133+
var inner = select(MSG_ID, ENQ_TS, USER_DATA, rn)
134+
.from(t)
135+
.where(condition)
136+
.asTable("x");
137+
return dsl.select( MSG_ID, ENQ_TS, USER_DATA)
138+
.from(inner)
139+
.where(field(name("x", "rn"), Integer.class).eq(1))
140+
.orderBy(ENQ_TS.desc())
141+
.offset(offset)
142+
.limit(pageSize)
143+
.fetch();
144+
}
145+
}

0 commit comments

Comments
 (0)