/** * Generated by API Builder - https://www.apibuilder.io * Service version: 0.0.1 * User agent: apibuilder app.apibuilder.io/nccloud/registry-api/0.0.1/http4s_0_22 */ package de.nccloud.registry.api.v0.models { sealed trait ServiceEvent extends _root_.scala.Product with _root_.scala.Serializable { def serviceEventType: ServiceEventType } /** * Defines the valid type values for the type ServiceEvent */ sealed trait ServiceEventType extends _root_.scala.Product with _root_.scala.Serializable object ServiceEventType { case object ServiceUpsertedEvent extends ServiceEventType { override def toString = "service_upserted_event" } case object ServiceDeletedEvent extends ServiceEventType { override def toString = "service_deleted_event" } final case class UNDEFINED(override val toString: String) extends ServiceEventType val all: scala.List[ServiceEventType] = scala.List(ServiceUpsertedEvent, ServiceDeletedEvent) private val byName: Map[String, ServiceEventType] = all.map(x => x.toString.toLowerCase -> x).toMap def apply(value: String): ServiceEventType = fromString(value).getOrElse(UNDEFINED(value)) def fromString(value: String): _root_.scala.Option[ServiceEventType] = byName.get(value.toLowerCase) } /** * A single available service. * * @param uri URI under which this service is deployed. * @param title A human-readable title of the service. * @param description A human-readable description of the service. */ final case class Service( name: String, version: String, state: de.nccloud.registry.api.v0.models.ServiceState, `type`: de.nccloud.registry.api.v0.models.ServiceType = de.nccloud.registry.api.v0.models.ServiceType.Public, uri: String, title: _root_.scala.Option[String] = None, description: _root_.scala.Option[String] = None ) /** * A service has been undeployed is not reachable anymore. * * @param name Name of the service that has been undeployed. */ final case class ServiceDeletedEvent( name: String, timestamp: _root_.java.time.Instant ) extends ServiceEvent { override val serviceEventType: ServiceEventType = ServiceEventType.ServiceDeletedEvent } /** * A service has been newly deployed or updated. */ final case class ServiceUpsertedEvent( service: de.nccloud.registry.api.v0.models.Service, timestamp: _root_.java.time.Instant ) extends ServiceEvent { override val serviceEventType: ServiceEventType = ServiceEventType.ServiceUpsertedEvent } /** * Provides future compatibility in clients - in the future, when a type is added * to the union ServiceEvent, it will need to be handled in the client code. This * implementation will deserialize these future types as an instance of this class. * * @param description Information about the type that we received that is undefined in this version of * the client. */ final case class ServiceEventUndefinedType( description: String ) extends ServiceEvent { override val serviceEventType: ServiceEventType = ServiceEventType.UNDEFINED(description) } /** * The current state of a single service. */ sealed trait ServiceState extends _root_.scala.Product with _root_.scala.Serializable object ServiceState { /** * This service is currently not deployed. */ case object Unavailable extends ServiceState { override def toString = "unavailable" } /** * This service is deployed and reachable. */ case object Available extends ServiceState { override def toString = "available" } /** * This service is deployed but not reachable due to an error. */ case object Error extends ServiceState { override def toString = "error" } /** * UNDEFINED captures values that are sent either in error or * that were added by the server after this library was * generated. We want to make it easy and obvious to users of * this library to handle this case gracefully. * * We use all CAPS for the variable name to avoid collisions * with the camel cased values above. */ final case class UNDEFINED(override val toString: String) extends ServiceState /** * all returns a list of all the valid, known values. We use * lower case to avoid collisions with the camel cased values * above. */ val all: scala.List[ServiceState] = scala.List(Unavailable, Available, Error) private val byName: Map[String, ServiceState] = all.map(x => x.toString.toLowerCase -> x).toMap def apply(value: String): ServiceState = fromString(value).getOrElse(UNDEFINED(value)) def fromString(value: String): _root_.scala.Option[ServiceState] = byName.get(value.toLowerCase) } /** * Indicates where a service is reachable. */ sealed trait ServiceType extends _root_.scala.Product with _root_.scala.Serializable object ServiceType { /** * This service is publicly reachable. */ case object Public extends ServiceType { override def toString = "public" } /** * This service only reachable internally in the cluster. */ case object Internal extends ServiceType { override def toString = "internal" } /** * UNDEFINED captures values that are sent either in error or * that were added by the server after this library was * generated. We want to make it easy and obvious to users of * this library to handle this case gracefully. * * We use all CAPS for the variable name to avoid collisions * with the camel cased values above. */ final case class UNDEFINED(override val toString: String) extends ServiceType /** * all returns a list of all the valid, known values. We use * lower case to avoid collisions with the camel cased values * above. */ val all: scala.List[ServiceType] = scala.List(Public, Internal) private val byName: Map[String, ServiceType] = all.map(x => x.toString.toLowerCase -> x).toMap def apply(value: String): ServiceType = fromString(value).getOrElse(UNDEFINED(value)) def fromString(value: String): _root_.scala.Option[ServiceType] = byName.get(value.toLowerCase) } } package de.nccloud.registry.api.v0.models { package object json { import io.circe.Decoder._ import io.circe.Encoder._ import scala.language.implicitConversions // See below - Make Scala 2.11 Either monadic import scala.util.Try import io.circe.{Json, JsonObject, Encoder, Decoder, DecodingFailure} import io.circe.syntax._ import de.nccloud.common.v0.models.json._ import de.nccloud.registry.api.v0.models.json._ // Make Scala 2.11 Either monadic private[v0] implicit def eitherOps[A,B](e: Either[A,B]) = cats.implicits.catsSyntaxEither(e) private[v0] implicit val decodeUUID: Decoder[_root_.java.util.UUID] = Decoder.decodeString.emapTry(str => Try(_root_.java.util.UUID.fromString(str))) private[v0] implicit val encodeUUID: Encoder[_root_.java.util.UUID] = Encoder.encodeString.contramap[_root_.java.util.UUID](uuid => uuid.toString) private[v0] implicit val decodeInstant: Decoder[_root_.java.time.Instant] = Decoder.decodeString.emapTry(str => Try(_root_.java.time.OffsetDateTime.parse(str).toInstant)) private[v0] implicit val encodeInstant: Encoder[_root_.java.time.Instant] = Encoder.encodeString.contramap[_root_.java.time.Instant](_.toString) private[v0] implicit val decodeLocalDate: Decoder[_root_.java.time.LocalDate] = Decoder.decodeString.emapTry(str => Try(_root_.java.time.LocalDate.parse(str))) private[v0] implicit val encodeLocalDate: Encoder[_root_.java.time.LocalDate] = Encoder.encodeString.contramap[_root_.java.time.LocalDate](_.toString) implicit val jsonDecoderRegistryApiServiceState: Decoder[de.nccloud.registry.api.v0.models.ServiceState] = Decoder.decodeString.map(de.nccloud.registry.api.v0.models.ServiceState(_)) implicit val jsonEncoderRegistryApiServiceState: Encoder[de.nccloud.registry.api.v0.models.ServiceState] = Encoder.encodeString.contramap[de.nccloud.registry.api.v0.models.ServiceState](_.toString) implicit val jsonDecoderRegistryApiServiceType: Decoder[de.nccloud.registry.api.v0.models.ServiceType] = Decoder.decodeString.map(de.nccloud.registry.api.v0.models.ServiceType(_)) implicit val jsonEncoderRegistryApiServiceType: Encoder[de.nccloud.registry.api.v0.models.ServiceType] = Encoder.encodeString.contramap[de.nccloud.registry.api.v0.models.ServiceType](_.toString) implicit def decodeRegistryApiService: Decoder[Service] = Decoder.instance { c => for { name <- c.downField("name").as[String] version <- c.downField("version").as[String] state <- c.downField("state").as[de.nccloud.registry.api.v0.models.ServiceState] __type__ <- c.downField("type").as[de.nccloud.registry.api.v0.models.ServiceType] uri <- c.downField("uri").as[String] title <- c.downField("title").as[Option[String]] description <- c.downField("description").as[Option[String]] } yield { Service( name = name, version = version, state = state, `type` = __type__, uri = uri, title = title, description = description ) } } implicit def encodeRegistryApiService: Encoder[Service] = Encoder.instance { t => Json.fromFields(Seq( Some("name" -> t.name.asJson), Some("version" -> t.version.asJson), Some("state" -> t.state.asJson), Some("type" -> t.`type`.asJson), Some("uri" -> t.uri.asJson), t.title.map(t => "title" -> t.asJson), t.description.map(t => "description" -> t.asJson) ).flatten) } implicit def decodeRegistryApiServiceDeletedEvent: Decoder[ServiceDeletedEvent] = Decoder.instance { c => for { name <- c.downField("name").as[String] timestamp <- c.downField("timestamp").as[_root_.java.time.Instant] } yield { ServiceDeletedEvent( name = name, timestamp = timestamp ) } } implicit def encodeRegistryApiServiceDeletedEvent: Encoder[ServiceDeletedEvent] = Encoder.instance { t => Json.fromFields(Seq( Some("name" -> t.name.asJson), Some("timestamp" -> t.timestamp.asJson) ).flatten) } implicit def decodeRegistryApiServiceUpsertedEvent: Decoder[ServiceUpsertedEvent] = Decoder.instance { c => for { service <- c.downField("service").as[de.nccloud.registry.api.v0.models.Service] timestamp <- c.downField("timestamp").as[_root_.java.time.Instant] } yield { ServiceUpsertedEvent( service = service, timestamp = timestamp ) } } implicit def encodeRegistryApiServiceUpsertedEvent: Encoder[ServiceUpsertedEvent] = Encoder.instance { t => Json.fromFields(Seq( Some("service" -> t.service.asJson), Some("timestamp" -> t.timestamp.asJson) ).flatten) } implicit def decodeRegistryApiServiceEvent: Decoder[ServiceEvent] = Decoder.instance { c => c.get[Option[String]]("type") match { case Right(Some(s)) if s == "service_upserted_event" => c.as[de.nccloud.registry.api.v0.models.ServiceUpsertedEvent] case Right(Some(s)) if s == "service_deleted_event" => c.as[de.nccloud.registry.api.v0.models.ServiceDeletedEvent] case Right(Some(s)) => Right(de.nccloud.registry.api.v0.models.ServiceEventUndefinedType(s)) case _ => Left(DecodingFailure("Union[ServiceEvent] requires a discriminator named 'type' - this field was not found in the Json", c.history)) } } implicit def encodeRegistryApiServiceEvent: Encoder[ServiceEvent] = Encoder.instance { case t: de.nccloud.registry.api.v0.models.ServiceUpsertedEvent => t.asJson.mapObject(obj => ("type", Json.fromString("service_upserted_event")) +: obj) case t: de.nccloud.registry.api.v0.models.ServiceDeletedEvent => t.asJson.mapObject(obj => ("type", Json.fromString("service_deleted_event")) +: obj) case other => sys.error(s"The type[${other.getClass.getName}] has no JSON encoder") } } } package de.nccloud.registry.api.v0 { import cats.effect._ import cats.implicits._ import io.circe.syntax._ object Constants { val Namespace = "de.nccloud.registry.api.v0" val UserAgent = "apibuilder app.apibuilder.io/nccloud/registry-api/0.0.1/http4s_0_22" val Version = "0.0.1" val VersionMajor = 0 } class Client[F[_]: Sync]( val baseUrl: org.http4s.Uri, auth: scala.Option[de.nccloud.registry.api.v0.Authorization] = None, defaultHeaders: Seq[(String, String)] = Nil, httpClient: org.http4s.client.Client[F] ) extends interfaces.Client[F] { import org.http4s.Response import de.nccloud.common.v0.models.json._ import de.nccloud.registry.api.v0.models.json._ def services: Services[F] = Services object Services extends Services[F] { override def get( offset: Int = 0, limit: Int = 25, sortBy: String = "name", direction: de.nccloud.common.v0.models.SortDirection = de.nccloud.common.v0.models.SortDirection.Asc, requestHeaders: Seq[(String, String)] = Nil ): F[Seq[de.nccloud.registry.api.v0.models.Service]] = { val urlPath = Seq() val queryParameters = Seq( Some("offset" -> offset.toString), Some("limit" -> limit.toString), Some("sort_by" -> sortBy), Some("direction" -> direction.toString) ).flatten _executeRequest[Unit, Seq[de.nccloud.registry.api.v0.models.Service]]("GET", path = urlPath, queryParameters = queryParameters, requestHeaders = requestHeaders) { case r if r.status.code == 200 => _root_.de.nccloud.registry.api.v0.Client.parseJson[F, Seq[de.nccloud.registry.api.v0.models.Service]]("Seq[de.nccloud.registry.api.v0.models.Service]", r) case r => Sync[F].raiseError(new de.nccloud.registry.api.v0.errors.FailedRequest(r.status.code, s"Unsupported response code[${r.status.code}]. Expected: 200")) } } override def getByName( name: String, requestHeaders: Seq[(String, String)] = Nil ): F[de.nccloud.registry.api.v0.models.Service] = { val urlPath = Seq(name) _executeRequest[Unit, de.nccloud.registry.api.v0.models.Service]("GET", path = urlPath, requestHeaders = requestHeaders) { case r if r.status.code == 200 => _root_.de.nccloud.registry.api.v0.Client.parseJson[F, de.nccloud.registry.api.v0.models.Service]("de.nccloud.registry.api.v0.models.Service", r) case r if r.status.code == 404 => Sync[F].raiseError(new de.nccloud.registry.api.v0.errors.UnitResponse(r.status.code)) case r => Sync[F].raiseError(new de.nccloud.registry.api.v0.errors.FailedRequest(r.status.code, s"Unsupported response code[${r.status.code}]. Expected: 200, 404")) } } override def getUriByName( name: String, requestHeaders: Seq[(String, String)] = Nil ): F[String] = { val urlPath = Seq(name, "uri") _executeRequest[Unit, String]("GET", path = urlPath, requestHeaders = requestHeaders) { case r if r.status.code == 200 => _root_.de.nccloud.registry.api.v0.Client.parseJson[F, String]("String", r) case r if r.status.code == 404 => Sync[F].raiseError(new de.nccloud.registry.api.v0.errors.UnitResponse(r.status.code)) case r => Sync[F].raiseError(new de.nccloud.registry.api.v0.errors.FailedRequest(r.status.code, s"Unsupported response code[${r.status.code}]. Expected: 200, 404")) } } } private lazy val defaultApiHeaders = Seq( ("User-Agent", Constants.UserAgent), ("X-Apidoc-Version", Constants.Version), ("X-Apidoc-Version-Major", Constants.VersionMajor.toString) ) def apiHeaders: Seq[(String, String)] = defaultApiHeaders def modifyRequest(request: org.http4s.Request[F]): org.http4s.Request[F] = request implicit def circeJsonEncoder[F[_]: Sync, A](implicit encoder: io.circe.Encoder[A]) = org.http4s.circe.jsonEncoderOf[F, A] def _executeRequest[T, U]( method: String, path: Seq[String], queryParameters: Seq[(String, String)] = Nil, requestHeaders: Seq[(String, String)] = Nil, body: Option[T] = None, formBody : Option[org.http4s.UrlForm] = None )(handler: org.http4s.Response[F] => F[U] )(implicit encoder: io.circe.Encoder[T]): F[U] = { import org.http4s.QueryParamEncoder._ val m = org.http4s.Method.fromString(method) match { case Right(m) => m case Left(e) => sys.error(e.toString) } val headers = org.http4s.Headers(( apiHeaders ++ defaultHeaders ++ requestHeaders ).groupBy(_._1).map { case (k, l) => org.http4s.Header.Raw(org.typelevel.ci.CIString(k), l.last._2) }.toList) val queryMap = queryParameters.groupBy(_._1).map { case (k, v) => k -> v.map(_._2) } val uri = path.foldLeft(baseUrl){ case (uri, segment) => uri / segment }.setQueryParams(queryMap) val request = org.http4s.Request[F](method = m, uri = uri, headers = headers) val reqAndMaybeAuth = auth.fold(request) { case Authorization.Basic(username, passwordOpt) => { val userpass = s"$username:${passwordOpt.getOrElse("")}" val token = java.util.Base64.getEncoder.encodeToString(userpass.getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)) request.putHeaders(org.http4s.Header.Raw(org.typelevel.ci.CIString("Authorization"), s"Basic $token")) } case a => sys.error("Invalid authorization scheme[" + a.getClass + "]") } val reqAndMaybeAuthAndBody = if (formBody.nonEmpty) formBody.fold(reqAndMaybeAuth)(reqAndMaybeAuth.withEntity) else body.fold(reqAndMaybeAuth)(reqAndMaybeAuth.withEntity) httpClient.fetch(modifyRequest(reqAndMaybeAuthAndBody))(handler) } } object Client { import cats.effect._ implicit def circeJsonDecoder[F[_]: Sync, A](implicit decoder: io.circe.Decoder[A]) = org.http4s.circe.jsonOf[F, A] def parseJson[F[_]: Sync, T]( className: String, r: org.http4s.Response[F] )(implicit decoder: io.circe.Decoder[T]): F[T] = r.attemptAs[T].value.flatMap { case Right(value) => Sync[F].pure(value) case Left(error) => Sync[F].raiseError(new de.nccloud.registry.api.v0.errors.FailedRequest(r.status.code, s"Invalid json for class[" + className + "]", None, error)) } } sealed trait Authorization extends _root_.scala.Product with _root_.scala.Serializable object Authorization { final case class Basic(username: String, password: Option[String] = None) extends Authorization } package interfaces { trait Client[F[_]] { def baseUrl: org.http4s.Uri def services: de.nccloud.registry.api.v0.Services[F] } } trait Services[F[_]] { /** * Get all services. */ def get( offset: Int = 0, limit: Int = 25, sortBy: String = "name", direction: de.nccloud.common.v0.models.SortDirection = de.nccloud.common.v0.models.SortDirection.Asc, requestHeaders: Seq[(String, String)] = Nil ): F[Seq[de.nccloud.registry.api.v0.models.Service]] def getByName( name: String, requestHeaders: Seq[(String, String)] = Nil ): F[de.nccloud.registry.api.v0.models.Service] /** * Get the URI of given service. */ def getUriByName( name: String, requestHeaders: Seq[(String, String)] = Nil ): F[String] } package errors { final case class UnitResponse(status: Int) extends Exception(s"HTTP $status") final case class FailedRequest(responseCode: Int, message: String, requestUri: Option[_root_.java.net.URI] = None, parent: Exception = null) extends _root_.java.lang.Exception(s"HTTP $responseCode: $message", parent) } }