|
| 1 | +/* |
| 2 | +Copyright (c) 2017, Qvantel |
| 3 | +All rights reserved. |
| 4 | +
|
| 5 | +Redistribution and use in source and binary forms, with or without |
| 6 | +modification, are permitted provided that the following conditions are met: |
| 7 | + * Redistributions of source code must retain the above copyright |
| 8 | + notice, this list of conditions and the following disclaimer. |
| 9 | + * Redistributions in binary form must reproduce the above copyright |
| 10 | + notice, this list of conditions and the following disclaimer in the |
| 11 | + documentation and/or other materials provided with the distribution. |
| 12 | + * Neither the name of the Qvantel nor the |
| 13 | + names of its contributors may be used to endorse or promote products |
| 14 | + derived from this software without specific prior written permission. |
| 15 | +
|
| 16 | +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
| 17 | +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
| 18 | +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 19 | +DISCLAIMED. IN NO EVENT SHALL Qvantel BE LIABLE FOR ANY |
| 20 | +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
| 21 | +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
| 22 | +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
| 23 | +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 24 | +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
| 25 | +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 26 | + */ |
| 27 | +package com.qvantel.jsonapi.akka |
| 28 | + |
| 29 | +import _root_.akka.http.scaladsl.Http |
| 30 | +import _root_.akka.http.scaladsl.client.RequestBuilding |
| 31 | +import _root_.akka.http.scaladsl.marshalling._ |
| 32 | +import _root_.akka.http.scaladsl.model._ |
| 33 | +import _root_.akka.http.scaladsl.model.headers._ |
| 34 | +import _root_.akka.http.scaladsl.unmarshalling._ |
| 35 | +import _root_.akka.stream.Materializer |
| 36 | +import _root_.akka.stream.scaladsl._ |
| 37 | +import _root_.akka.util.{ByteString, Timeout} |
| 38 | +import _root_.spray.json._ |
| 39 | + |
| 40 | +import scala.concurrent.{ExecutionContext, Future} |
| 41 | +import scala.concurrent.duration._ |
| 42 | + |
| 43 | +import com.qvantel.jsonapi._ |
| 44 | +import com.qvantel.jsonapi.model.TopLevel |
| 45 | + |
| 46 | +trait JsonApiSupport extends JsonApiSupport0 { |
| 47 | + |
| 48 | + implicit def jsonApiCollectionMarshaller[T]( |
| 49 | + implicit writer: JsonApiWriter[T], |
| 50 | + printer: JsonPrinter = PrettyPrinter, |
| 51 | + metaProfiles: Set[MetaProfile] = Set.empty, |
| 52 | + sorting: JsonApiSorting = JsonApiSorting.Unsorted, |
| 53 | + sparseFields: Map[String, List[String]] = Map.empty, |
| 54 | + pagination: JsonApiPagination.PaginationFunc = JsonApiPagination.EmptyFunc): ToEntityMarshaller[Iterable[T]] = |
| 55 | + Marshaller.withFixedContentType(ct) { as => |
| 56 | + HttpEntity(ct, rawCollection(as)) |
| 57 | + } |
| 58 | + |
| 59 | + implicit def jsonApiCollectionRequestUnmarshaller[T]( |
| 60 | + implicit reader: JsonApiReader[T]): FromRequestUnmarshaller[Iterable[T]] = |
| 61 | + new FromRequestUnmarshaller[Iterable[T]] { |
| 62 | + override def apply(value: HttpRequest)(implicit ec: ExecutionContext, |
| 63 | + materializer: Materializer): Future[Iterable[T]] = { |
| 64 | + val include = value.uri.query().get("include").map(_.split(',').toSet).getOrElse(Set.empty[String]) |
| 65 | + value.entity.toStrict(10.seconds).flatMap(strictEntity => extractEntities(strictEntity.data, include)) |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + implicit def jsonApiCollectionResponseUnmarshaller[T]( |
| 70 | + implicit reader: JsonApiReader[T]): FromResponseUnmarshaller[Iterable[T]] = |
| 71 | + new FromResponseUnmarshaller[Iterable[T]] { |
| 72 | + override def apply(value: HttpResponse)(implicit ec: ExecutionContext, |
| 73 | + materializer: Materializer): Future[Iterable[T]] = { |
| 74 | + val include = value.headers |
| 75 | + .find(_.name == JsonApiSupport.JsonApiIncludeHeader) |
| 76 | + .map(_.value.split(',').toSet) |
| 77 | + .getOrElse(Set.empty[String]) |
| 78 | + value.entity.toStrict(10.seconds).flatMap(strictEntity => extractEntities(strictEntity.data, include)) |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | +} |
| 83 | + |
| 84 | +trait JsonApiSupport0 { |
| 85 | + val ct = MediaTypes.`application/vnd.api+json` |
| 86 | + |
| 87 | + implicit val jsonApiTopLevelSingle: Unmarshaller[HttpEntity, TopLevel.Single] = { |
| 88 | + Unmarshaller.byteStringUnmarshaller.map { data => |
| 89 | + JsonParser(data.utf8String).asJsObject.convertTo[TopLevel.Single] |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + implicit val jsonApiTopLevelCollection: Unmarshaller[HttpEntity, TopLevel.Collection] = { |
| 94 | + Unmarshaller.byteStringUnmarshaller.map { data => |
| 95 | + JsonParser(data.utf8String).asJsObject.convertTo[TopLevel.Collection] |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + implicit val jsonApiErrorObject: Unmarshaller[HttpEntity, TopLevel.Errors] = { |
| 100 | + Unmarshaller.byteStringUnmarshaller.map { data => |
| 101 | + JsonParser(data.utf8String).asJsObject.convertTo[TopLevel.Errors] |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + implicit def jsonApiOneMarshaller[T](implicit writer: JsonApiWriter[T], |
| 106 | + printer: JsonPrinter = PrettyPrinter, |
| 107 | + metaProfiles: Set[MetaProfile] = Set.empty, |
| 108 | + sorting: JsonApiSorting = JsonApiSorting.Unsorted, |
| 109 | + sparseFields: Map[String, List[String]] = Map.empty): ToEntityMarshaller[T] = |
| 110 | + Marshaller.withFixedContentType(ct) { a => |
| 111 | + HttpEntity(ct, rawOne(a)) |
| 112 | + } |
| 113 | + |
| 114 | + implicit def relatedResponseMarshaller[A]( |
| 115 | + implicit writer: JsonApiWriter[A], |
| 116 | + printer: JsonPrinter = PrettyPrinter, |
| 117 | + sorting: JsonApiSorting = JsonApiSorting.Unsorted, |
| 118 | + sparseFields: Map[String, List[String]] = Map.empty): ToEntityMarshaller[com.qvantel.jsonapi.RelatedResponse[A]] = |
| 119 | + PredefinedToEntityMarshallers.StringMarshaller.wrap(ct) { value => |
| 120 | + printer.apply(value.toResponse) |
| 121 | + } |
| 122 | + |
| 123 | + implicit def jsonApiOneRequestUnmarshaller[T](implicit reader: JsonApiReader[T]): FromRequestUnmarshaller[T] = |
| 124 | + new FromRequestUnmarshaller[T] { |
| 125 | + override def apply(value: HttpRequest)(implicit ec: ExecutionContext, materializer: Materializer): Future[T] = { |
| 126 | + val include = value.uri.query().get("include").map(_.split(',').toSet).getOrElse(Set.empty[String]) |
| 127 | + value.entity.toStrict(10.seconds).flatMap(strictEntity => extractEntity(strictEntity.data, include)) |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + implicit def jsonApiOneResponseUnmarshaller[T](implicit reader: JsonApiReader[T]): FromResponseUnmarshaller[T] = |
| 132 | + new FromResponseUnmarshaller[T] { |
| 133 | + override def apply(value: HttpResponse)(implicit ec: ExecutionContext, materializer: Materializer): Future[T] = { |
| 134 | + val include = value.headers |
| 135 | + .find(_.name == JsonApiSupport.JsonApiIncludeHeader) |
| 136 | + .map(_.value.split(',').toSet) |
| 137 | + .getOrElse(Set.empty[String]) |
| 138 | + value.entity.toStrict(10.seconds).flatMap(strictEntity => extractEntity(strictEntity.data, include)) |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + def extractEntity[T](data: ByteString, include: Set[String])(implicit reader: JsonApiReader[T], |
| 143 | + ec: ExecutionContext): Future[T] = |
| 144 | + Future { |
| 145 | + val json = JsonParser(data.decodeString("UTF-8")).asJsObject |
| 146 | + readOne[T](json, include) |
| 147 | + } |
| 148 | + |
| 149 | + def extractEntity[T](data: Source[ByteString, Any], include: Set[String])(implicit materializer: Materializer, |
| 150 | + reader: JsonApiReader[T], |
| 151 | + ec: ExecutionContext): Future[T] = |
| 152 | + data.runFold(ByteString(""))(_ ++ _).flatMap(extractEntity[T](_, include)) |
| 153 | + |
| 154 | + def extractEntities[T](data: ByteString, include: Set[String])(implicit reader: JsonApiReader[T], |
| 155 | + ec: ExecutionContext): Future[Iterable[T]] = |
| 156 | + Future { |
| 157 | + val json = JsonParser(data.decodeString("UTF-8")).asJsObject |
| 158 | + readCollection[T](json, include).toList |
| 159 | + } |
| 160 | + |
| 161 | + def extractEntities[T](data: Source[ByteString, Any], include: Set[String])( |
| 162 | + implicit materializer: Materializer, |
| 163 | + reader: JsonApiReader[T], |
| 164 | + ec: ExecutionContext): Future[Iterable[T]] = |
| 165 | + data.runFold(ByteString(""))(_ ++ _).flatMap(extractEntities[T](_, include)) |
| 166 | +} |
| 167 | + |
| 168 | +/** Custom SendReceive that adds the include params into X-Internal-Include |
| 169 | + * header that can be read by FromResponseUnmarshaller |
| 170 | + */ |
| 171 | +object JsonApiClientAkka extends RequestBuilding { |
| 172 | + import _root_.akka.actor._ |
| 173 | + import _root_.akka.http.scaladsl.settings.{ClientConnectionSettings, ConnectionPoolSettings} |
| 174 | + |
| 175 | + import scala.concurrent.duration._ |
| 176 | + |
| 177 | + def jsonApiSendReceive(implicit refFactory: ActorRefFactory, |
| 178 | + executionContext: ExecutionContext, |
| 179 | + system: ActorSystem, |
| 180 | + futureTimeout: Timeout = 60.seconds): HttpRequest => Future[HttpResponse] = { |
| 181 | + |
| 182 | + val conSettings = ClientConnectionSettings(system.settings.config).withIdleTimeout(futureTimeout.duration) |
| 183 | + val timeoutSettings = ConnectionPoolSettings(system.settings.config).withConnectionSettings(conSettings) |
| 184 | + req => |
| 185 | + val response = Http().singleRequest(request = req, settings = timeoutSettings) |
| 186 | + req.uri.query().get("include") match { |
| 187 | + case Some(include) => response.map(_.withHeaders(RawHeader(JsonApiSupport.JsonApiIncludeHeader, include))) |
| 188 | + case None => response |
| 189 | + } |
| 190 | + } |
| 191 | +} |
| 192 | + |
| 193 | +object JsonApiSupport extends JsonApiSupport { |
| 194 | + val JsonApiIncludeHeader: String = "X-Internal-Include" |
| 195 | +} |
0 commit comments