use of de.ii.xtraplatform.crs.domain.EpsgCrs in project ldproxy by interactive-instruments.
the class TilesQueriesHandlerImpl method getMultiLayerTileResponse.
private Response getMultiLayerTileResponse(QueryInputTileMultiLayer queryInput, ApiRequestContext requestContext) {
OgcApi api = requestContext.getApi();
OgcApiDataV2 apiData = api.getData();
Tile multiLayerTile = queryInput.getTile();
List<String> collectionIds = multiLayerTile.getCollectionIds();
Map<String, FeatureQuery> queryMap = queryInput.getQueryMap();
Map<String, Tile> singleLayerTileMap = queryInput.getSingleLayerTileMap();
FeatureProvider2 featureProvider = multiLayerTile.getFeatureProvider().get();
TileMatrixSet tileMatrixSet = multiLayerTile.getTileMatrixSet();
int tileLevel = multiLayerTile.getTileLevel();
int tileRow = multiLayerTile.getTileRow();
int tileCol = multiLayerTile.getTileCol();
if (!(multiLayerTile.getOutputFormat() instanceof TileFormatWithQuerySupportExtension))
throw new RuntimeException(String.format("Unexpected tile format without query support. Found: %s", multiLayerTile.getOutputFormat().getClass().getSimpleName()));
TileFormatWithQuerySupportExtension outputFormat = (TileFormatWithQuerySupportExtension) multiLayerTile.getOutputFormat();
// process parameters and generate query
Optional<CrsTransformer> crsTransformer = Optional.empty();
EpsgCrs targetCrs = tileMatrixSet.getCrs();
if (featureProvider.supportsCrs()) {
EpsgCrs sourceCrs = featureProvider.crs().getNativeCrs();
crsTransformer = crsTransformerFactory.getTransformer(sourceCrs, targetCrs);
}
List<Link> links = new DefaultLinksGenerator().generateLinks(requestContext.getUriCustomizer(), requestContext.getMediaType(), requestContext.getAlternateMediaTypes(), i18n, requestContext.getLanguage());
Map<String, ByteArrayOutputStream> byteArrayMap = new HashMap<>();
for (String collectionId : collectionIds) {
// TODO limitation of the current model: all layers have to come from the same feature provider and use the same CRS
Tile tile = singleLayerTileMap.get(collectionId);
if (!multiLayerTile.getTemporary()) {
// use cached tile
try {
Optional<InputStream> tileContent = tileCache.getTile(tile);
if (tileContent.isPresent()) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ByteStreams.copy(tileContent.get(), buffer);
byteArrayMap.put(collectionId, buffer);
continue;
}
} catch (SQLException | IOException e) {
// could not read the cache, generate the tile
}
}
String featureTypeId = apiData.getCollections().get(collectionId).getExtension(FeaturesCoreConfiguration.class).map(cfg -> cfg.getFeatureType().orElse(collectionId)).orElse(collectionId);
FeatureQuery query = queryMap.get(collectionId);
ImmutableFeatureTransformationContextTiles transformationContext;
try {
transformationContext = new ImmutableFeatureTransformationContextTiles.Builder().api(api).apiData(apiData).featureSchema(featureProvider.getData().getTypes().get(featureTypeId)).tile(tile).tileCache(tileCache).collectionId(collectionId).ogcApiRequest(requestContext).crsTransformer(crsTransformer).codelists(entityRegistry.getEntitiesForType(Codelist.class).stream().collect(Collectors.toMap(PersistentEntity::getId, c -> c))).defaultCrs(queryInput.getDefaultCrs()).links(links).isFeatureCollection(true).fields(query.getFields()).limit(query.getLimit()).offset(0).i18n(i18n).outputStream(new OutputStreamToByteConsumer()).build();
} catch (Exception e) {
throw new RuntimeException("Error building the tile transformation context.", e);
}
Optional<FeatureTokenEncoder<?>> encoder = outputFormat.getFeatureEncoder(transformationContext);
if (outputFormat.supportsFeatureQuery() && encoder.isPresent()) {
FeatureStream featureStream = featureProvider.queries().getFeatureStream(query);
ResultReduced<byte[]> result = generateTile(featureStream, encoder.get(), transformationContext, outputFormat);
if (result.isSuccess()) {
byte[] bytes = result.reduced();
ByteArrayOutputStream buffer = new ByteArrayOutputStream(bytes.length);
buffer.write(bytes, 0, bytes.length);
byteArrayMap.put(collectionId, buffer);
}
} else {
throw new NotAcceptableException(MessageFormat.format("The requested media type {0} cannot be generated, because it does not support streaming.", requestContext.getMediaType().type()));
}
}
TileFormatWithQuerySupportExtension.MultiLayerTileContent result;
try {
result = outputFormat.combineSingleLayerTilesToMultiLayerTile(tileMatrixSet, singleLayerTileMap, byteArrayMap);
} catch (IOException e) {
throw new RuntimeException("Error accessing the tile cache.", e);
}
// try to write/update tile in cache, if all collections have been processed
if (result.isComplete) {
try {
tileCache.storeTile(multiLayerTile, result.byteArray);
} catch (Throwable e) {
String msg = "Failure to write the multi-layer file of tile {}/{}/{}/{} in dataset '{}', format '{}' to the cache";
LogContext.errorAsInfo(LOGGER, e, msg, tileMatrixSet.getId(), tileLevel, tileRow, tileCol, api.getId(), outputFormat.getExtension());
}
}
Date lastModified = null;
EntityTag etag = getEtag(result.byteArray);
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_%d_%d_%d.%s", tileMatrixSet.getId(), tileLevel, tileRow, tileCol, outputFormat.getMediaType().fileExtension())).entity(result.byteArray).build();
}
use of de.ii.xtraplatform.crs.domain.EpsgCrs in project ldproxy by interactive-instruments.
the class TileFormatMVT method getMaxAllowableOffset.
@Override
public double getMaxAllowableOffset(Tile tile) {
double maxAllowableOffsetTileMatrixSet = tile.getTileMatrixSet().getMaxAllowableOffset(tile.getTileLevel(), tile.getTileRow(), tile.getTileCol());
Unit<?> tmsCrsUnit = crsInfo.getUnit(tile.getTileMatrixSet().getCrs());
EpsgCrs nativeCrs = crsSupport.getStorageCrs(tile.getApiData(), Optional.empty());
Unit<?> nativeCrsUnit = crsInfo.getUnit(nativeCrs);
if (tmsCrsUnit.equals(nativeCrsUnit))
return maxAllowableOffsetTileMatrixSet;
else if (tmsCrsUnit.equals(Units.DEGREE) && nativeCrsUnit.equals(Units.METRE))
return maxAllowableOffsetTileMatrixSet * 111333.0;
else if (tmsCrsUnit.equals(Units.METRE) && nativeCrsUnit.equals(Units.DEGREE))
return maxAllowableOffsetTileMatrixSet / 111333.0;
LOGGER.error("TileFormatMVT.getMaxAllowableOffset: Cannot convert between axis units '{}' and '{}'.", tmsCrsUnit.getName(), nativeCrsUnit.getName());
return 0;
}
use of de.ii.xtraplatform.crs.domain.EpsgCrs in project ldproxy by interactive-instruments.
the class EndpointRoutesPost method computeRoute.
/**
* creates a new route
*
* @return a route according to the RouteExchangeModel
*/
@POST
@SuppressWarnings("UnstableApiUsage")
public Response computeRoute(@Auth Optional<User> optionalUser, @Context OgcApi api, @Context ApiRequestContext requestContext, @Context UriInfo uriInfo, @Context HttpServletRequest request, byte[] requestBody) {
OgcApiDataV2 apiData = api.getData();
checkAuthorization(apiData, optionalUser);
FeatureProvider2 featureProvider = providers.getFeatureProviderOrThrow(api.getData());
ensureFeatureProviderSupportsRouting(featureProvider);
String featureTypeId = api.getData().getExtension(RoutingConfiguration.class).map(RoutingConfiguration::getFeatureType).orElseThrow(() -> new IllegalStateException("No feature type has been configured for routing."));
EpsgCrs defaultCrs = apiData.getExtension(RoutingConfiguration.class).map(RoutingConfiguration::getDefaultEpsgCrs).orElse(OgcCrs.CRS84);
Map<String, Integer> coordinatePrecision = apiData.getExtension(RoutingConfiguration.class).map(RoutingConfiguration::getCoordinatePrecision).orElse(ImmutableMap.of());
String speedLimitUnit = apiData.getExtension(RoutingConfiguration.class).map(RoutingConfiguration::getSpeedLimitUnit).orElse("kmph");
Double elevationProfileSimplificationTolerance = apiData.getExtension(RoutingConfiguration.class).map(RoutingConfiguration::getElevationProfileSimplificationTolerance).orElse(null);
List<OgcApiQueryParameter> allowedParameters = getQueryParameters(extensionRegistry, api.getData(), "/routes", HttpMethods.POST);
FeatureQuery query = ogcApiFeaturesQuery.requestToBareFeatureQuery(api.getData(), featureTypeId, defaultCrs, coordinatePrecision, 1, Integer.MAX_VALUE, Integer.MAX_VALUE, toFlatMap(uriInfo.getQueryParameters()), allowedParameters);
RouteDefinition definition;
try {
// parse input
definition = mapper.readValue(requestBody, RouteDefinition.class);
} catch (IOException e) {
throw new IllegalArgumentException(String.format("The content of the route definition is invalid: %s", e.getMessage()), e);
}
String routeId = Hashing.murmur3_128().newHasher().putObject(definition, RouteDefinition.FUNNEL).putString(Optional.ofNullable(request.getHeader("crs")).orElse(defaultCrs.toUriString()), StandardCharsets.UTF_8).hash().toString();
if (apiData.getExtension(RoutingConfiguration.class).map(RoutingConfiguration::isManageRoutesEnabled).orElse(false)) {
if (routeRepository.routeExists(apiData, routeId)) {
// If the same route is already stored, just return the stored route
QueryHandlerRoutes.QueryInputRoute queryInput = new ImmutableQueryInputRoute.Builder().routeId(routeId).build();
return queryHandler.handle(QueryHandlerRoutes.Query.GET_ROUTE, queryInput, requestContext);
}
}
QueryHandlerRoutes.QueryInputComputeRoute queryInput = new ImmutableQueryInputComputeRoute.Builder().from(getGenericQueryInput(api.getData())).definition(definition).routeId(routeId).featureProvider(featureProvider).featureTypeId(featureTypeId).query(query).crs(Optional.ofNullable(request.getHeader("crs"))).defaultCrs(defaultCrs).speedLimitUnit(speedLimitUnit).elevationProfileSimplificationTolerance(Optional.ofNullable(elevationProfileSimplificationTolerance)).build();
return queryHandler.handle(QueryHandlerRoutes.Query.COMPUTE_ROUTE, queryInput, requestContext);
}
use of de.ii.xtraplatform.crs.domain.EpsgCrs in project ldproxy by interactive-instruments.
the class FeaturesQueryImpl method requestToFeatureQuery.
@Override
public FeatureQuery requestToFeatureQuery(OgcApiDataV2 apiData, FeatureTypeConfigurationOgcApi collectionData, EpsgCrs defaultCrs, Map<String, Integer> coordinatePrecision, Map<String, String> parameters, List<OgcApiQueryParameter> allowedParameters, String featureId) {
for (OgcApiQueryParameter parameter : allowedParameters) {
parameters = parameter.transformParameters(collectionData, parameters, apiData);
}
final CqlFilter filter = CqlFilter.of(In.of(ScalarLiteral.of(featureId)));
final String collectionId = collectionData.getId();
final String featureTypeId = apiData.getCollections().get(collectionId).getExtension(FeaturesCoreConfiguration.class).map(cfg -> cfg.getFeatureType().orElse(collectionId)).orElse(collectionId);
final ImmutableFeatureQuery.Builder queryBuilder = ImmutableFeatureQuery.builder().type(featureTypeId).filter(filter).returnsSingleFeature(true).crs(defaultCrs);
for (OgcApiQueryParameter parameter : allowedParameters) {
parameter.transformQuery(collectionData, queryBuilder, parameters, apiData);
}
return processCoordinatePrecision(queryBuilder, coordinatePrecision).build();
}
use of de.ii.xtraplatform.crs.domain.EpsgCrs in project ldproxy by interactive-instruments.
the class CapabilityCrs method onStartup.
@Override
public ValidationResult onStartup(OgcApi api, MODE apiValidation) {
Optional<CrsConfiguration> crsConfiguration = api.getData().getExtension(CrsConfiguration.class).filter(ExtensionConfiguration::isEnabled);
if (crsConfiguration.isEmpty()) {
return ValidationResult.of();
}
EpsgCrs defaultCrs = api.getData().getExtension(FeaturesCoreConfiguration.class).map(FeaturesCoreConfiguration::getDefaultEpsgCrs).orElse(OgcCrs.CRS84);
EpsgCrs providerCrs = featuresCoreProviders.getFeatureProvider(api.getData()).flatMap(featureProvider2 -> featureProvider2.getData().getNativeCrs()).orElse(OgcCrs.CRS84);
EpsgCrs lastCrs = null;
try {
lastCrs = defaultCrs;
crsTransformerFactory.getTransformer(providerCrs, defaultCrs);
for (EpsgCrs crs : crsConfiguration.get().getAdditionalCrs()) {
lastCrs = crs;
crsTransformerFactory.getTransformer(providerCrs, crs);
}
} catch (Throwable e) {
return ImmutableValidationResult.builder().mode(apiValidation).addErrors(String.format("Could not find transformation for %s -> %s: %s", providerCrs.toHumanReadableString(), lastCrs.toHumanReadableString(), e.getMessage())).build();
}
try {
lastCrs = defaultCrs;
crsTransformerFactory.getTransformer(defaultCrs, providerCrs);
for (EpsgCrs crs : crsConfiguration.get().getAdditionalCrs()) {
lastCrs = crs;
crsTransformerFactory.getTransformer(crs, providerCrs);
}
} catch (Throwable e) {
return ImmutableValidationResult.builder().mode(apiValidation).addErrors(String.format("Could not find transformation for %s -> %s: %s", lastCrs.toHumanReadableString(), providerCrs.toHumanReadableString(), e.getMessage())).build();
}
return ValidationResult.of();
}
Aggregations