-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathTimeSeriesIdentifierDescriptorController.java
More file actions
354 lines (300 loc) · 16.7 KB
/
TimeSeriesIdentifierDescriptorController.java
File metadata and controls
354 lines (300 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
* 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;
import static com.codahale.metrics.MetricRegistry.name;
import static cwms.cda.api.Controllers.*;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import cwms.cda.api.errors.CdaError;
import cwms.cda.api.errors.ErrorTraceSupport;
import cwms.cda.data.dao.JooqDao;
import cwms.cda.data.dao.TimeSeriesIdentifierDescriptorDao;
import cwms.cda.data.dto.TimeSeriesIdentifierDescriptor;
import cwms.cda.data.dto.TimeSeriesIdentifierDescriptors;
import cwms.cda.formatters.ContentType;
import cwms.cda.formatters.Formats;
import io.javalin.apibuilder.CrudHandler;
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 java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.google.common.flogger.FluentLogger;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.jooq.DSLContext;
import org.jooq.exception.DataAccessException;
public class TimeSeriesIdentifierDescriptorController implements CrudHandler {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final String TAG = "TimeSeries Identifier";
private static final int DEFAULT_PAGE_SIZE = 500;
private final MetricRegistry metrics;
private final Histogram requestResultSize;
public TimeSeriesIdentifierDescriptorController(MetricRegistry metrics) {
this.metrics = metrics;
String className = this.getClass().getName();
requestResultSize = this.metrics.histogram((name(className, RESULTS, SIZE)));
}
private Timer.Context markAndTime(String subject) {
return Controllers.markAndTime(metrics, getClass().getName(), subject);
}
protected DSLContext getDslContext(Context ctx) {
return JooqDao.getDslContext(ctx);
}
@OpenApi(queryParams = {
@OpenApiParam(name = OFFICE, description = "Specifies the owning office of the "
+ "timeseries identifier(s) whose data is to be included in the response. If "
+ "this field is not specified, matching timeseries identifier information from"
+ " all offices shall be returned."),
@OpenApiParam(name = TIMESERIES_ID_REGEX, description = "A case insensitive RegExp "
+ "that will be applied to the timeseries-id field. If this field is "
+ "not specified the results will not be constrained by timeseries-id."),
@OpenApiParam(name = INCLUDE_ALIASES, type = Boolean.class, description = "Specifies whether to include "
+ "aliased items as content in the results. Default is false."),
@OpenApiParam(name = PAGE,
description = "This end point can return a lot of data, this "
+ "identifies where in the request you are. This is an opaque"
+ " value, and can be obtained from the 'next-page' value in "
+ "the response."
),
@OpenApiParam(name = PAGE_SIZE, type = Integer.class,
description = "How many entries per page returned. "
+ "Default " + DEFAULT_PAGE_SIZE + "."
)},
responses = {@OpenApiResponse(status = STATUS_200,
content = {
@OpenApiContent(type = Formats.JSONV2, from = TimeSeriesIdentifierDescriptors.class)
}),
@OpenApiResponse(status = STATUS_404, description = "Based on the combination of "
+ "inputs provided the time series identifier descriptors were not found."),
@OpenApiResponse(status = STATUS_501, description = "request format is not "
+ "implemented")},
description = "Returns CWMS timeseries identifier descriptor"
+ "Data. Currently includes aliased items in results.",
tags = {TAG}
)
@Override
public void getAll(Context ctx) {
String cursor = ctx.queryParamAsClass(PAGE, String.class).getOrDefault("");
int pageSize =
ctx.queryParamAsClass(PAGE_SIZE, Integer.class).getOrDefault(DEFAULT_PAGE_SIZE);
try (final Timer.Context ignored = markAndTime(GET_ALL)) {
DSLContext dsl = getDslContext(ctx);
TimeSeriesIdentifierDescriptorDao dao = new TimeSeriesIdentifierDescriptorDao(dsl);
String office = ctx.queryParam(OFFICE);
String idRegex = ctx.queryParam(TIMESERIES_ID_REGEX);
boolean includeAliases = ctx.queryParamAsClass(INCLUDE_ALIASES, Boolean.class).getOrDefault(false);
TimeSeriesIdentifierDescriptors descriptors =
dao.getTimeSeriesIdentifiers(cursor, pageSize, office, idRegex, includeAliases);
String formatHeader = ctx.header(Header.ACCEPT);
if (Formats.DEFAULT.equals(formatHeader)) {
// parseHeaderAndQueryParm normally defaults to JSONV1 when the input is */*
formatHeader = Formats.JSONV2;
}
ContentType contentType = Formats.parseHeader(formatHeader, TimeSeriesIdentifierDescriptors.class);
String result = Formats.format(contentType, descriptors);
ctx.result(result).contentType(contentType.toString());
requestResultSize.update(result.length());
ctx.status(HttpServletResponse.SC_OK);
}
}
@OpenApi(
pathParams = {
@OpenApiParam(name = TIMESERIES_ID, required = true, description = "Specifies"
+ " the identifier of the timeseries to be included in the response."),
},
queryParams = {
@OpenApiParam(name = OFFICE, required = true, description = "Specifies the "
+ "owning office of the timeseries identifier to be "
+ "included in the response."),
},
responses = {
@OpenApiResponse(status = STATUS_200,
content = {
@OpenApiContent(from = TimeSeriesIdentifierDescriptor.class, type =
Formats.JSONV2)
}
),
@OpenApiResponse(status = STATUS_404, description = "Based on the combination of "
+ "inputs provided the timeseries identifier descriptor was not found."),
@OpenApiResponse(status = STATUS_501, description = "request format is not "
+ "implemented")},
description = "Retrieves requested timeseries identifier descriptor",
tags = {TAG}
)
@Override
public void getOne(@NotNull Context ctx, @NotNull String timeseriesId) {
try (final Timer.Context ignored = markAndTime(GET_ONE)) {
DSLContext dsl = getDslContext(ctx);
TimeSeriesIdentifierDescriptorDao dao = new TimeSeriesIdentifierDescriptorDao(dsl);
String office = requiredParam(ctx, OFFICE);
String formatHeader = ctx.header(Header.ACCEPT);
if (Formats.DEFAULT.equals(formatHeader)) {
// parseHeaderAndQueryParm normally defaults to JSONV1 when the input is */*
formatHeader = Formats.JSONV2;
}
ContentType contentType = Formats.parseHeader(formatHeader, TimeSeriesIdentifierDescriptor.class);
Optional<TimeSeriesIdentifierDescriptor> grp = dao.getTimeSeriesIdentifier(office, timeseriesId);
if (grp.isPresent()) {
String result = Formats.format(contentType, grp.get());
ctx.result(result).contentType(contentType.toString());
requestResultSize.update(result.length());
ctx.status(HttpServletResponse.SC_OK);
} else {
CdaError re = new CdaError("Unable to find identifier based on parameters "
+ "given");
logger.atInfo().log("%s%s for request %s", re, System.lineSeparator(), ctx.fullUrl());
ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re);
}
}
}
@OpenApi(
description = "Create new TimeSeriesIdentifierDescriptor",
requestBody = @OpenApiRequestBody(
content = {
@OpenApiContent(from = TimeSeriesIdentifierDescriptor.class, type = Formats.JSONV2),
@OpenApiContent(from = TimeSeriesIdentifierDescriptor.class, type = Formats.XMLV2)
},
required = true),
queryParams = {
@OpenApiParam(name = FAIL_IF_EXISTS, type = Boolean.class,
description = "Create will fail if provided ID already exists. Default: true")
},
method = HttpMethod.POST,
tags = {TAG}
)
@Override
public void create(@NotNull Context ctx) {
try (final Timer.Context ignored = markAndTime(CREATE)) {
DSLContext dsl = getDslContext(ctx);
String formatHeader = ctx.req.getContentType();
String body = ctx.body();
ContentType contentType = Formats.parseHeader(formatHeader, TimeSeriesIdentifierDescriptor.class);
TimeSeriesIdentifierDescriptor tsid = Formats.parseContent(contentType, body,
TimeSeriesIdentifierDescriptor.class);
TimeSeriesIdentifierDescriptorDao dao = new TimeSeriesIdentifierDescriptorDao(dsl);
// these could be made optional queryParams
boolean versioned = false;
Number numForwards = null;
Number numBackwards = null;
boolean failIfExists = ctx.queryParamAsClass(FAIL_IF_EXISTS, Boolean.class).getOrDefault(true);
dao.create(tsid, versioned, numForwards, numBackwards, failIfExists);
ctx.status(HttpServletResponse.SC_CREATED);
}
}
@OpenApi(
pathParams = {
@OpenApiParam(name = NAME, description = "The timeseries id"),
},
queryParams = {
@OpenApiParam(name = OFFICE, required = true, description = "Specifies the "
+ "owning office of the timeseries identifier to be updated"),
@OpenApiParam(name = TIMESERIES_ID, description = "A new timeseries-id. "
+ "If specified a rename operation will be performed and "
+ SNAP_FORWARD + ", " + SNAP_BACKWARD + ", and " + ACTIVE + " must not be provided"),
@OpenApiParam(name = INTERVAL_OFFSET, type = Long.class,
description = "The offset into the data interval in minutes. "
+ "If specified and a new timeseries-id is also specified both will be passed to a "
+ "rename operation. May also be passed to update operation."),
@OpenApiParam(name = SNAP_FORWARD, type = Long.class,
description = "The new snap forward tolerance in minutes. "
+ "This specifies how many minutes before the expected data time "
+ "that data will be considered to be on time."),
@OpenApiParam(name = SNAP_BACKWARD, type = Long.class,
description = "The new snap backward tolerance in minutes. "
+ "This specifies how many minutes after the expected data time "
+ "that data will be considered to be on time."),
@OpenApiParam(name = ACTIVE, type = Boolean.class,
description = "'True' or 'true' if the time series is active")
}, tags = {TAG}
)
@Override
public void update(@NotNull Context ctx, @NotNull String name) {
String office = requiredParam(ctx, OFFICE);
String newTimeseriesId = ctx.queryParam(TIMESERIES_ID);
Long intervalOffset = ctx.queryParamAsClass(INTERVAL_OFFSET, Long.class).getOrDefault(null);
List<String> updateKeys = Arrays.asList(SNAP_FORWARD, SNAP_BACKWARD, ACTIVE, INTERVAL_OFFSET);
Map<String, List<String>> paramMap = ctx.queryParamMap();
List<String> foundUpdateKeys = updateKeys.stream()
.filter(paramMap::containsKey)
.collect(Collectors.toList());
if (!foundUpdateKeys.isEmpty() && newTimeseriesId != null) {
throw new IllegalArgumentException("Cannot specify a new timeseries-id and any of the"
+ " following update parameters: " + foundUpdateKeys);
}
try (final Timer.Context ignored = markAndTime(UPDATE)) {
DSLContext dsl = getDslContext(ctx);
TimeSeriesIdentifierDescriptorDao dao = new TimeSeriesIdentifierDescriptorDao(dsl);
if (foundUpdateKeys.isEmpty()) {
// basic rename.
dao.rename(office, name, newTimeseriesId, intervalOffset);
} else {
Long forward = ctx.queryParamAsClass(SNAP_FORWARD, Long.class).getOrDefault(null);
Long backward = ctx.queryParamAsClass(SNAP_BACKWARD, Long.class).getOrDefault(null);
boolean active = ctx.queryParamAsClass(ACTIVE, Boolean.class).getOrDefault(true);
dao.update(office, name, intervalOffset, forward, backward, active);
}
}
}
@OpenApi(
pathParams = {
@OpenApiParam(name = TIMESERIES_ID, required = true,
description = "The timeseries-id of the timeseries to be deleted. "),
},
queryParams = {
@OpenApiParam(name = OFFICE, required = true, description = "Specifies the "
+ "owning office of the timeseries to be deleted."),
@OpenApiParam(name = METHOD, required = true, description = "Specifies the delete method used.",
type = JooqDao.DeleteMethod.class)
},
description = "Deletes requested timeseries identifier",
method = HttpMethod.DELETE,
tags = {TAG}
)
@Override
public void delete(@NotNull Context ctx, @NotNull String timeseriesId) {
JooqDao.DeleteMethod method =requiredParamAs(ctx, METHOD, JooqDao.DeleteMethod.class);
String office = requiredParam(ctx, OFFICE);
try (final Timer.Context ignored = markAndTime(DELETE)) {
DSLContext dsl = getDslContext(ctx);
logger.atFine().log("Deleting timeseries:%s from office:%s", timeseriesId, office);
TimeSeriesIdentifierDescriptorDao dao = new TimeSeriesIdentifierDescriptorDao(dsl);
dao.delete(office, timeseriesId, method);
ctx.status(HttpServletResponse.SC_OK);
} catch (DataAccessException ex) {
CdaError re = ErrorTraceSupport.buildError(ctx, "Internal Error", ex);
logger.atSevere().withCause(ex).log("%s", re.toString());
ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re);
}
}
}