Beispiel #1
0
    def add_child(
        self,
        child: Union["Catalog", "Collection_Type"],
        title: Optional[str] = None,
        strategy: Optional[HrefLayoutStrategy] = None,
    ) -> None:
        """Adds a link to a child :class:`~pystac.Catalog` or
        :class:`~pystac.Collection`. This method will set the child's parent to this
        object, and its root to this Catalog's root.

        Args:
            child : The child to add.
            title : Optional title to give to the :class:`~pystac.Link`
            strategy : The layout strategy to use for setting the
                self href of the child.
        """

        # Prevent typo confusion
        if isinstance(child, pystac.Item):
            raise pystac.STACError("Cannot add item as child. Use add_item instead.")

        if strategy is None:
            strategy = BestPracticesLayoutStrategy()

        child.set_root(self.get_root())
        child.set_parent(self)

        # set self link
        self_href = self.get_self_href()
        if self_href:
            child_href = strategy.get_href(child, os.path.dirname(self_href))
            child.set_self_href(child_href)

        self.add_link(Link.child(child, title=title))
Beispiel #2
0
    def add_item(
        self,
        item: "Item_Type",
        title: Optional[str] = None,
        strategy: Optional[HrefLayoutStrategy] = None,
    ) -> None:
        """Adds a link to an :class:`~pystac.Item`.
        This method will set the item's parent to this object, and its root to
        this Catalog's root.

        Args:
            item : The item to add.
            title : Optional title to give to the :class:`~pystac.Link`
        """

        # Prevent typo confusion
        if isinstance(item, pystac.Catalog):
            raise pystac.STACError("Cannot add catalog as item. Use add_child instead.")

        if strategy is None:
            strategy = BestPracticesLayoutStrategy()

        item.set_root(self.get_root())
        item.set_parent(self)

        # set self link
        self_href = self.get_self_href()
        if self_href:
            item_href = strategy.get_href(item, os.path.dirname(self_href))
            item.set_self_href(item_href)

        self.add_link(Link.item(item, title=title))
Beispiel #3
0
    def counts(self, v: Optional[List[LabelCount]]) -> None:
        if v is None:
            self.properties.pop("counts", None)
        else:
            if not isinstance(v, list):
                raise pystac.STACError(
                    "counts must be a list! Invalid input: {}".format(v))

            self.properties["counts"] = [c.to_dict() for c in v]
Beispiel #4
0
    def label_classes(self, v: Optional[List[LabelClasses]]) -> None:
        if v is None:
            self.obj.properties.pop(CLASSES_PROP, None)
        else:
            if not isinstance(v, list):
                raise pystac.STACError(
                    "label_classes must be a list! Invalid input: {}".format(
                        v))

            classes = [x.to_dict() for x in v]
            self.obj.properties[CLASSES_PROP] = classes
Beispiel #5
0
 def get_href(self, stac_object, parent_dir, is_root=False):
     stac_object_type = stac_object.STAC_OBJECT_TYPE
     if stac_object_type == pystac.STACObjectType.CATALOG:
         return self.get_catalog_href(stac_object, parent_dir, is_root)
     elif stac_object_type == pystac.STACObjectType.COLLECTION:
         return self.get_collection_href(stac_object, parent_dir, is_root)
     elif stac_object_type == pystac.STACObjectType.ITEM:
         return self.get_item_href(stac_object, parent_dir)
     else:
         raise pystac.STACError(
             'Unknown STAC object type {}'.format(stac_object_type))
Beispiel #6
0
 def get_href(self,
              stac_object: "STACObject_Type",
              parent_dir: str,
              is_root: bool = False) -> str:
     if isinstance(stac_object, pystac.Item):
         return self.get_item_href(stac_object, parent_dir)
     elif isinstance(stac_object, pystac.Collection):
         return self.get_collection_href(stac_object, parent_dir, is_root)
     elif isinstance(stac_object, pystac.Catalog):
         return self.get_catalog_href(stac_object, parent_dir, is_root)
     else:
         raise pystac.STACError(
             "Unknown STAC object type {}".format(stac_object))
Beispiel #7
0
 def _set_field(self, prop_name: str, v: Optional[Any]) -> None:
     if hasattr(self.object, prop_name):
         setattr(self.object, prop_name, v)
     elif hasattr(self.object, "properties"):
         item = cast("Item_Type", self.object)
         if v is None:
             item.properties.pop(prop_name, None)
         else:
             item.properties[prop_name] = v
     elif hasattr(self.object, "extra_fields") and isinstance(
             self.object.extra_fields, Dict):
         if v is None:
             self.object.extra_fields.pop(prop_name, None)
         else:
             self.object.extra_fields[prop_name] = v
     else:
         raise pystac.STACError(f"Cannot set field {prop_name} on {self}.")
Beispiel #8
0
    def apply(self, published=None, expires=None, unpublished=None):
        """Applies timestamps extension properties to the extended Item.

        Args:
            published (datetime or None): Date and time the corresponding data
                was published the first time.
            expires (datetime or None): Date and time the corresponding data
                expires (is not valid any longer).
            unpublished (datetime or None): Date and time the corresponding data
                was unpublished.
        """
        if published is None and expires is None and unpublished is None:
            raise pystac.STACError(
                "timestamps extension needs at least one property value.")

        self.published = published
        self.expires = expires
        self.unpublished = unpublished
Beispiel #9
0
    def validate_owner_has_extension(cls, asset: pystac.Asset,
                                     add_if_missing: bool) -> None:
        """Given an :class:`~pystac.Asset`, checks if the asset's owner has this
        extension's schema URI in its :attr:`~pystac.STACObject.stac_extensions` list.
        If ``add_if_missing`` is ``True``, the schema URI will be added to the owner.

        Raises:
            STACError : If ``add_if_missing`` is ``True`` and ``asset.owner`` is
                ``None``.
        """
        if asset.owner is None:
            if add_if_missing:
                raise pystac.STACError(
                    "Attempted to use add_if_missing=True for an Asset with no owner. "
                    "Use Asset.set_owner or set add_if_missing=False.")
            else:
                return
        return cls.validate_has_extension(cast(S, asset.owner), add_if_missing)
Beispiel #10
0
    def resolve_stac_object(self,
                            root: Optional["Catalog_Type"] = None) -> "Link":
        """Resolves a STAC object from the HREF of this link, if the link is not
        already resolved.

        Args:
            root : Optional root of the catalog for this link.
                If provided, the root's resolved object cache is used to search for
                previously resolved instances of the STAC object.
        """
        if self._target_object:
            pass
        elif self._target_href:
            target_href = self._target_href

            # If it's a relative link, base it off the parent.
            if not is_absolute_href(target_href):
                if self.owner is None:
                    raise pystac.STACError(
                        "Relative path {} encountered "
                        "without owner or start_href.".format(target_href))
                start_href = self.owner.get_self_href()

                if start_href is None:
                    raise pystac.STACError(
                        "Relative path {} encountered "
                        'without owner "self" link set.'.format(target_href))

                target_href = make_absolute_href(target_href, start_href)
            obj = None

            stac_io: Optional[pystac.StacIO] = None

            if root is not None:
                obj = root._resolved_objects.get_by_href(target_href)
                stac_io = root._stac_io

            if obj is None:

                if stac_io is None:
                    if self.owner is not None:
                        if isinstance(self.owner, pystac.Catalog):
                            stac_io = self.owner._stac_io
                        elif self.rel != pystac.RelType.ROOT:
                            owner_root = self.owner.get_root()
                            if owner_root is not None:
                                stac_io = owner_root._stac_io
                    if stac_io is None:
                        stac_io = pystac.StacIO.default()

                obj = stac_io.read_stac_object(target_href, root=root)
                obj.set_self_href(target_href)
                if root is not None:
                    obj = root._resolved_objects.get_or_cache(obj)
                    obj.set_root(root)
            self._target_object = obj
        else:
            raise ValueError("Cannot resolve STAC object without a target")

        if (self.owner
                and self.rel in [pystac.RelType.CHILD, pystac.RelType.ITEM]
                and isinstance(self.owner, pystac.Catalog)):
            assert self._target_object
            self._target_object.set_parent(self.owner)

        return self
Beispiel #11
0
    def size(self, v: int) -> None:
        if not isinstance(v, int):
            raise pystac.STACError(
                "size must be an int! Invalid input: {}".format(v))

        self.properties["size"] = v
Beispiel #12
0
 def polarizations(self, values: List[Polarization]) -> None:
     if not isinstance(values, list):
         raise pystac.STACError(
             f'polarizations must be a list. Invalid "{values}"')
     self.item.properties[POLARIZATIONS] = [v.value for v in values]
Beispiel #13
0
 def polarizations(self, values: List[Polarization]) -> None:
     if not isinstance(values, list):
         raise pystac.STACError(
             f'polarizations must be a list. Invalid "{values}"')
     self._set_property(POLARIZATIONS_PROP, [v.value for v in values],
                        pop_if_none=False)