Search in sources :

Example 1 with TileFormatExtension

use of de.ii.ogcapi.tiles.domain.TileFormatExtension in project ldproxy by interactive-instruments.

the class TilesQueriesHandlerImpl method getTileSetResponse.

private Response getTileSetResponse(QueryInputTileSet queryInput, ApiRequestContext requestContext) {
    OgcApi api = requestContext.getApi();
    OgcApiDataV2 apiData = api.getData();
    String tileMatrixSetId = queryInput.getTileMatrixSetId();
    Optional<String> collectionId = queryInput.getCollectionId();
    String definitionPath = queryInput.getPath();
    String path = collectionId.map(value -> definitionPath.replace("{collectionId}", value)).orElse(definitionPath).replace("{tileMatrixSetId}", tileMatrixSetId);
    TileSetFormatExtension outputFormat = api.getOutputFormat(TileSetFormatExtension.class, requestContext.getMediaType(), path, collectionId).orElseThrow(() -> new NotAcceptableException(MessageFormat.format("The requested media type ''{0}'' is not supported for this resource.", requestContext.getMediaType())));
    List<TileFormatExtension> tileFormats = extensionRegistry.getExtensionsForType(TileFormatExtension.class).stream().filter(format -> collectionId.map(s -> format.isApplicable(apiData, s, definitionPath)).orElseGet(() -> format.isApplicable(apiData, definitionPath))).collect(Collectors.toUnmodifiableList());
    DataType dataType = tileFormats.stream().map(TileFormatExtension::getDataType).findAny().orElseThrow(() -> new NotFoundException("No encoding found for this tile set."));
    final TilesLinkGenerator tilesLinkGenerator = new TilesLinkGenerator();
    List<Link> links = tilesLinkGenerator.generateTileSetLinks(requestContext.getUriCustomizer(), requestContext.getMediaType(), requestContext.getAlternateMediaTypes(), tileFormats, i18n, requestContext.getLanguage());
    MinMax zoomLevels = queryInput.getZoomLevels();
    List<Double> center = queryInput.getCenter();
    TileSet tileset = TilesHelper.buildTileSet(api, getTileMatrixSetById(tileMatrixSetId), zoomLevels, center, collectionId, dataType, links, Optional.of(requestContext.getUriCustomizer().copy()), crsTransformerFactory, limitsGenerator, providers, entityRegistry);
    Date lastModified = getLastModified(queryInput, requestContext.getApi());
    EntityTag etag = !outputFormat.getMediaType().type().equals(MediaType.TEXT_HTML_TYPE) || (collectionId.isEmpty() ? apiData.getExtension(HtmlConfiguration.class) : apiData.getExtension(HtmlConfiguration.class, collectionId.get())).map(HtmlConfiguration::getSendEtags).orElse(false) ? getEtag(tileset, TileSet.FUNNEL, outputFormat) : null;
    Response.ResponseBuilder response = evaluatePreconditions(requestContext, lastModified, etag);
    if (Objects.nonNull(response))
        return response.build();
    return prepareSuccessResponse(requestContext, queryInput.getIncludeLinkHeader() ? links : null, lastModified, etag, queryInput.getCacheControl().orElse(null), queryInput.getExpires().orElse(null), null, true, String.format("%s.%s", tileset.getTileMatrixSetId(), outputFormat.getMediaType().fileExtension())).entity(outputFormat.getTileSetEntity(tileset, apiData, collectionId, requestContext)).build();
}
Also used : Date(java.util.Date) Link(de.ii.ogcapi.foundation.domain.Link) LoggerFactory(org.slf4j.LoggerFactory) TileSetFormatExtension(de.ii.ogcapi.tiles.domain.TileSetFormatExtension) EpsgCrs(de.ii.xtraplatform.crs.domain.EpsgCrs) TileSetsFormatExtension(de.ii.ogcapi.tiles.domain.TileSetsFormatExtension) ApiMediaType(de.ii.ogcapi.foundation.domain.ApiMediaType) MediaType(javax.ws.rs.core.MediaType) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) TileMatrixSetRepository(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetRepository) Tile(de.ii.ogcapi.tiles.domain.Tile) ExtensionRegistry(de.ii.ogcapi.foundation.domain.ExtensionRegistry) OutputStreamToByteConsumer(de.ii.xtraplatform.streams.domain.OutputStreamToByteConsumer) PersistentEntity(de.ii.xtraplatform.store.domain.entities.PersistentEntity) HtmlConfiguration(de.ii.ogcapi.html.domain.HtmlConfiguration) ApiRequestContext(de.ii.ogcapi.foundation.domain.ApiRequestContext) FeaturesCoreProviders(de.ii.ogcapi.features.core.domain.FeaturesCoreProviders) ImmutableMap(com.google.common.collect.ImmutableMap) FeatureTokenEncoder(de.ii.xtraplatform.features.domain.FeatureTokenEncoder) OgcApi(de.ii.ogcapi.foundation.domain.OgcApi) Codelist(de.ii.xtraplatform.codelists.domain.Codelist) DefaultLinksGenerator(de.ii.ogcapi.foundation.domain.DefaultLinksGenerator) CompletionException(java.util.concurrent.CompletionException) StreamingOutput(javax.ws.rs.core.StreamingOutput) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ImmutableFeatureTransformationContextTiles(de.ii.ogcapi.tiles.domain.ImmutableFeatureTransformationContextTiles) NotFoundException(javax.ws.rs.NotFoundException) Objects(java.util.Objects) List(java.util.List) TilesQueriesHandler(de.ii.ogcapi.tiles.domain.TilesQueriesHandler) Builder(de.ii.ogcapi.tiles.domain.ImmutableTileSets.Builder) Response(javax.ws.rs.core.Response) OgcApiDataV2(de.ii.ogcapi.foundation.domain.OgcApiDataV2) TileMatrixSet(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSet) CrsTransformerFactory(de.ii.xtraplatform.crs.domain.CrsTransformerFactory) ByteStreams(com.google.common.io.ByteStreams) Sink(de.ii.xtraplatform.streams.domain.Reactive.Sink) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) FeatureTypeConfigurationOgcApi(de.ii.ogcapi.foundation.domain.FeatureTypeConfigurationOgcApi) EntityRegistry(de.ii.xtraplatform.store.domain.entities.EntityRegistry) QueryHandler(de.ii.ogcapi.foundation.domain.QueryHandler) FeatureQuery(de.ii.xtraplatform.features.domain.FeatureQuery) TileFormatWithQuerySupportExtension(de.ii.ogcapi.tiles.domain.TileFormatWithQuerySupportExtension) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CrsTransformer(de.ii.xtraplatform.crs.domain.CrsTransformer) QueryInput(de.ii.ogcapi.foundation.domain.QueryInput) PropertyTransformations(de.ii.xtraplatform.features.domain.transform.PropertyTransformations) HashMap(java.util.HashMap) Singleton(javax.inject.Singleton) TileSet(de.ii.ogcapi.tiles.domain.TileSet) LogContext(de.ii.xtraplatform.base.domain.LogContext) DataType(de.ii.ogcapi.tiles.domain.TileSet.DataType) AutoBind(com.github.azahnen.dagger.annotations.AutoBind) MessageFormat(java.text.MessageFormat) Inject(javax.inject.Inject) ClientBuilder(javax.ws.rs.client.ClientBuilder) TileMatrixSetLimitsGenerator(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetLimitsGenerator) SQLException(java.sql.SQLException) ImmutableList(com.google.common.collect.ImmutableList) QueriesHandler(de.ii.ogcapi.foundation.domain.QueriesHandler) ImmutableTileSets(de.ii.ogcapi.tiles.domain.ImmutableTileSets) FeatureTransformationContextTiles(de.ii.ogcapi.tiles.domain.FeatureTransformationContextTiles) TileCache(de.ii.ogcapi.tiles.domain.TileCache) NotAcceptableException(javax.ws.rs.NotAcceptableException) Logger(org.slf4j.Logger) MinMax(de.ii.ogcapi.tiles.domain.MinMax) I18n(de.ii.ogcapi.foundation.domain.I18n) IOException(java.io.IOException) FeatureStream(de.ii.xtraplatform.features.domain.FeatureStream) EntityTag(javax.ws.rs.core.EntityTag) FeatureProvider2(de.ii.xtraplatform.features.domain.FeatureProvider2) StaticTileProviderStore(de.ii.ogcapi.tiles.domain.StaticTileProviderStore) FeaturesCoreConfiguration(de.ii.ogcapi.features.core.domain.FeaturesCoreConfiguration) SinkReduced(de.ii.xtraplatform.streams.domain.Reactive.SinkReduced) ServerErrorException(javax.ws.rs.ServerErrorException) ResultReduced(de.ii.xtraplatform.features.domain.FeatureStream.ResultReduced) TileSets(de.ii.ogcapi.tiles.domain.TileSets) TileFormatExtension(de.ii.ogcapi.tiles.domain.TileFormatExtension) WebTarget(javax.ws.rs.client.WebTarget) Comparator(java.util.Comparator) InputStream(java.io.InputStream) TileFormatExtension(de.ii.ogcapi.tiles.domain.TileFormatExtension) OgcApi(de.ii.ogcapi.foundation.domain.OgcApi) FeatureTypeConfigurationOgcApi(de.ii.ogcapi.foundation.domain.FeatureTypeConfigurationOgcApi) NotFoundException(javax.ws.rs.NotFoundException) MinMax(de.ii.ogcapi.tiles.domain.MinMax) TileSet(de.ii.ogcapi.tiles.domain.TileSet) Date(java.util.Date) OgcApiDataV2(de.ii.ogcapi.foundation.domain.OgcApiDataV2) Response(javax.ws.rs.core.Response) NotAcceptableException(javax.ws.rs.NotAcceptableException) DataType(de.ii.ogcapi.tiles.domain.TileSet.DataType) EntityTag(javax.ws.rs.core.EntityTag) TileSetFormatExtension(de.ii.ogcapi.tiles.domain.TileSetFormatExtension) Link(de.ii.ogcapi.foundation.domain.Link)

Example 2 with TileFormatExtension

use of de.ii.ogcapi.tiles.domain.TileFormatExtension in project ldproxy by interactive-instruments.

the class TileProviderFeatures method getQueryInput.

@Override
@JsonIgnore
@Value.Derived
public QueryInput getQueryInput(OgcApiDataV2 apiData, URICustomizer uriCustomizer, Map<String, String> queryParameters, List<OgcApiQueryParameter> allowedParameters, QueryInput genericInput, Tile tile) {
    if (!tile.getFeatureProvider().map(FeatureProvider2::supportsQueries).orElse(false)) {
        throw new IllegalStateException("Tile cannot be generated. The feature provider does not support feature queries.");
    }
    TileFormatExtension outputFormat = tile.getOutputFormat();
    List<String> collections = tile.getCollectionIds();
    if (collections.isEmpty()) {
        return new ImmutableQueryInputTileEmpty.Builder().from(genericInput).tile(tile).build();
    }
    if (!(outputFormat instanceof TileFormatWithQuerySupportExtension))
        throw new RuntimeException(String.format("Unexpected tile format without query support. Found: %s", outputFormat.getClass().getSimpleName()));
    // first execute the information that is passed as processing parameters (e.g., "properties")
    Map<String, Object> processingParameters = new HashMap<>();
    for (OgcApiQueryParameter parameter : allowedParameters) {
        processingParameters = parameter.transformContext(null, processingParameters, queryParameters, apiData);
    }
    if (tile.isDatasetTile()) {
        if (!outputFormat.canMultiLayer() && collections.size() > 1)
            throw new NotAcceptableException("The requested tile format supports only a single layer. Please select only a single collection.");
        Map<String, Tile> singleLayerTileMap = collections.stream().collect(ImmutableMap.toImmutableMap(collectionId -> collectionId, collectionId -> new ImmutableTile.Builder().from(tile).collectionIds(ImmutableList.of(collectionId)).isDatasetTile(false).build()));
        Map<String, FeatureQuery> queryMap = collections.stream().filter(collectionId -> {
            Optional<FeaturesCoreConfiguration> featuresConfiguration = apiData.getCollections().get(collectionId).getExtension(FeaturesCoreConfiguration.class);
            return featuresConfiguration.isPresent() && featuresConfiguration.get().getQueryables().isPresent() && !featuresConfiguration.get().getQueryables().get().getSpatial().isEmpty();
        }).collect(ImmutableMap.toImmutableMap(collectionId -> collectionId, collectionId -> {
            String featureTypeId = apiData.getCollections().get(collectionId).getExtension(FeaturesCoreConfiguration.class).map(cfg -> cfg.getFeatureType().orElse(collectionId)).orElse(collectionId);
            TilesConfiguration layerConfiguration = apiData.getExtension(TilesConfiguration.class, collectionId).orElseThrow();
            FeatureQuery query = ((TileFormatWithQuerySupportExtension) outputFormat).getQuery(singleLayerTileMap.get(collectionId), allowedParameters, queryParameters, layerConfiguration, uriCustomizer);
            return ImmutableFeatureQuery.builder().from(query).type(featureTypeId).build();
        }));
        FeaturesCoreConfiguration coreConfiguration = apiData.getExtension(FeaturesCoreConfiguration.class).orElseThrow();
        return new ImmutableQueryInputTileMultiLayer.Builder().from(genericInput).tile(tile).singleLayerTileMap(singleLayerTileMap).queryMap(queryMap).processingParameters(processingParameters).defaultCrs(apiData.getExtension(FeaturesCoreConfiguration.class).map(FeaturesCoreConfiguration::getDefaultEpsgCrs).orElseThrow()).build();
    } else {
        String collectionId = tile.getCollectionId();
        FeatureTypeConfigurationOgcApi featureType = apiData.getCollectionData(collectionId).orElseThrow();
        TilesConfiguration layerConfiguration = apiData.getExtension(TilesConfiguration.class, collectionId).orElseThrow();
        FeatureQuery query = ((TileFromFeatureQuery) outputFormat).getQuery(tile, allowedParameters, queryParameters, layerConfiguration, uriCustomizer);
        FeaturesCoreConfiguration coreConfiguration = featureType.getExtension(FeaturesCoreConfiguration.class).orElseThrow();
        return new ImmutableQueryInputTileSingleLayer.Builder().from(genericInput).tile(tile).query(query).processingParameters(processingParameters).defaultCrs(featureType.getExtension(FeaturesCoreConfiguration.class).map(FeaturesCoreConfiguration::getDefaultEpsgCrs).orElseThrow()).build();
    }
}
Also used : FeatureQuery(de.ii.xtraplatform.features.domain.FeatureQuery) TileFormatWithQuerySupportExtension(de.ii.ogcapi.tiles.domain.TileFormatWithQuerySupportExtension) TileFromFeatureQuery(de.ii.ogcapi.tiles.domain.TileFromFeatureQuery) QueryInput(de.ii.ogcapi.foundation.domain.QueryInput) HashMap(java.util.HashMap) TilesConfiguration(de.ii.ogcapi.tiles.domain.TilesConfiguration) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Value(org.immutables.value.Value) PredefinedFilter(de.ii.ogcapi.tiles.domain.PredefinedFilter) SeedingOptions(de.ii.ogcapi.tiles.domain.SeedingOptions) Rule(de.ii.ogcapi.tiles.domain.Rule) Map(java.util.Map) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) Tile(de.ii.ogcapi.tiles.domain.Tile) Nullable(javax.annotation.Nullable) ImmutableQueryInputTileSingleLayer(de.ii.ogcapi.tiles.domain.ImmutableQueryInputTileSingleLayer) OgcApiQueryParameter(de.ii.ogcapi.foundation.domain.OgcApiQueryParameter) NotAcceptableException(javax.ws.rs.NotAcceptableException) ImmutableMap(com.google.common.collect.ImmutableMap) MinMax(de.ii.ogcapi.tiles.domain.MinMax) URICustomizer(de.ii.ogcapi.foundation.domain.URICustomizer) Maps(com.google.common.collect.Maps) FeatureProvider2(de.ii.xtraplatform.features.domain.FeatureProvider2) FeaturesCoreConfiguration(de.ii.ogcapi.features.core.domain.FeaturesCoreConfiguration) Objects(java.util.Objects) ImmutableQueryInputTileEmpty(de.ii.ogcapi.tiles.domain.ImmutableQueryInputTileEmpty) List(java.util.List) OgcApiDataV2(de.ii.ogcapi.foundation.domain.OgcApiDataV2) TileFormatExtension(de.ii.ogcapi.tiles.domain.TileFormatExtension) TileProvider(de.ii.ogcapi.tiles.domain.TileProvider) ImmutableFeatureQuery(de.ii.xtraplatform.features.domain.ImmutableFeatureQuery) Optional(java.util.Optional) ImmutableTile(de.ii.ogcapi.tiles.domain.ImmutableTile) JsonDeserialize(com.fasterxml.jackson.databind.annotation.JsonDeserialize) FeatureTypeConfigurationOgcApi(de.ii.ogcapi.foundation.domain.FeatureTypeConfigurationOgcApi) ImmutableQueryInputTileMultiLayer(de.ii.ogcapi.tiles.domain.ImmutableQueryInputTileMultiLayer) HashMap(java.util.HashMap) FeatureProvider2(de.ii.xtraplatform.features.domain.FeatureProvider2) ImmutableQueryInputTileMultiLayer(de.ii.ogcapi.tiles.domain.ImmutableQueryInputTileMultiLayer) TilesConfiguration(de.ii.ogcapi.tiles.domain.TilesConfiguration) FeatureQuery(de.ii.xtraplatform.features.domain.FeatureQuery) TileFromFeatureQuery(de.ii.ogcapi.tiles.domain.TileFromFeatureQuery) ImmutableFeatureQuery(de.ii.xtraplatform.features.domain.ImmutableFeatureQuery) ImmutableQueryInputTileEmpty(de.ii.ogcapi.tiles.domain.ImmutableQueryInputTileEmpty) FeatureTypeConfigurationOgcApi(de.ii.ogcapi.foundation.domain.FeatureTypeConfigurationOgcApi) FeaturesCoreConfiguration(de.ii.ogcapi.features.core.domain.FeaturesCoreConfiguration) TileFromFeatureQuery(de.ii.ogcapi.tiles.domain.TileFromFeatureQuery) TileFormatExtension(de.ii.ogcapi.tiles.domain.TileFormatExtension) Optional(java.util.Optional) Tile(de.ii.ogcapi.tiles.domain.Tile) ImmutableTile(de.ii.ogcapi.tiles.domain.ImmutableTile) OgcApiQueryParameter(de.ii.ogcapi.foundation.domain.OgcApiQueryParameter) NotAcceptableException(javax.ws.rs.NotAcceptableException) TileFormatWithQuerySupportExtension(de.ii.ogcapi.tiles.domain.TileFormatWithQuerySupportExtension) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore)

Example 3 with TileFormatExtension

use of de.ii.ogcapi.tiles.domain.TileFormatExtension in project ldproxy by interactive-instruments.

the class AbstractEndpointTileSingleCollection method getTile.

protected Response getTile(OgcApi api, ApiRequestContext requestContext, UriInfo uriInfo, String definitionPath, String collectionId, String tileMatrixSetId, String tileMatrix, String tileRow, String tileCol, TileProvider tileProvider) throws CrsTransformationException, IOException, NotFoundException {
    OgcApiDataV2 apiData = api.getData();
    Map<String, String> queryParams = toFlatMap(uriInfo.getQueryParameters());
    FeatureTypeConfigurationOgcApi featureType = apiData.getCollections().get(collectionId);
    TilesConfiguration tilesConfiguration = featureType.getExtension(TilesConfiguration.class).orElseThrow();
    checkPathParameter(extensionRegistry, apiData, definitionPath, "collectionId", collectionId);
    checkPathParameter(extensionRegistry, apiData, definitionPath, "tileMatrixSetId", tileMatrixSetId);
    checkPathParameter(extensionRegistry, apiData, definitionPath, "tileMatrix", tileMatrix);
    checkPathParameter(extensionRegistry, apiData, definitionPath, "tileRow", tileRow);
    checkPathParameter(extensionRegistry, apiData, definitionPath, "tileCol", tileCol);
    final List<OgcApiQueryParameter> allowedParameters = getQueryParameters(extensionRegistry, apiData, definitionPath, collectionId);
    int row;
    int col;
    int level;
    try {
        level = Integer.parseInt(tileMatrix);
        row = Integer.parseInt(tileRow);
        col = Integer.parseInt(tileCol);
    } catch (NumberFormatException e) {
        throw new ServerErrorException("Could not convert tile coordinates that have been validated to integers", 500);
    }
    MinMax zoomLevels = tilesConfiguration.getZoomLevelsDerived().get(tileMatrixSetId);
    if (zoomLevels.getMax() < level || zoomLevels.getMin() > level)
        throw new NotFoundException("The requested tile is outside the zoom levels for this tile set.");
    TileMatrixSet tileMatrixSet = tileMatrixSetRepository.get(tileMatrixSetId).orElseThrow(() -> new NotFoundException("Unknown tile matrix set: " + tileMatrixSetId));
    TileMatrixSetLimits tileLimits = limitsGenerator.getCollectionTileMatrixSetLimits(api, collectionId, tileMatrixSet, zoomLevels).stream().filter(limits -> limits.getTileMatrix().equals(tileMatrix)).findAny().orElse(null);
    if (tileLimits != null) {
        if (tileLimits.getMaxTileCol() < col || tileLimits.getMinTileCol() > col || tileLimits.getMaxTileRow() < row || tileLimits.getMinTileRow() > row)
            // return 404, if outside the range
            throw new NotFoundException("The requested tile is outside of the limits for this zoom level and tile set.");
    }
    String path = definitionPath.replace("{collectionId}", collectionId).replace("{tileMatrixSetId}", tileMatrixSetId).replace("{tileMatrix}", tileMatrix).replace("{tileRow}", tileRow).replace("{tileCol}", tileCol);
    TileFormatExtension outputFormat = requestContext.getApi().getOutputFormat(TileFormatExtension.class, requestContext.getMediaType(), path, Optional.of(collectionId)).orElseThrow(() -> new NotAcceptableException(MessageFormat.format("The requested media type ''{0}'' is not supported for this resource.", requestContext.getMediaType())));
    Optional<FeatureProvider2> featureProvider = providers.getFeatureProvider(apiData);
    // check, if the cache can be used (no query parameters except f)
    boolean useCache = tileProvider.tilesMayBeCached() && tilesConfiguration.getCache() != TilesConfiguration.TileCacheType.NONE && (queryParams.isEmpty() || (queryParams.size() == 1 && queryParams.containsKey("f")));
    // don't store the tile in the cache if it is outside the range
    MinMax cacheMinMax = tilesConfiguration.getZoomLevelsDerived().get(tileMatrixSetId);
    useCache = useCache && (Objects.isNull(cacheMinMax) || (level <= cacheMinMax.getMax() && level >= cacheMinMax.getMin()));
    Tile tile = new ImmutableTile.Builder().tileMatrixSet(tileMatrixSet).tileLevel(level).tileRow(row).tileCol(col).api(api).apiData(apiData).outputFormat(outputFormat).featureProvider(featureProvider).collectionIds(ImmutableList.of(collectionId)).temporary(!useCache).isDatasetTile(false).build();
    QueryInput queryInput = null;
    // if cache can be used and the tile is cached for the requested format, return the cache
    if (useCache) {
        // get the tile from the cache and return it
        Optional<InputStream> tileStream = Optional.empty();
        try {
            tileStream = cache.getTile(tile);
        } catch (Exception e) {
            LOGGER.warn("Failed to retrieve tile {}/{}/{}/{} for collection '{}' from the cache. Reason: {}", tile.getTileMatrixSet().getId(), tile.getTileLevel(), tile.getTileRow(), tile.getTileCol(), collectionId, e.getMessage());
        }
        if (tileStream.isPresent()) {
            queryInput = new Builder().from(getGenericQueryInput(apiData)).tile(tile).tileContent(tileStream.get()).build();
        }
    }
    // not cached or cache access failed
    if (Objects.isNull(queryInput))
        queryInput = tileProvider.getQueryInput(apiData, requestContext.getUriCustomizer(), queryParams, allowedParameters, getGenericQueryInput(apiData), tile);
    TilesQueriesHandler.Query query = null;
    if (queryInput instanceof TilesQueriesHandler.QueryInputTileMbtilesTile)
        query = TilesQueriesHandler.Query.MBTILES_TILE;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileTileServerTile)
        query = TilesQueriesHandler.Query.TILESERVER_TILE;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileEmpty)
        query = TilesQueriesHandler.Query.EMPTY_TILE;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileStream)
        query = TilesQueriesHandler.Query.TILE_STREAM;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileMultiLayer)
        query = TilesQueriesHandler.Query.MULTI_LAYER_TILE;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileSingleLayer)
        query = TilesQueriesHandler.Query.SINGLE_LAYER_TILE;
    return queryHandler.handle(query, queryInput, requestContext);
}
Also used : TilesQueriesHandler(de.ii.ogcapi.tiles.domain.TilesQueriesHandler) FeatureProvider2(de.ii.xtraplatform.features.domain.FeatureProvider2) Builder(de.ii.ogcapi.tiles.domain.ImmutableQueryInputTileStream.Builder) TilesConfiguration(de.ii.ogcapi.tiles.domain.TilesConfiguration) NotFoundException(javax.ws.rs.NotFoundException) MinMax(de.ii.ogcapi.tiles.domain.MinMax) FeatureTypeConfigurationOgcApi(de.ii.ogcapi.foundation.domain.FeatureTypeConfigurationOgcApi) QueryInput(de.ii.ogcapi.foundation.domain.QueryInput) TileMatrixSetLimits(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetLimits) TileMatrixSet(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSet) TileFormatExtension(de.ii.ogcapi.tiles.domain.TileFormatExtension) InputStream(java.io.InputStream) Tile(de.ii.ogcapi.tiles.domain.Tile) ImmutableTile(de.ii.ogcapi.tiles.domain.ImmutableTile) OgcApiQueryParameter(de.ii.ogcapi.foundation.domain.OgcApiQueryParameter) CrsTransformationException(de.ii.xtraplatform.crs.domain.CrsTransformationException) NotAcceptableException(javax.ws.rs.NotAcceptableException) IOException(java.io.IOException) NotFoundException(javax.ws.rs.NotFoundException) ServerErrorException(javax.ws.rs.ServerErrorException) OgcApiDataV2(de.ii.ogcapi.foundation.domain.OgcApiDataV2) NotAcceptableException(javax.ws.rs.NotAcceptableException) ServerErrorException(javax.ws.rs.ServerErrorException)

Example 4 with TileFormatExtension

use of de.ii.ogcapi.tiles.domain.TileFormatExtension in project ldproxy by interactive-instruments.

the class TileCacheImpl method deleteTilesFiles.

private void deleteTilesFiles(OgcApiDataV2 apiData, Optional<String> collectionId, Map<String, MinMax> zoomLevels, Map<String, BoundingBox> boundingBoxes) throws IOException {
    List<String> extensions = getTileFormats(apiData, collectionId).stream().map(TileFormatExtension::getExtension).collect(ImmutableList.toImmutableList());
    Map<String, Map<String, TileMatrixSetLimits>> limits = zoomLevels.keySet().stream().map(tmsId -> {
        Map<String, TileMatrixSetLimits> limitsMap = getLimits(apiData, getTileMatrixSetById(tmsId), zoomLevels.get(tmsId), collectionId, boundingBoxes.get(tmsId)).stream().map(l -> new SimpleImmutableEntry<>(l.getTileMatrix(), l)).collect(Collectors.toUnmodifiableMap(Entry::getKey, Entry::getValue));
        return new SimpleImmutableEntry<>(tmsId, limitsMap);
    }).collect(Collectors.toUnmodifiableMap(Entry::getKey, Entry::getValue));
    Path basePath = getTilesStore().resolve(apiData.getId());
    try (Stream<Path> walk = Files.find(basePath, 5, (path, basicFileAttributes) -> basicFileAttributes.isRegularFile() && shouldDeleteTileFile(basePath.relativize(path), collectionId, limits, extensions))) {
        walk.map(Path::toFile).forEach(File::delete);
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) LoggerFactory(org.slf4j.LoggerFactory) FileTime(java.nio.file.attribute.FileTime) ImmutableValidationResult(de.ii.xtraplatform.store.domain.entities.ImmutableValidationResult) MbtilesMetadata(de.ii.ogcapi.tiles.app.mbtiles.MbtilesMetadata) MODE(de.ii.xtraplatform.store.domain.entities.ValidationResult.MODE) Locale(java.util.Locale) Map(java.util.Map) TileMatrixSetRepository(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetRepository) Tile(de.ii.ogcapi.tiles.domain.Tile) ExtensionRegistry(de.ii.ogcapi.foundation.domain.ExtensionRegistry) Path(java.nio.file.Path) FeaturesCoreProviders(de.ii.ogcapi.features.core.domain.FeaturesCoreProviders) OgcApi(de.ii.ogcapi.foundation.domain.OgcApi) Set(java.util.Set) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) OgcApiDataV2(de.ii.ogcapi.foundation.domain.OgcApiDataV2) TileMatrixSet(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSet) CrsTransformerFactory(de.ii.xtraplatform.crs.domain.CrsTransformerFactory) Entry(java.util.Map.Entry) Optional(java.util.Optional) BoundingBox(de.ii.xtraplatform.crs.domain.BoundingBox) MbtilesTileset(de.ii.ogcapi.tiles.app.mbtiles.MbtilesTileset) EntityRegistry(de.ii.xtraplatform.store.domain.entities.EntityRegistry) TileFormatWithQuerySupportExtension(de.ii.ogcapi.tiles.domain.TileFormatWithQuerySupportExtension) TileMatrixSetLimits(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetLimits) HashMap(java.util.HashMap) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) Singleton(javax.inject.Singleton) TileSet(de.ii.ogcapi.tiles.domain.TileSet) AutoBind(com.github.azahnen.dagger.annotations.AutoBind) TilesConfiguration(de.ii.ogcapi.tiles.domain.TilesConfiguration) MessageFormat(java.text.MessageFormat) Inject(javax.inject.Inject) TileMatrixSetLimitsGenerator(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetLimitsGenerator) SQLException(java.sql.SQLException) ImmutableList(com.google.common.collect.ImmutableList) ValidationResult(de.ii.xtraplatform.store.domain.entities.ValidationResult) AppContext(de.ii.xtraplatform.base.domain.AppContext) TileCache(de.ii.ogcapi.tiles.domain.TileCache) Logger(org.slf4j.Logger) MinMax(de.ii.ogcapi.tiles.domain.MinMax) Files(java.nio.file.Files) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ImmutableMbtilesMetadata(de.ii.ogcapi.tiles.app.mbtiles.ImmutableMbtilesMetadata) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) File(java.io.File) SchemaInfo(de.ii.ogcapi.features.core.domain.SchemaInfo) TileFormatExtension(de.ii.ogcapi.tiles.domain.TileFormatExtension) CACHE_DIR(de.ii.ogcapi.foundation.domain.FoundationConfiguration.CACHE_DIR) Metadata(de.ii.ogcapi.foundation.domain.Metadata) InputStream(java.io.InputStream) Path(java.nio.file.Path) Entry(java.util.Map.Entry) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File)

Example 5 with TileFormatExtension

use of de.ii.ogcapi.tiles.domain.TileFormatExtension in project ldproxy by interactive-instruments.

the class AbstractEndpointTileMultiCollection method getTile.

protected Response getTile(OgcApi api, ApiRequestContext requestContext, UriInfo uriInfo, String definitionPath, String tileMatrixSetId, String tileMatrix, String tileRow, String tileCol, TileProvider tileProvider) throws CrsTransformationException, IOException, NotFoundException {
    OgcApiDataV2 apiData = api.getData();
    Map<String, String> queryParams = toFlatMap(uriInfo.getQueryParameters());
    TilesConfiguration tilesConfiguration = apiData.getExtension(TilesConfiguration.class).orElseThrow();
    checkPathParameter(extensionRegistry, apiData, definitionPath, "tileMatrixSetId", tileMatrixSetId);
    checkPathParameter(extensionRegistry, apiData, definitionPath, "tileMatrix", tileMatrix);
    checkPathParameter(extensionRegistry, apiData, definitionPath, "tileRow", tileRow);
    checkPathParameter(extensionRegistry, apiData, definitionPath, "tileCol", tileCol);
    final List<OgcApiQueryParameter> allowedParameters = getQueryParameters(extensionRegistry, apiData, definitionPath);
    int row;
    int col;
    int level;
    try {
        level = Integer.parseInt(tileMatrix);
        row = Integer.parseInt(tileRow);
        col = Integer.parseInt(tileCol);
    } catch (NumberFormatException e) {
        throw new ServerErrorException("Could not convert tile coordinates that have been validated to integers", 500);
    }
    MinMax zoomLevels = tilesConfiguration.getZoomLevelsDerived().get(tileMatrixSetId);
    if (zoomLevels.getMax() < level || zoomLevels.getMin() > level)
        throw new NotFoundException("The requested tile is outside the zoom levels for this tile set.");
    TileMatrixSet tileMatrixSet = tileMatrixSetRepository.get(tileMatrixSetId).orElseThrow(() -> new NotFoundException("Unknown tile matrix set: " + tileMatrixSetId));
    TileMatrixSetLimits tileLimits = limitsGenerator.getTileMatrixSetLimits(api, tileMatrixSet, zoomLevels).stream().filter(limits -> limits.getTileMatrix().equals(tileMatrix)).findAny().orElse(null);
    if (tileLimits != null) {
        if (tileLimits.getMaxTileCol() < col || tileLimits.getMinTileCol() > col || tileLimits.getMaxTileRow() < row || tileLimits.getMinTileRow() > row)
            // return 404, if outside the range
            throw new NotFoundException("The requested tile is outside of the limits for this zoom level and tile set.");
    }
    String path = definitionPath.replace("{tileMatrixSetId}", tileMatrixSetId).replace("{tileMatrix}", tileMatrix).replace("{tileRow}", tileRow).replace("{tileCol}", tileCol);
    TileFormatExtension outputFormat = requestContext.getApi().getOutputFormat(TileFormatExtension.class, requestContext.getMediaType(), path, Optional.empty()).orElseThrow(() -> new NotAcceptableException(MessageFormat.format("The requested media type ''{0}'' is not supported for this resource.", requestContext.getMediaType())));
    Optional<FeatureProvider2> featureProvider = providers.getFeatureProvider(apiData);
    List<String> collections = queryParams.containsKey("collections") ? Splitter.on(",").splitToList(queryParams.get("collections")) : apiData.getCollections().values().stream().filter(collection -> apiData.isCollectionEnabled(collection.getId())).filter(collection -> {
        Optional<TilesConfiguration> layerConfiguration = collection.getExtension(TilesConfiguration.class);
        if (layerConfiguration.isEmpty() || !layerConfiguration.get().isEnabled() || !layerConfiguration.get().isMultiCollectionEnabled())
            return false;
        MinMax levels = layerConfiguration.get().getZoomLevelsDerived().get(tileMatrixSetId);
        return !Objects.nonNull(levels) || (levels.getMax() >= level && levels.getMin() <= level);
    }).map(FeatureTypeConfiguration::getId).collect(Collectors.toList());
    // check, if the cache can be used (no query parameters except f)
    boolean useCache = tileProvider.tilesMayBeCached() && tilesConfiguration.getCache() != TilesConfiguration.TileCacheType.NONE && (queryParams.isEmpty() || (queryParams.size() == 1 && queryParams.containsKey("f")));
    // don't store the tile in the cache if it is outside the range
    MinMax cacheMinMax = tilesConfiguration.getZoomLevelsDerived().get(tileMatrixSetId);
    useCache = useCache && (Objects.isNull(cacheMinMax) || (level <= cacheMinMax.getMax() && level >= cacheMinMax.getMin()));
    Tile tile = new ImmutableTile.Builder().tileMatrixSet(tileMatrixSet).tileLevel(level).tileRow(row).tileCol(col).api(api).apiData(apiData).outputFormat(outputFormat).featureProvider(featureProvider).collectionIds(collections).temporary(!useCache).isDatasetTile(true).build();
    QueryInput queryInput = null;
    // if cache can be used and the tile is cached for the requested format, return the cache
    if (useCache) {
        // get the tile from the cache and return it
        Optional<InputStream> tileStream = Optional.empty();
        try {
            tileStream = cache.getTile(tile);
        } catch (Exception e) {
            LOGGER.warn("Failed to retrieve multi-collection tile {}/{}/{}/{} from the cache. Reason: {}", tile.getTileMatrixSet().getId(), tile.getTileLevel(), tile.getTileRow(), tile.getTileCol(), e.getMessage());
        }
        if (tileStream.isPresent()) {
            queryInput = new Builder().from(getGenericQueryInput(apiData)).tile(tile).tileContent(tileStream.get()).build();
        }
    }
    // not cached or cache access failed
    if (Objects.isNull(queryInput))
        queryInput = tileProvider.getQueryInput(apiData, requestContext.getUriCustomizer(), queryParams, allowedParameters, getGenericQueryInput(apiData), tile);
    TilesQueriesHandler.Query query = null;
    if (queryInput instanceof TilesQueriesHandler.QueryInputTileMbtilesTile)
        query = TilesQueriesHandler.Query.MBTILES_TILE;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileTileServerTile)
        query = TilesQueriesHandler.Query.TILESERVER_TILE;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileEmpty)
        query = TilesQueriesHandler.Query.EMPTY_TILE;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileStream)
        query = TilesQueriesHandler.Query.TILE_STREAM;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileMultiLayer)
        query = TilesQueriesHandler.Query.MULTI_LAYER_TILE;
    else if (queryInput instanceof TilesQueriesHandler.QueryInputTileSingleLayer)
        query = TilesQueriesHandler.Query.SINGLE_LAYER_TILE;
    return queryHandler.handle(query, queryInput, requestContext);
}
Also used : Endpoint(de.ii.ogcapi.foundation.domain.Endpoint) CrsTransformationException(de.ii.xtraplatform.crs.domain.CrsTransformationException) LoggerFactory(org.slf4j.LoggerFactory) EndpointTileMultiCollection(de.ii.ogcapi.tiles.infra.EndpointTileMultiCollection) Map(java.util.Map) TileMatrixSetRepository(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetRepository) ImmutableOgcApiResourceData(de.ii.ogcapi.collections.domain.ImmutableOgcApiResourceData) Tile(de.ii.ogcapi.tiles.domain.Tile) ExtensionRegistry(de.ii.ogcapi.foundation.domain.ExtensionRegistry) Splitter(com.google.common.base.Splitter) ApiOperation(de.ii.ogcapi.foundation.domain.ApiOperation) ApiRequestContext(de.ii.ogcapi.foundation.domain.ApiRequestContext) FeaturesCoreProviders(de.ii.ogcapi.features.core.domain.FeaturesCoreProviders) OgcApi(de.ii.ogcapi.foundation.domain.OgcApi) HttpMethods(de.ii.ogcapi.foundation.domain.HttpMethods) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) ImmutableApiEndpointDefinition(de.ii.ogcapi.foundation.domain.ImmutableApiEndpointDefinition) Objects(java.util.Objects) ApiEndpointDefinition(de.ii.ogcapi.foundation.domain.ApiEndpointDefinition) List(java.util.List) TilesQueriesHandler(de.ii.ogcapi.tiles.domain.TilesQueriesHandler) Response(javax.ws.rs.core.Response) OgcApiDataV2(de.ii.ogcapi.foundation.domain.OgcApiDataV2) TileMatrixSet(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSet) CrsTransformerFactory(de.ii.xtraplatform.crs.domain.CrsTransformerFactory) TileProvider(de.ii.ogcapi.tiles.domain.TileProvider) Optional(java.util.Optional) FormatExtension(de.ii.ogcapi.foundation.domain.FormatExtension) ImmutableTile(de.ii.ogcapi.tiles.domain.ImmutableTile) UriInfo(javax.ws.rs.core.UriInfo) TileMatrixSetLimits(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetLimits) ExtensionConfiguration(de.ii.ogcapi.foundation.domain.ExtensionConfiguration) OgcApiPathParameter(de.ii.ogcapi.foundation.domain.OgcApiPathParameter) QueryInput(de.ii.ogcapi.foundation.domain.QueryInput) TilesConfiguration(de.ii.ogcapi.tiles.domain.TilesConfiguration) MessageFormat(java.text.MessageFormat) TileMatrixSetLimitsGenerator(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetLimitsGenerator) FeatureTypeConfiguration(de.ii.xtraplatform.features.domain.FeatureTypeConfiguration) OgcApiQueryParameter(de.ii.ogcapi.foundation.domain.OgcApiQueryParameter) TileCache(de.ii.ogcapi.tiles.domain.TileCache) NotAcceptableException(javax.ws.rs.NotAcceptableException) Logger(org.slf4j.Logger) MinMax(de.ii.ogcapi.tiles.domain.MinMax) IOException(java.io.IOException) FeatureProvider2(de.ii.xtraplatform.features.domain.FeatureProvider2) StaticTileProviderStore(de.ii.ogcapi.tiles.domain.StaticTileProviderStore) ServerErrorException(javax.ws.rs.ServerErrorException) TileFormatExtension(de.ii.ogcapi.tiles.domain.TileFormatExtension) Builder(de.ii.ogcapi.tiles.domain.ImmutableQueryInputTileStream.Builder) InputStream(java.io.InputStream) TilesQueriesHandler(de.ii.ogcapi.tiles.domain.TilesQueriesHandler) FeatureProvider2(de.ii.xtraplatform.features.domain.FeatureProvider2) Builder(de.ii.ogcapi.tiles.domain.ImmutableQueryInputTileStream.Builder) TilesConfiguration(de.ii.ogcapi.tiles.domain.TilesConfiguration) NotFoundException(javax.ws.rs.NotFoundException) MinMax(de.ii.ogcapi.tiles.domain.MinMax) QueryInput(de.ii.ogcapi.foundation.domain.QueryInput) TileMatrixSetLimits(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSetLimits) TileMatrixSet(de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSet) TileFormatExtension(de.ii.ogcapi.tiles.domain.TileFormatExtension) Optional(java.util.Optional) InputStream(java.io.InputStream) Tile(de.ii.ogcapi.tiles.domain.Tile) ImmutableTile(de.ii.ogcapi.tiles.domain.ImmutableTile) OgcApiQueryParameter(de.ii.ogcapi.foundation.domain.OgcApiQueryParameter) Endpoint(de.ii.ogcapi.foundation.domain.Endpoint) CrsTransformationException(de.ii.xtraplatform.crs.domain.CrsTransformationException) NotFoundException(javax.ws.rs.NotFoundException) NotAcceptableException(javax.ws.rs.NotAcceptableException) IOException(java.io.IOException) ServerErrorException(javax.ws.rs.ServerErrorException) OgcApiDataV2(de.ii.ogcapi.foundation.domain.OgcApiDataV2) NotAcceptableException(javax.ws.rs.NotAcceptableException) FeatureTypeConfiguration(de.ii.xtraplatform.features.domain.FeatureTypeConfiguration) ServerErrorException(javax.ws.rs.ServerErrorException)

Aggregations

OgcApiDataV2 (de.ii.ogcapi.foundation.domain.OgcApiDataV2)6 MinMax (de.ii.ogcapi.tiles.domain.MinMax)6 Tile (de.ii.ogcapi.tiles.domain.Tile)6 TileFormatExtension (de.ii.ogcapi.tiles.domain.TileFormatExtension)6 QueryInput (de.ii.ogcapi.foundation.domain.QueryInput)5 FeatureProvider2 (de.ii.xtraplatform.features.domain.FeatureProvider2)5 List (java.util.List)5 Map (java.util.Map)5 Objects (java.util.Objects)5 Optional (java.util.Optional)5 NotAcceptableException (javax.ws.rs.NotAcceptableException)5 ImmutableList (com.google.common.collect.ImmutableList)4 FeaturesCoreProviders (de.ii.ogcapi.features.core.domain.FeaturesCoreProviders)4 ExtensionRegistry (de.ii.ogcapi.foundation.domain.ExtensionRegistry)4 FeatureTypeConfigurationOgcApi (de.ii.ogcapi.foundation.domain.FeatureTypeConfigurationOgcApi)4 OgcApi (de.ii.ogcapi.foundation.domain.OgcApi)4 TileFormatWithQuerySupportExtension (de.ii.ogcapi.tiles.domain.TileFormatWithQuerySupportExtension)4 TileMatrixSet (de.ii.ogcapi.tiles.domain.tileMatrixSet.TileMatrixSet)4 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4