Exemplo n.º 1
0
 def encode(cls, value):
     """ Encode value to a Unicode string."""
     if value == 0:
         return u'ImageCRS'
     elif validateEPSGCode(value):
         return unicode(asURL(value))
     raise ValueError("Invalid CRS %r!" % value)
Exemplo n.º 2
0
 def encode(cls, value):
     """ Encode value to a unicode string."""
     if value == 0:
         return u'ImageCRS'
     elif validateEPSGCode(value):
         return unicode(asURL(value))
     raise ValueError("Invalid CRS %r!" % value)
Exemplo n.º 3
0
 def parse(cls, raw_value):
     """ Cast or parse input to its proper represenation."""
     if isinstance(raw_value, cls.dtype):
         if raw_value == 0 or validateEPSGCode(raw_value):
             return raw_value
     else:
         if raw_value == "ImageCRS":
             return 0
         else:
             value = parseEPSGCode(raw_value, (fromURL, fromURN, fromShortCode))
             if value is not None:
                 return value
     raise ValueError("Invalid CRS %r!" % raw_value)
Exemplo n.º 4
0
 def parse(cls, raw_value):
     """ Cast or parse input to its proper representation."""
     if isinstance(raw_value, cls.dtype):
         if raw_value == 0 or validateEPSGCode(raw_value):
             return raw_value
     else:
         if raw_value == "ImageCRS":
             return 0
         else:
             value = parseEPSGCode(raw_value,
                                   (fromURL, fromURN, fromShortCode))
             if value is not None:
                 return value
     raise ValueError("Invalid CRS %r!" % raw_value)
Exemplo n.º 5
0
    def readFromDataset(cls, ds, default_srid=None):
        """
        This class method returns a :class:`GeospatialMetadata` object
        initialized with the metadata read from the GDAL dataset ``ds``. It
        expects an open :class:`osgeo.gdal.Dataset` object as input. Furthermore
        it accepts an optional integer ``default_srid`` parameter that will be
        used to set the SRID if it cannot be retrieved from the dataset.
        """

        size_x = ds.RasterXSize
        size_y = ds.RasterYSize
        
        is_ref = ds.GetGCPCount() > 0 

        proj   = ds.GetGCPProjection() if is_ref else ds.GetProjection() 

        if not isinstance(proj,basestring) or len(proj)<1 : 
            raise RuntimeError("Failed to extract CRS (projection) of the "
                    "dataset!" ) 
                
        # convert projection to EPSG code 

        srs = osr.SpatialReference()
    
        try:
            srs.ImportFromWkt( proj )
            srs.AutoIdentifyEPSG()
            ptype = "PROJCS" if srs.IsProjected() else "GEOGCS"
            srid = int(srs.GetAuthorityCode(ptype))

        except (RuntimeError, TypeError), e:
            logger.warn("Projection: %s" % proj) 
            logger.warn("Failed to identify projection's EPSG code."
                "%s: %s" % ( type(e).__name__ , str(e) ) ) 

            if default_srid is not None:
                logger.warn("Using the provided SRID '%s' instead."
                   % str(default_srid) )
            else:
                raise RuntimeError("Unknown SRS and no default supplied.")

            #validate the default SRID 
            if not crss.validateEPSGCode( default_srid ) : 
                raise RuntimeError("The default SRID '%s' is not a valid" 
                    " EPSG code." % str(default_srid) )

            srid = int(default_srid)
Exemplo n.º 6
0
    def render(self, params):
        # get coverage related stuff
        coverage = params.coverage

        # ReferenceableDataset are not supported in WCS < 2.0
        if issubclass(coverage.real_type, models.ReferenceableDataset):
            raise NoSuchCoverageException((coverage.identifier,))

        data_items = self.data_items_for_coverage(coverage)

        range_type = coverage.range_type
        bands = list(range_type)

        subsets = params.subsets
        
        if subsets:
            srid = subsets.srid
            if srid is not None:
                if not crss.validateEPSGCode(srid):
                    raise RenderException(
                        "Failed to extract an EPSG code from the CRS URI "
                        "'%s'." % srid, "subset"
                    )

        
        # create and configure map object
        map_ = self.create_map()

        # configure outputformat
        native_format = self.get_native_format(coverage, data_items)
        if get_format_by_mime(native_format) is None:
            native_format = "image/tiff"

        frmt = params.format or native_format

        if frmt is None:
            raise RenderException("Format could not be determined", "format")

        mime_type, frmt = split_format(frmt)

        imagemode = ms.gdalconst_to_imagemode(bands[0].data_type)
        time_stamp = datetime.now().strftime("%Y%m%d%H%M%S")
        basename = "%s_%s" % (coverage.identifier, time_stamp)
        of = create_outputformat(
            mime_type, frmt, imagemode, basename, 
            getattr(params, "encoding_params", {})
        )

        map_.appendOutputFormat(of)
        map_.setOutputFormat(of)

        # TODO: use layer factory here
        layer = self.layer_for_coverage(coverage, native_format, params.version)
        
        map_.insertLayer(layer)

        for connector in self.connectors:
            if connector.supports(data_items):
                break
        else:
            raise OperationNotSupportedException(
                "Could not find applicable layer connector.", "coverage"
            )

        try:
            connector.connect(coverage, data_items, layer)
            # create request object and dispatch it against the map
            request = ms.create_request(
                self.translate_params(params, range_type)
            )
            request.setParameter("format", mime_type)
            raw_result = ms.dispatch(map_, request)

        finally:
            # perform any required layer related cleanup
            connector.disconnect(coverage, data_items, layer)

        result_set = result_set_from_raw_data(raw_result)

        if params.version == Version(2, 0):
            if getattr(params, "mediatype", None) in ("multipart/mixed", "multipart/related"):
                encoder = WCS20EOXMLEncoder()
                is_mosaic = issubclass(
                    coverage.real_type, models.RectifiedStitchedMosaic
                )

                if not is_mosaic:
                    tree = encoder.alter_rectified_dataset(
                        coverage, getattr(params, "http_request", None), 
                        etree.parse(result_set[0].data_file).getroot(), 
                        subsets.bounding_polygon(coverage) if subsets else None
                    )
                else:
                    tree = encoder.alter_rectified_stitched_mosaic(
                        coverage.cast(), getattr(params, "http_request", None), 
                        etree.parse(result_set[0].data_file).getroot(), 
                        subsets.bounding_polygon(coverage) if subsets else None
                    )

                result_set[0] = ResultBuffer(
                    encoder.serialize(tree), 
                    encoder.content_type
                )

        # "default" response
        return result_set