Search in sources :

Example 1 with ContentType

use of cwms.radar.formatters.ContentType in project cwms-radar-api by USACE.

the class TimeSeriesController method getAll.

@OpenApi(queryParams = { @OpenApiParam(name = "name", required = true, description = "Specifies the name(s) of the time series whose data is to be included in the response. A case insensitive comparison is used to match names."), @OpenApiParam(name = "office", required = false, description = "Specifies the owning office of the time series(s) whose data is to be included in the response. If this field is not specified, matching location level information from all offices shall be returned."), @OpenApiParam(name = "unit", required = false, description = "Specifies the unit or unit system of the response. Valid values for the unit field are:\r\n 1. EN.   (default) Specifies English unit system.  Location level values will be in the default English units for their parameters.\r\n2. SI.   Specifies the SI unit system.  Location level values will be in the default SI units for their parameters.\r\n3. Other. Any unit returned in the response to the units URI request that is appropriate for the requested parameters."), @OpenApiParam(name = "datum", required = false, description = "Specifies the elevation datum of the response. This field affects only elevation location levels. Valid values for this field are:\r\n1. NAVD88.  The elevation values will in the specified or default units above the NAVD-88 datum.\r\n2. NGVD29.  The elevation values will be in the specified or default units above the NGVD-29 datum."), @OpenApiParam(name = "begin", required = false, description = "Specifies the start of the time window for data to be included in the response. If this field is not specified, any required time window begins 24 hours prior to the specified or default end time. The format for this field is ISO 8601 extended, with optional offset and timezone, i.e., 'YYYY-MM-dd'T'hh:mm:ss[Z'['VV']']', e.g., '2021-06-10T13:00:00-0700[PST8PDT]'."), @OpenApiParam(name = "end", required = false, description = "Specifies the end of the time window for data to be included in the response. If this field is not specified, any required time window ends at the current time. The format for this field is ISO 8601 extended, with optional timezone, i.e., 'YYYY-MM-dd'T'hh:mm:ss[Z'['VV']']', e.g., '2021-06-10T13:00:00-0700[PST8PDT]'."), @OpenApiParam(name = "timezone", required = false, description = "Specifies 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.\r\nIgnored if begin was specified with offset and timezone."), @OpenApiParam(name = "format", required = false, description = "Specifies the encoding format of the response. Valid values for the format field for this URI are:\r\n1.    tab\r\n2.    csv\r\n3.    xml\r\n4.  wml2 (only if name field is specified)\r\n5.    json (default)"), @OpenApiParam(name = "page", required = false, 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 = "pageSize", required = false, type = Integer.class, description = "How many entries per page returned. Default " + defaultPageSize + ".") }, responses = { @OpenApiResponse(status = "200", description = "A list of elements of the data set you've selected.", content = { @OpenApiContent(from = TimeSeries.class, type = Formats.JSONV2), @OpenApiContent(from = TimeSeries.class, type = Formats.XML) }), @OpenApiResponse(status = "400", description = "Invalid parameter combination"), @OpenApiResponse(status = "404", description = "The provided combination of parameters did not find a timeseries."), @OpenApiResponse(status = "501", description = "Requested format is not implemented") }, method = HttpMethod.GET, tags = { "TimeSeries" })
@Override
public void getAll(Context ctx) {
    getAllRequests.mark();
    try (final Timer.Context timeContext = getAllRequestsTime.time();
        DSLContext dsl = getDslContext(ctx)) {
        TimeSeriesDao dao = getTimeSeriesDao(dsl);
        String format = ctx.queryParamAsClass("format", String.class).getOrDefault("");
        String names = ctx.queryParam("name");
        String office = ctx.queryParam("office");
        String unit = ctx.queryParamAsClass("unit", String.class).getOrDefault(UnitSystem.EN.getValue());
        String datum = ctx.queryParam("datum");
        String begin = ctx.queryParam("begin");
        String end = ctx.queryParam("end");
        String timezone = ctx.queryParamAsClass("timezone", String.class).getOrDefault("UTC");
        // The following parameters are only used for jsonv2 and xmlv2
        String cursor = ctx.queryParamAsClass("cursor", String.class).getOrDefault(ctx.queryParamAsClass("page", String.class).getOrDefault(""));
        int pageSize = ctx.queryParamAsClass("pageSize", Integer.class).getOrDefault(ctx.queryParamAsClass("pagesize", Integer.class).getOrDefault(defaultPageSize));
        String acceptHeader = ctx.header(Header.ACCEPT);
        ContentType contentType = Formats.parseHeaderAndQueryParm(acceptHeader, format);
        String results;
        String version = contentType.getParameters().get("version");
        ZoneId tz = ZoneId.of(timezone, ZoneId.SHORT_IDS);
        begin = begin != null ? begin : "PT-24H";
        ZonedDateTime beginZdt = DateUtils.parseUserDate(begin, timezone);
        ZonedDateTime endZdt = end != null ? DateUtils.parseUserDate(end, timezone) : ZonedDateTime.now(tz);
        if (version != null && version.equals("2")) {
            TimeSeries ts = dao.getTimeseries(cursor, pageSize, names, office, unit, datum, beginZdt, endZdt, tz);
            results = Formats.format(contentType, ts);
            ctx.status(HttpServletResponse.SC_OK);
            // Send back the link to the next page in the response header
            StringBuffer linkValue = new StringBuffer(600);
            linkValue.append(String.format("<%s>; rel=self; type=\"%s\"", buildRequestUrl(ctx, ts, ts.getPage()), contentType));
            if (ts.getNextPage() != null) {
                linkValue.append(",");
                linkValue.append(String.format("<%s>; rel=next; type=\"%s\"", buildRequestUrl(ctx, ts, ts.getNextPage()), contentType));
            }
            ctx.header("Link", linkValue.toString());
            ctx.result(results).contentType(contentType.toString());
        } else {
            if (format == null || format.isEmpty()) {
                format = "json";
            }
            results = dao.getTimeseries(format, names, office, unit, datum, beginZdt, endZdt, tz);
            ctx.status(HttpServletResponse.SC_OK);
            ctx.result(results);
        }
        requestResultSize.update(results.length());
    } catch (NotFoundException e) {
        RadarError re = new RadarError("Not found.");
        logger.log(Level.WARNING, re.toString(), e);
        ctx.status(HttpServletResponse.SC_NOT_FOUND);
        ctx.json(re);
    } catch (IllegalArgumentException ex) {
        RadarError re = new RadarError("Invalid arguments supplied");
        logger.log(Level.SEVERE, re.toString(), ex);
        ctx.status(HttpServletResponse.SC_BAD_REQUEST);
        ctx.json(re);
    }
}
Also used : TimeSeries(cwms.radar.data.dto.TimeSeries) ContentType(cwms.radar.formatters.ContentType) ZoneId(java.time.ZoneId) DSLContext(org.jooq.DSLContext) RadarError(cwms.radar.api.errors.RadarError) Timer(com.codahale.metrics.Timer) ZonedDateTime(java.time.ZonedDateTime) TimeSeriesDao(cwms.radar.data.dao.TimeSeriesDao) OpenApi(io.javalin.plugin.openapi.annotations.OpenApi)

Example 2 with ContentType

use of cwms.radar.formatters.ContentType in project cwms-radar-api by USACE.

the class TimeSeriesGroupController method getOne.

@OpenApi(pathParams = { @OpenApiParam(name = "group-id", required = true, description = "Specifies the timeseries group whose data is to be included in the response") }, queryParams = { @OpenApiParam(name = "office", required = true, description = "Specifies the owning office of the timeseries group whose data is to be included in the response."), @OpenApiParam(name = "category-id", required = true, description = "Specifies the category containing the timeseries group whose data is to be included in the response.") }, responses = { @OpenApiResponse(status = "200", content = { @OpenApiContent(from = TimeSeriesGroup.class, type = Formats.JSON) }) }, description = "Retrieves requested timeseries group", tags = { "Timeseries Groups" })
@Override
public void getOne(Context ctx, String groupId) {
    getOneRequest.mark();
    try (final Timer.Context timeContext = getOneRequestTime.time();
        DSLContext dsl = getDslContext(ctx)) {
        TimeSeriesGroupDao dao = new TimeSeriesGroupDao(dsl);
        String office = ctx.queryParam("office");
        String categoryId = ctx.queryParam("category-id");
        String formatHeader = ctx.header(Header.ACCEPT);
        ContentType contentType = Formats.parseHeaderAndQueryParm(formatHeader, null);
        TimeSeriesGroup group = null;
        List<TimeSeriesGroup> timeSeriesGroups = dao.getTimeSeriesGroups(office, categoryId, groupId);
        if (timeSeriesGroups != null && !timeSeriesGroups.isEmpty()) {
            if (timeSeriesGroups.size() == 1) {
                group = timeSeriesGroups.get(0);
            } else {
                // An error. [office, categoryId, groupId] should have, at most, one match
                String message = String.format("Multiple TimeSeriesGroups returned from getTimeSeriesGroups " + "for:%s category:%s groupId:%s At most one match was expected. Found:%s", office, categoryId, groupId, timeSeriesGroups);
                throw new IllegalArgumentException(message);
            }
        }
        if (group != null) {
            String result = Formats.format(contentType, group);
            ctx.result(result);
            ctx.contentType(contentType.toString());
            requestResultSize.update(result.length());
            ctx.status(HttpServletResponse.SC_OK);
        } else {
            RadarError re = new RadarError("Unable to find group based on parameters given");
            logger.info(() -> new StringBuilder().append(re.toString()).append(System.lineSeparator()).append("for request ").append(ctx.fullUrl()).toString());
            ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re);
        }
    }
}
Also used : TimeSeriesGroup(cwms.radar.data.dto.TimeSeriesGroup) RadarError(cwms.radar.api.errors.RadarError) Timer(com.codahale.metrics.Timer) ContentType(cwms.radar.formatters.ContentType) DSLContext(org.jooq.DSLContext) TimeSeriesGroupDao(cwms.radar.data.dao.TimeSeriesGroupDao) OpenApi(io.javalin.plugin.openapi.annotations.OpenApi)

Example 3 with ContentType

use of cwms.radar.formatters.ContentType in project cwms-radar-api by USACE.

the class TimeseriesCatalogEntryTest method test_xml_serialization_earliest.

@Test
void test_xml_serialization_earliest() {
    CatalogEntry entry = buildEntry();
    Catalog cat = new Catalog(null, 1, 10, new ArrayList<CatalogEntry>() {

        {
            add(entry);
        }
    });
    ContentType contentType = Formats.parseHeader(Formats.XML);
    String xml = Formats.format(contentType, cat);
    assertNotNull(xml);
    assertFalse(xml.isEmpty());
    XmlPath path = XmlPath.from(xml);
    assertThat(path.getString("catalog.entries.entry.@name"), equalTo("Barren-Lake.Elev.Inst.0.0.USGS-raw"));
    assertThat(path.getString("catalog.entries.entry.units"), equalTo("m"));
    assertThat(path.getInt("catalog.entries.entry.interval"), equalTo(0));
    assertThat(path.getLong("catalog.entries.entry.interval-offset"), equalTo(-2147483648L));
    assertThat(path.getString("catalog.entries.entry.time-zone"), equalTo("US/Central"));
    Object tmp = path.get("catalog.entries.entry.extents");
    System.out.println(tmp.toString());
    assertThat(path.getString("catalog.entries.entry.extents.extents.earliest-time"), equalTo("2017-07-27T05:00:00Z"));
    assertThat(path.getString("catalog.entries.entry.extents.extents.latest-time"), equalTo("2017-11-24T22:30:00Z"));
}
Also used : XmlPath(io.restassured.path.xml.XmlPath) ContentType(cwms.radar.formatters.ContentType) Catalog(cwms.radar.data.dto.Catalog) Test(org.junit.jupiter.api.Test)

Example 4 with ContentType

use of cwms.radar.formatters.ContentType in project cwms-radar-api by USACE.

the class ClobController method getAll.

@OpenApi(queryParams = { @OpenApiParam(name = "office", required = false, description = "Specifies the owning office. If this field is not specified, matching information from all offices shall be returned."), @OpenApiParam(name = "page", required = false, 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 = "pageSize", required = false, type = Integer.class, description = "How many entries per page returned. Default " + defaultPageSize + "."), @OpenApiParam(name = "includeValues", required = false, type = Boolean.class, description = "Do you want the value associated with this particular clob (default: false)"), @OpenApiParam(name = "like", required = false, type = String.class, description = "Posix regular expression matching against the id") }, responses = { @OpenApiResponse(status = "200", description = "A list of clobs.", content = { @OpenApiContent(type = Formats.JSONV2, from = Clobs.class), @OpenApiContent(type = Formats.XMLV2, from = Clobs.class) }) }, tags = { "Clob" })
@Override
public void getAll(Context ctx) {
    getAllRequests.mark();
    try (final Timer.Context timeContext = getAllRequestsTime.time();
        DSLContext dsl = getDslContext(ctx)) {
        String office = ctx.queryParam("office");
        Optional<String> officeOpt = Optional.ofNullable(office);
        String formatParm = ctx.queryParamAsClass("format", String.class).getOrDefault("");
        String formatHeader = ctx.header(Header.ACCEPT);
        ContentType contentType = Formats.parseHeaderAndQueryParm(formatHeader, formatParm);
        String cursor = ctx.queryParamAsClass("cursor", String.class).allowNullable().get();
        cursor = cursor != null ? cursor : ctx.queryParamAsClass("page", String.class).getOrDefault("");
        if (!CwmsDTOPaginated.CURSOR_CHECK.invoke(cursor)) {
            ctx.json(new RadarError("cursor or page passed in but failed validation")).status(HttpCode.BAD_REQUEST);
            return;
        }
        int pageSize = ctx.queryParamAsClass("pageSize", Integer.class).getOrDefault(ctx.queryParamAsClass("pagesize", Integer.class).getOrDefault(defaultPageSize));
        boolean includeValues = ctx.queryParamAsClass("includeValues", Boolean.class).getOrDefault(false);
        String like = ctx.queryParamAsClass("like", String.class).getOrDefault(".*");
        ClobDao dao = new ClobDao(dsl);
        Clobs clobs = dao.getClobs(cursor, pageSize, officeOpt, includeValues, like);
        String result = Formats.format(contentType, clobs);
        ctx.result(result);
        ctx.contentType(contentType.toString());
        requestResultSize.update(result.length());
    }
}
Also used : ClobDao(cwms.radar.data.dao.ClobDao) ContentType(cwms.radar.formatters.ContentType) DSLContext(org.jooq.DSLContext) RadarError(cwms.radar.api.errors.RadarError) Timer(com.codahale.metrics.Timer) Clobs(cwms.radar.data.dto.Clobs) OpenApi(io.javalin.plugin.openapi.annotations.OpenApi)

Example 5 with ContentType

use of cwms.radar.formatters.ContentType in project cwms-radar-api by USACE.

the class LevelsController method create.

@OpenApi(queryParams = { @OpenApiParam(name = "office", required = true, description = "Specifies the office in which Location Level will be created") }, requestBody = @OpenApiRequestBody(content = { @OpenApiContent(from = LocationLevel.class, type = Formats.JSON), @OpenApiContent(from = LocationLevel.class, type = Formats.XML) }, required = true), description = "Create new CWMS Location Level", method = HttpMethod.POST, path = "/levels", tags = { "Levels" })
@Override
public void create(@NotNull Context ctx) {
    try (final Timer.Context timeContext = markAndTime("create");
        DSLContext dsl = getDslContext(ctx)) {
        LocationLevelsDao levelsDao = getLevelsDao(dsl);
        String office = ctx.queryParam("office");
        String reqContentType = ctx.req.getContentType();
        String formatHeader = reqContentType != null ? reqContentType : Formats.JSON;
        ContentType contentType = Formats.parseHeader(formatHeader);
        if (contentType == null) {
            throw new FormattingException("Format header could not be parsed");
        }
        LocationLevel level = deserializeLocationLevel(ctx.body(), formatHeader, office);
        // getUnmarshalledDateTime(ctx.body(), contentType.getType());
        ZonedDateTime unmarshalledDateTime = level.getLevelDate();
        ZoneId timezoneId = unmarshalledDateTime.getZone();
        if (timezoneId == null) {
            timezoneId = ZoneId.systemDefault();
        }
        level = new LocationLevel.Builder(level).withLevelDate(unmarshalledDateTime).build();
        level.validate();
        levelsDao.storeLocationLevel(level, timezoneId);
        ctx.status(HttpServletResponse.SC_ACCEPTED).json("Created Location Level");
    }
}
Also used : LocationLevelsDao(cwms.radar.data.dao.LocationLevelsDao) FormattingException(cwms.radar.formatters.FormattingException) Timer(com.codahale.metrics.Timer) ContentType(cwms.radar.formatters.ContentType) ZoneId(java.time.ZoneId) ZonedDateTime(java.time.ZonedDateTime) DSLContext(org.jooq.DSLContext) LocationLevel(cwms.radar.data.dto.LocationLevel) OpenApi(io.javalin.plugin.openapi.annotations.OpenApi)

Aggregations

ContentType (cwms.radar.formatters.ContentType)31 Timer (com.codahale.metrics.Timer)26 DSLContext (org.jooq.DSLContext)26 OpenApi (io.javalin.plugin.openapi.annotations.OpenApi)22 RadarError (cwms.radar.api.errors.RadarError)21 FormattingException (cwms.radar.formatters.FormattingException)7 LocationsDao (cwms.radar.data.dao.LocationsDao)5 IOException (java.io.IOException)5 TimeSeriesDao (cwms.radar.data.dao.TimeSeriesDao)3 Catalog (cwms.radar.data.dto.Catalog)3 Location (cwms.radar.data.dto.Location)3 Office (cwms.radar.data.dto.Office)3 ZoneId (java.time.ZoneId)3 ZonedDateTime (java.time.ZonedDateTime)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 BasinDao (cwms.radar.data.dao.BasinDao)2 ClobDao (cwms.radar.data.dao.ClobDao)2 LocationCategoryDao (cwms.radar.data.dao.LocationCategoryDao)2 LocationGroupDao (cwms.radar.data.dao.LocationGroupDao)2