repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
atomicbits/scramlgen
modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/TypesParseTest.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser import io.atomicbits.scraml.ramlparser.lookup.{ CanonicalNameGenerator, CanonicalTypeCollector } import io.atomicbits.scraml.ramlparser.model.parsedtypes.{ ParsedObject, ParsedString, ParsedTypeReference } import io.atomicbits.scraml.ramlparser.model.{ NativeId, Raml } import io.atomicbits.scraml.ramlparser.parser.RamlParser import io.atomicbits.util.TestUtils import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import org.scalatest.featurespec.AnyFeatureSpec import org.scalatest.matchers.should.Matchers._ import scala.util.Try /** * Created by peter on 25/11/16. */ class TypesParseTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll { Scenario("test parsing types in a RAML 1.0 model") { Given("a RAML 1.0 specification with some types defined") val defaultBasePath = List("io", "atomicbits", "types") val parser = RamlParser("/types/TypesTestApi.raml", "UTF-8") When("we parse the specification") val parsedModel: Try[Raml] = parser.parse Then("we get all four actions in the userid resource") val raml = parsedModel.get val bookType = raml.types(NativeId("Book")).asInstanceOf[ParsedObject] val authorType = raml.types(NativeId("Author")).asInstanceOf[ParsedObject] val comicBookType = raml.types(NativeId("ComicBook")).asInstanceOf[ParsedObject] bookType.properties("title").propertyType.parsed match { case stringType: ParsedString => stringType.required shouldBe Some(true) case _ => fail(s"The title property of a book should be a StringType.") } bookType.properties("author").propertyType.parsed match { case typeReference: ParsedTypeReference => typeReference.refersTo.asInstanceOf[NativeId] shouldBe NativeId("Author") case _ => fail(s"The author property of a book should be a ReferenceType.") } comicBookType.parents shouldBe Set(ParsedTypeReference(NativeId("Book"))) comicBookType.properties("hero").propertyType.parsed match { case stringType: ParsedString => stringType.required shouldBe None case _ => fail(s"The hero property of a comicbook should be a StringType.") } val prettyModel = TestUtils.prettyPrint(parsedModel) val canonicalTypeCollector = CanonicalTypeCollector(CanonicalNameGenerator(defaultBasePath)) val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml) // ToDo: parse the RAML 1.0 type discriminator and type discriminator value // println(s"Parsed raml: $prettyModel") } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedEnum.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.parsedtypes import io.atomicbits.scraml.ramlparser.model._ import play.api.libs.json.{ JsArray, JsObject, JsString, JsValue } import scala.util.{ Success, Try } /** * Created by peter on 1/04/16. */ case class ParsedEnum(id: Id, choices: List[String], required: Option[Boolean] = None, model: TypeModel = RamlModel) extends NonPrimitiveType with AllowedAsObjectField { override def updated(updatedId: Id): ParsedEnum = copy(id = updatedId) override def asTypeModel(typeModel: TypeModel): ParsedType = copy(model = typeModel) } object ParsedEnum { val value = "enum" def apply(json: JsValue): Try[ParsedEnum] = { val model: TypeModel = TypeModel(json) val id = JsonSchemaIdExtractor(json) val choices = (json \ "enum").asOpt[List[String]] val required = (json \ "required").asOpt[Boolean] Success(ParsedEnum(id, choices.getOrElse(List.empty), required, model)) } def unapply(json: JsValue): Option[Try[ParsedEnum]] = { (ParsedType.typeDeclaration(json), (json \ ParsedEnum.value).toOption) match { case (Some(JsString(ParsedString.value)), Some(JsArray(x))) => Some(ParsedEnum(json)) case (None, Some(JsArray(x))) => Some(ParsedEnum(json)) case _ => None } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/transformers/ParsedDateTransformer.scala
<reponame>atomicbits/scramlgen /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.lookup.transformers import io.atomicbits.scraml.ramlparser.lookup.{ CanonicalLookupHelper, CanonicalNameGenerator } import io.atomicbits.scraml.ramlparser.model.canonicaltypes._ import io.atomicbits.scraml.ramlparser.model.parsedtypes._ /** * Created by peter on 7/10/17. */ object ParsedDateTransformer { // format: off def unapply(parsedTypeContext: ParsedTypeContext) (implicit canonicalNameGenerator: CanonicalNameGenerator): Option[(TypeReference, CanonicalLookupHelper)] = { // format: on val parsed: ParsedType = parsedTypeContext.parsedType val canonicalLookupHelper: CanonicalLookupHelper = parsedTypeContext.canonicalLookupHelper val canonicalNameOpt: Option[CanonicalName] = parsedTypeContext.canonicalNameOpt val parentNameOpt: Option[CanonicalName] = parsedTypeContext.parentNameOpt // This is the optional json-schema parent parsed match { case parsedBoolean: ParsedDateOnly => Some((DateOnlyType, canonicalLookupHelper)) case parsedBoolean: ParsedTimeOnly => Some((TimeOnlyType, canonicalLookupHelper)) case parsedBoolean: ParsedDateTimeOnly => Some((DateTimeOnlyType, canonicalLookupHelper)) case parsedBoolean: ParsedDateTimeDefault => Some((DateTimeDefaultType, canonicalLookupHelper)) case parsedBoolean: ParsedDateTimeRFC2616 => Some((DateTimeRFC2616Type, canonicalLookupHelper)) case _ => None } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/util/TryUtils.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.util import io.atomicbits.scraml.ramlparser.parser.RamlParseException import scala.util.control.NonFatal import scala.util.{ Failure, Success, Try } /** * Created by peter on 20/03/16. */ object TryUtils { def accumulate[T](tries: Seq[Try[T]]): Try[Seq[T]] = { val (successes, errors) = tries.partition(_.isSuccess) if (errors.isEmpty) { Success(successes.map(_.get)) } else { val errorsTyped = errors.collect { case Failure(exc) => exc } Failure(errorsTyped.reduce(addExceptions)) } } def accumulate[U, T](tryMap: Map[U, Try[T]]): Try[Map[U, T]] = { val (keys, values) = tryMap.toSeq.unzip accumulate(values) map { successfulValues => keys.zip(successfulValues).toMap } } def accumulate[T](tryOption: Option[Try[T]]): Try[Option[T]] = { tryOption match { case Some(Failure(ex)) => Failure[Option[T]](ex) case Some(Success(t)) => Success(Option(t)) case None => Success(None) } } def addExceptions(exc1: Throwable, exc2: Throwable): Throwable = { (exc1, exc2) match { case (e1: RamlParseException, e2: RamlParseException) => e1 ++ e2 case (e1, e2: RamlParseException) => e1 case (e1: RamlParseException, e2) => e2 case (e1, NonFatal(e2)) => e1 case (NonFatal(e1), e2) => e2 case (e1, e2) => e1 } } /** * withSuccess collects all failure cases in an applicative way according to the 'addExceptions' specs. */ def withSuccess[A, RES](a: Try[A])(fn: A => RES): Try[RES] = { a.map(fn) } def withSuccess[A, B, RES](a: Try[A], b: Try[B])(fn: (A, B) => RES): Try[RES] = withSuccessCurried(a, b)(fn.curried) private def withSuccessCurried[A, B, RES](a: Try[A], b: Try[B])(fn: A => B => RES): Try[RES] = { val tried: Try[(B => RES)] = withSuccess(a)(fn) processDelta(b, tried) } def withSuccess[A, B, C, RES](a: Try[A], b: Try[B], c: Try[C])(fn: (A, B, C) => RES): Try[RES] = withSuccessCurried(a, b, c)(fn.curried) private def withSuccessCurried[A, B, C, RES](a: Try[A], b: Try[B], c: Try[C])(fn: A => B => C => RES): Try[RES] = { val tried: Try[(C => RES)] = withSuccessCurried(a, b)(fn) processDelta(c, tried) } def withSuccess[A, B, C, D, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D])(fn: (A, B, C, D) => RES): Try[RES] = withSuccessCurried(a, b, c, d)(fn.curried) private def withSuccessCurried[A, B, C, D, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D])(fn: A => B => C => D => RES): Try[RES] = { val tried: Try[(D => RES)] = withSuccessCurried(a, b, c)(fn) processDelta(d, tried) } def withSuccess[A, B, C, D, E, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E])(fn: (A, B, C, D, E) => RES): Try[RES] = withSuccessCurried(a, b, c, d, e)(fn.curried) private def withSuccessCurried[A, B, C, D, E, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E])( fn: A => B => C => D => E => RES): Try[RES] = { val tried: Try[(E => RES)] = withSuccessCurried(a, b, c, d)(fn) processDelta(e, tried) } def withSuccess[A, B, C, D, E, F, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F])( fn: (A, B, C, D, E, F) => RES): Try[RES] = withSuccessCurried(a, b, c, d, e, f)(fn.curried) private def withSuccessCurried[A, B, C, D, E, F, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F])( fn: A => B => C => D => E => F => RES): Try[RES] = { val tried: Try[(F => RES)] = withSuccessCurried(a, b, c, d, e)(fn) processDelta(f, tried) } def withSuccess[A, B, C, D, E, F, G, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G])( fn: (A, B, C, D, E, F, G) => RES): Try[RES] = withSuccessCurried(a, b, c, d, e, f, g)(fn.curried) private def withSuccessCurried[A, B, C, D, E, F, G, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G])( fn: A => B => C => D => E => F => G => RES): Try[RES] = { val tried: Try[(G => RES)] = withSuccessCurried(a, b, c, d, e, f)(fn) processDelta(g, tried) } def withSuccess[A, B, C, D, E, F, G, H, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H])( fn: (A, B, C, D, E, F, G, H) => RES): Try[RES] = withSuccessCurried(a, b, c, d, e, f, g, h)(fn.curried) private def withSuccessCurried[A, B, C, D, E, F, G, H, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H])(fn: A => B => C => D => E => F => G => H => RES): Try[RES] = { val tried: Try[(H => RES)] = withSuccessCurried(a, b, c, d, e, f, g)(fn) processDelta(h, tried) } def withSuccess[A, B, C, D, E, F, G, H, I, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I])(fn: (A, B, C, D, E, F, G, H, I) => RES): Try[RES] = withSuccessCurried(a, b, c, d, e, f, g, h, i)(fn.curried) private def withSuccessCurried[A, B, C, D, E, F, G, H, I, RES]( a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I])(fn: A => B => C => D => E => F => G => H => I => RES): Try[RES] = { val tried: Try[(I => RES)] = withSuccessCurried(a, b, c, d, e, f, g, h)(fn) processDelta(i, tried) } def withSuccess[A, B, C, D, E, F, G, H, I, J, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I], j: Try[J])(fn: (A, B, C, D, E, F, G, H, I, J) => RES): Try[RES] = withSuccessCurried(a, b, c, d, e, f, g, h, i, j)(fn.curried) private def withSuccessCurried[A, B, C, D, E, F, G, H, I, J, RES]( a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I], j: Try[J])(fn: A => B => C => D => E => F => G => H => I => J => RES): Try[RES] = { val tried: Try[(J => RES)] = withSuccessCurried(a, b, c, d, e, f, g, h, i)(fn) processDelta(j, tried) } def withSuccess[A, B, C, D, E, F, G, H, I, J, K, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I], j: Try[J], k: Try[K])(fn: (A, B, C, D, E, F, G, H, I, J, K) => RES): Try[RES] = withSuccessCurried(a, b, c, d, e, f, g, h, i, j, k)(fn.curried) private def withSuccessCurried[A, B, C, D, E, F, G, H, I, J, K, RES]( a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I], j: Try[J], k: Try[K])(fn: A => B => C => D => E => F => G => H => I => J => K => RES): Try[RES] = { val tried: Try[(K => RES)] = withSuccessCurried(a, b, c, d, e, f, g, h, i, j)(fn) processDelta(k, tried) } def withSuccess[A, B, C, D, E, F, G, H, I, J, K, L, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I], j: Try[J], k: Try[K], l: Try[L])(fn: (A, B, C, D, E, F, G, H, I, J, K, L) => RES): Try[RES] = withSuccessCurried(a, b, c, d, e, f, g, h, i, j, k, l)(fn.curried) private def withSuccessCurried[A, B, C, D, E, F, G, H, I, J, K, L, RES]( a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I], j: Try[J], k: Try[K], l: Try[L])(fn: A => B => C => D => E => F => G => H => I => J => K => L => RES): Try[RES] = { val tried: Try[(L => RES)] = withSuccessCurried(a, b, c, d, e, f, g, h, i, j, k)(fn) processDelta(l, tried) } def withSuccess[A, B, C, D, E, F, G, H, I, J, K, L, M, RES](a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I], j: Try[J], k: Try[K], l: Try[L], m: Try[M])(fn: (A, B, C, D, E, F, G, H, I, J, K, L, M) => RES): Try[RES] = withSuccessCurried(a, b, c, d, e, f, g, h, i, j, k, l, m)(fn.curried) private def withSuccessCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, RES]( a: Try[A], b: Try[B], c: Try[C], d: Try[D], e: Try[E], f: Try[F], g: Try[G], h: Try[H], i: Try[I], j: Try[J], k: Try[K], l: Try[L], m: Try[M])(fn: A => B => C => D => E => F => G => H => I => J => K => L => M => RES): Try[RES] = { val tried: Try[(M => RES)] = withSuccessCurried(a, b, c, d, e, f, g, h, i, j, k, l)(fn) processDelta(m, tried) } private def processDelta[X, RES](delta: Try[X], fn: Try[(X => RES)]): Try[RES] = { delta match { case Success(value) => fn match { case Success(func) => Success(func(value)) case Failure(failures) => Failure(failures) } case Failure(exc) => fn match { case Success(func) => Failure(exc) case Failure(failures) => Failure(addExceptions(failures, exc)) } } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedTypeReference.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.parsedtypes import com.fasterxml.jackson.core.JsonParseException import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.parser.{ ParseContext, RamlParseException } import io.atomicbits.scraml.util.TryUtils import play.api.libs.json.{ JsArray, JsObject, JsString, JsValue } import scala.util.{ Failure, Success, Try } /** * Created by peter on 1/04/16. */ case class ParsedTypeReference(refersTo: Id, id: Id = ImplicitId, required: Option[Boolean] = None, genericTypes: List[ParsedType] = List.empty, fragments: Fragments = Fragments(), model: TypeModel = RamlModel) extends NonPrimitiveType with AllowedAsObjectField with Fragmented { override def updated(updatedId: Id): ParsedTypeReference = copy(id = updatedId) override def asTypeModel(typeModel: TypeModel): ParsedTypeReference = copy(model = typeModel) } object ParsedTypeReference { val value = "$ref" def apply(json: JsValue)(implicit parseContext: ParseContext): Try[ParsedTypeReference] = { val model: TypeModel = TypeModel(json) val id = JsonSchemaIdExtractor(json) val ref = json match { case RefExtractor(refId) => refId } val required = (json \ "required").asOpt[Boolean] val genericTypes = getGenericTypes(json) val fragments = json match { case Fragments(fragment) => fragment } TryUtils.withSuccess( Success(ref), Success(id), Success(required), genericTypes, fragments, Success(model) )(new ParsedTypeReference(_, _, _, _, _, _)) } def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[ParsedTypeReference]] = { def simpleStringTypeReference(theOtherType: String): Option[Try[ParsedTypeReference]] = { val triedOption: Try[Option[ParsedTypeReference]] = ParsedType(theOtherType).map { case typeRef: ParsedTypeReference => Some(typeRef) case _ => None } triedOption match { case Success(Some(typeRef)) => Some(Success(typeRef)) case Success(None) => None case Failure(x) => Some(Failure[ParsedTypeReference](x)) } } (ParsedType.typeDeclaration(json), (json \ ParsedTypeReference.value).toOption, json) match { case (None, Some(_), _) => Some(ParsedTypeReference(json)) case (Some(JsString(otherType)), None, _) => simpleStringTypeReference(otherType).map { triedParsedTypeRef => for { parsedTypeRef <- triedParsedTypeRef genericTypes <- getGenericTypes(json) req = (json \ "required").asOpt[Boolean] } yield parsedTypeRef.copy(genericTypes = genericTypes, required = req) } case (_, _, JsString(otherType)) => simpleStringTypeReference(otherType) case _ => None } } private def getGenericTypes(json: JsValue)(implicit parseContext: ParseContext): Try[List[ParsedType]] = { (json \ "genericTypes").toOption.collect { case genericTs: JsArray => val genericTsList = genericTs.value collect { case ParsedType(t) => t } TryUtils.accumulate(genericTsList.toList).map(_.toList) case genericTs: JsObject => val message = s""" |- | |The following generic type reference refers to its type parameter values |using an object map. This is the old way and it is not supported any longer. |Replace it with a JSON array. The order of the elements in the array must |correspond to the order of the type parameters in the referred type. | |The conflicting genericTypes construct is: | |$genericTs | |in | |${parseContext.sourceTrail.mkString(" <- ")} | |- """.stripMargin Failure(RamlParseException(message)) } getOrElse Try(List.empty[ParsedType]) } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/SourceReader.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.parser import java.io._ import java.net.{ URI, URL } import java.nio.file.{ FileSystems, Files, Path, Paths, FileSystem } import java.nio.file.{ FileSystem => _, _ } import java.util.Collections import scala.util.Try // We don't use CollectionConverters yet since we still want to cross-compile to scala 2.11 and 2.12 //import scala.jdk.CollectionConverters import scala.collection.JavaConverters._ /** * Created by peter on 12/04/17. */ object SourceReader { /** * Read the content of a given source. * * Mind that this function is NOT thread safe when reading from jar files. * * ToDo: extract & refactor the common parts in 'read' and 'readResources' * * @param source The source to read. * @param charsetName The charset the file content is encoded in. * @return A pair consisting of a file path and the file content. */ def read(source: String, charsetName: String = "UTF-8"): SourceFile = { // Resource loading // See: http://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource // What we see is that if resources start with a '/', then they get found by 'this.getClass.getResource'. If they don't start with // a '/', then they are found with 'this.getClass.getClassLoader.getResource'. val resource = Try(this.getClass.getResource(source).toURI).toOption // printReadStatus("regular resource", resource) // We want to assume that all resources given have an absolute path, also when they don't start with a '/' val classLoaderResource = Try(this.getClass.getClassLoader.getResource(source).toURI).toOption // printReadStatus("class loader resource", classLoaderResource) // File loading val file = Try(Paths.get(source)).filter(Files.exists(_)).map(_.toUri).toOption // printReadStatus("file resource", file) // URL loading val url = Try(new URL(source).toURI).toOption // printReadStatus("url resource", url) val uris: List[Option[URI]] = List(resource, classLoaderResource, file, url) // ToDo: replace with orElse structure & test val uri: URI = uris.flatten.headOption.getOrElse(sys.error(s"Unable to find resource $source")) val (thePath, fs): (Path, Option[FileSystem]) = uri.getScheme match { case "jar" => val fileSystem: FileSystem = Try(FileSystems.newFileSystem(uri, Collections.emptyMap[String, Any])) .recover { case exc: FileSystemAlreadyExistsException => FileSystems.getFileSystem(uri) // ToDo: see if reusing an open filesystem is a problem because it is closed below by the first thread that reaches that statement } .getOrElse { sys.error(s"Could not create or open filesystem for resource $uri") } (fileSystem.getPath(source), Some(fileSystem)) case _ => (Paths.get(uri), None) } val encoded: Array[Byte] = Files.readAllBytes(thePath) fs.foreach(_.close()) SourceFile(toDefaultFileSystem(thePath), new String(encoded, charsetName)) // ToDo: encoding detection via the file's BOM } /** * Read all files with a given extension in a given path, recursively through all subdirectories. * * Mind that this function is NOT thread safe when reading from jar files. * * http://www.uofr.net/~greg/java/get-resource-listing.html * http://alvinalexander.com/source-code/scala/create-list-all-files-beneath-directory-scala * http://stackoverflow.com/questions/31406471/get-resource-file-from-dependency-in-sbt * http://alvinalexander.com/blog/post/java/read-text-file-from-jar-file * * @param path The path that we want to read all files from recursively. * @param extension The extension of the files that we want to read. * @param charsetName The charset the file contents are encoded in. * @return */ def readResources(path: String, extension: String, charsetName: String = "UTF-8"): Set[SourceFile] = { val resource = Try(this.getClass.getResource(path).toURI).toOption val classLoaderResource = Try(this.getClass.getClassLoader.getResource(path).toURI).toOption val uris: List[Option[URI]] = List(resource, classLoaderResource) // ToDo: replace with orElse structure & test val uri: URI = uris.flatten.headOption.getOrElse(sys.error(s"Unable to find resource $path")) val (thePath, fs): (Path, Option[FileSystem]) = uri.getScheme match { case "jar" => val fileSystem = Try(FileSystems.newFileSystem(uri, Collections.emptyMap[String, Any])) .recover { case exc: FileSystemAlreadyExistsException => FileSystems.getFileSystem(uri) // ToDo: see if reusing an open filesystem is a problem because it is closed below by the first thread that reaches that statement } .getOrElse { sys.error(s"Could not create or open filesystem for resource $uri") } (fileSystem.getPath(path), Some(fileSystem)) case _ => (Paths.get(uri), None) } val walk = Files.walk(thePath) val paths: Set[Path] = walk.iterator.asScala.toSet def isFileWithExtension(somePath: Path): Boolean = Files.isRegularFile(somePath) && somePath.getFileName.toString.toLowerCase.endsWith(extension.toLowerCase) val sourceFiles = paths.collect { case currentPath if isFileWithExtension(currentPath) => val enc: Array[Byte] = Files.readAllBytes(currentPath) SourceFile(toDefaultFileSystem(currentPath), new String(enc, charsetName)) } fs.foreach(_.close()) sourceFiles } /** * Later on, we want to combine Path objects, but that only works when their filesystems are compatible, * so we convert paths that come out of a jar archive to the default filesystem. * * See: http://stackoverflow.com/questions/22611919/why-do-i-get-providermismatchexception-when-i-try-to-relativize-a-path-agains * * @param path The path to convert to the default filesystem. * @return The converted path. */ def toDefaultFileSystem(path: Path): Path = { val rootPath = if (path.isAbsolute) Paths.get(FileSystems.getDefault.getSeparator) else Paths.get("") path.iterator().asScala.foldLeft(rootPath) { case (aggr, component) => aggr.resolve(component.getFileName.toString) } } def getInputStreamContent(inputStream: InputStream): Array[Byte] = Stream.continually(inputStream.read).takeWhile(_ != -1).map(_.toByte).toArray /** * Beware, Windows paths are represented as URL as follows: file:///C:/Users/someone * uri.normalize().getPath then gives /C:/Users/someone instead of C:/Users/someone * also Paths.get(uri) then assumes /C:/Users/someone * One would think the java.nio.file implementation does it right, but it doesn't. * * This hack fixes this. * * see: http://stackoverflow.com/questions/18520972/converting-java-file-url-to-file-path-platform-independent-including-u * * http://stackoverflow.com/questions/9834776/java-nio-file-path-issue * */ private def cleanWindowsTripleSlashIssue(path: String): String = { val hasWindowsPrefix = path.split('/').filter(_.nonEmpty).headOption.collect { case first if first.endsWith(":") => true } getOrElse false if (hasWindowsPrefix && path.startsWith("/")) path.drop(1) else path } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/codegen/ActionGenerator.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.codegen import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform } import io.atomicbits.scraml.generator.restmodel._ import io.atomicbits.scraml.generator.typemodel._ import io.atomicbits.scraml.ramlparser.model.{ Method, Resource } /** * Created by peter on 20/01/17. */ case class ActionGenerator(actionCode: ActionCode) { /** * The reason why we treat all actions of a resource together is that certain paths towards the actual action * execution of the resource's actions may overlap when it concerns actions that have overlapping mandatory * content-type and/or accept header paths. Although such situations may be rare, we want to support them well, * so we pass all actions of a single resource together. * * @param resourceClassDefinition The resource class definition of the resource whose actions are going to be processed * (NOT recursively!) * @return A list of action function definitions or action paths that lead to the action function. Action paths will only be * required if multiple contenttype and/or accept headers will lead to a different typed body and/or response (we * don't support those yet, but we will do so in the future). */ def generateActionFunctions(resourceClassDefinition: ResourceClassDefinition)(implicit platform: Platform): SourceCodeFragment = { val resourcePackageParts: List[String] = resourceClassDefinition.resourcePackage val resource: Resource = resourceClassDefinition.resource val actionSelections: Set[ActionSelection] = resource.actions.map(ActionSelection(_)).toSet val actionsWithTypeSelection: Set[ActionSelection] = actionSelections.flatMap { actionSelection => for { contentType <- actionSelection.contentTypeHeaders responseType <- actionSelection.responseTypeHeaders actionWithTypeSelection = actionSelection.withContentTypeSelection(contentType).withResponseTypeSelection(responseType) } yield actionWithTypeSelection } val groupedByActionType: Map[Method, Set[ActionSelection]] = actionsWithTypeSelection.groupBy(_.action.actionType) // now, we have to map the actions onto a segment path if necessary val actionPathToAction: Set[ActionPath] = groupedByActionType.values.toList.map(_.toList).flatMap { case actionOfKindList @ (aok :: Nil) => List(ActionPath(NoContentHeaderSegment, NoAcceptHeaderSegment, actionOfKindList.head)) case actionOfKindList @ (aok :: aoks) => actionOfKindList.map { actionOfKind => val contentHeader = actionOfKind.selectedContentType match { case NoContentType => NoContentHeaderSegment case ct: ContentType => ActualContentHeaderSegment(ct) } val acceptHeader = actionOfKind.selectedResponseType match { // The selectedResponseTypesWithStatus have the same media type. case NoResponseType => NoAcceptHeaderSegment case rt: ResponseType => ActualAcceptHeaderSegment(rt) } ActionPath(contentHeader, acceptHeader, actionOfKind) } case Nil => Set.empty }.toSet val uniqueActionPaths: Map[ContentHeaderSegment, Map[AcceptHeaderSegment, Set[ActionSelection]]] = actionPathToAction .groupBy(_.contentHeader) .mapValues(_.groupBy(_.acceptHeader)) .mapValues(_.mapValues(_.map(_.action)).toMap).toMap val actionPathExpansion = uniqueActionPaths map { case (NoContentHeaderSegment, acceptHeaderMap) => expandAcceptHeaderMap(resourcePackageParts, acceptHeaderMap) case (ActualContentHeaderSegment(contentType), acceptHeaderMap) => expandContentTypePath(resourcePackageParts, contentType, acceptHeaderMap) } if (actionPathExpansion.nonEmpty) actionPathExpansion.reduce(_ ++ _) else SourceCodeFragment() } private def expandContentTypePath( resourcePackageParts: List[String], contentType: ContentType, acceptHeaderMap: Map[AcceptHeaderSegment, Set[ActionSelection]])(implicit platform: Platform): SourceCodeFragment = { // create the content type path class extending a HeaderSegment and add the class to the List[ClassRep] result // add a content type path field that instantiates the above class (into the List[String] result) // add the List[String] results of the expansion of the acceptHeader map to source of the above class // add the List[ClassRep] results of the expansion of the acceptHeader map to the List[ClassRep] result val SourceCodeFragment(acceptSegmentMethodImports, acceptSegmentMethods, acceptHeaderClasses) = expandAcceptHeaderMap(resourcePackageParts, acceptHeaderMap) // Header segment classes have the same class name in Java as in Scala. val headerSegmentClassName = s"Content${CleanNameTools.cleanClassName(contentType.contentTypeHeader.value)}HeaderSegment" val headerSegment: HeaderSegmentClassDefinition = createHeaderSegment(resourcePackageParts, headerSegmentClassName, acceptSegmentMethodImports, acceptSegmentMethods) val contentHeaderMethodName = s"content${CleanNameTools.cleanClassName(contentType.contentTypeHeader.value)}" val contentHeaderSegment: String = actionCode.contentHeaderSegmentField(contentHeaderMethodName, headerSegment.reference) SourceCodeFragment(imports = Set.empty, sourceDefinition = List(contentHeaderSegment), headerPathClassDefinitions = headerSegment :: acceptHeaderClasses) } private def expandAcceptHeaderMap(resourcePackageParts: List[String], acceptHeaderMap: Map[AcceptHeaderSegment, Set[ActionSelection]])( implicit platform: Platform): SourceCodeFragment = { val actionPathExpansion: List[SourceCodeFragment] = acceptHeaderMap.toList match { case (_, actionSelections) :: Nil => actionSelections.map(ActionFunctionGenerator(actionCode).generate).toList case ahMap @ (ah :: ahs) => ahMap flatMap { case (NoAcceptHeaderSegment, actionSelections) => actionSelections.map(ActionFunctionGenerator(actionCode).generate).toList case (ActualAcceptHeaderSegment(responseType), actionSelections) => List(expandResponseTypePath(resourcePackageParts, responseType, actionSelections)) } case Nil => List.empty } actionPathExpansion.foldLeft(SourceCodeFragment())(_ ++ _) } private def expandResponseTypePath(resourcePackageParts: List[String], responseType: ResponseType, actions: Set[ActionSelection])( implicit platform: Platform): SourceCodeFragment = { // create the result type path class extending a HeaderSegment and add the class to the List[ClassRep] result // add a result type path field that instantiates the above class (into the List[String] result) // add the List[String] results of the expansion of the actions to the above class and also add the imports needed by the actions // into the above class val actionFunctionResults = actions.map(ActionFunctionGenerator(actionCode).generate) val actionImports = actionFunctionResults.flatMap(_.imports) val actionMethods = actionFunctionResults.flatMap(_.sourceDefinition).toList // Header segment classes have the same class name in Java as in Scala. val headerSegmentClassName = s"Accept${CleanNameTools.cleanClassName(responseType.acceptHeader.value)}HeaderSegment" val headerSegment: HeaderSegmentClassDefinition = createHeaderSegment(resourcePackageParts, headerSegmentClassName, actionImports, actionMethods) val acceptHeaderMethodName = s"accept${CleanNameTools.cleanClassName(responseType.acceptHeader.value)}" val acceptHeaderSegment: String = actionCode.contentHeaderSegmentField(acceptHeaderMethodName, headerSegment.reference) SourceCodeFragment(imports = Set.empty, sourceDefinition = List(acceptHeaderSegment), headerPathClassDefinitions = List(headerSegment)) } private def createHeaderSegment(packageParts: List[String], className: String, imports: Set[ClassPointer], methods: List[String]): HeaderSegmentClassDefinition = { val classReference = ClassReference(name = className, packageParts = packageParts) HeaderSegmentClassDefinition(reference = classReference, imports = imports, methods = methods) } // Helper class to represent the path from a resource to an action over a content header segment and a accept header segment. case class ActionPath(contentHeader: ContentHeaderSegment, acceptHeader: AcceptHeaderSegment, action: ActionSelection) sealed trait HeaderSegment sealed trait ContentHeaderSegment extends HeaderSegment sealed trait AcceptHeaderSegment extends HeaderSegment case object NoContentHeaderSegment extends ContentHeaderSegment case class ActualContentHeaderSegment(header: ContentType) extends ContentHeaderSegment case object NoAcceptHeaderSegment extends AcceptHeaderSegment case class ActualAcceptHeaderSegment(header: ResponseType) extends AcceptHeaderSegment }
atomicbits/scramlgen
modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/ExpandRelativeToAbsoluteIdsTest.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser import io.atomicbits.scraml.ramlparser.lookup.{ CanonicalNameGenerator, CanonicalTypeCollector } import io.atomicbits.scraml.ramlparser.model.parsedtypes._ import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.parser.RamlParser import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import org.scalatest.featurespec.AnyFeatureSpec import org.scalatest.matchers.should.Matchers._ import scala.util.Try /** * Created by peter on 1/01/17. */ class ExpandRelativeToAbsoluteIdsTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll { Feature("Expand all relative IDs to absolute IDs in any json-schema ParsedType") { Scenario("test fragment reference ID expansion in a json-schema type") { Given("a RAML specification containing a json-schema definition with fragments") val defaultBasePath = List("io", "atomicbits", "schemas") val parser = RamlParser("/fragments/TestFragmentsApi.raml", "UTF-8") When("we parse the specification") val parsedModel: Try[Raml] = parser.parse val canonicalTypeCollector = CanonicalTypeCollector(CanonicalNameGenerator(defaultBasePath)) Then("we all our relative fragment IDs and their references are expanded to absolute IDs") val raml = parsedModel.get val parsedType = raml.types.get(NativeId("myfragments")).get val myFragmentsExpanded = canonicalTypeCollector.indexer.expandRelativeToAbsoluteIds(parsedType).asInstanceOf[ParsedObject] val definitionsFragment = myFragmentsExpanded.fragments.fragmentMap("definitions").asInstanceOf[Fragments] val addressFragment = definitionsFragment.fragments.fragmentMap("address").asInstanceOf[ParsedObject] println(s"$myFragmentsExpanded") addressFragment.id shouldBe AbsoluteFragmentId(RootId("http://atomicbits.io/schema/fragments.json"), List("definitions", "address")) val barsFragment = definitionsFragment.fragments.fragmentMap("bars").asInstanceOf[ParsedObject] println(s"$barsFragment") barsFragment.id shouldBe AbsoluteFragmentId(RootId("http://atomicbits.io/schema/fragments.json"), List("definitions", "bars")) val fooReference = myFragmentsExpanded.properties.valueMap("foo").propertyType val fooArray = fooReference.parsed.asInstanceOf[ParsedArray] val fooArrayItemId = fooArray.items.asInstanceOf[ParsedTypeReference].refersTo fooArrayItemId shouldBe AbsoluteFragmentId(RootId("http://atomicbits.io/schema/fragments.json"), List("definitions", "address")) val foobarsReference = myFragmentsExpanded.properties.valueMap("foobars").propertyType val foobarsArray = foobarsReference.parsed.asInstanceOf[ParsedArray] val foobarsArrayItemId = foobarsArray.items.asInstanceOf[ParsedTypeReference].refersTo foobarsArrayItemId shouldBe AbsoluteFragmentId(RootId("http://atomicbits.io/schema/fragments.json"), List("definitions", "bars")) } } }
atomicbits/scramlgen
modules/scraml-gen-simulation/src/test/scala/io/atomicbits/scraml/client/manual/BigCaseClass.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.client.manual import play.api.libs.json._ /** * Created by peter on 26/09/16. */ case class BigCaseClass(a: Option[String], b: String, c: String, d: String, e: String, f: String, g: String, h: String, i: String, j: String, k: String, l: String, m: String, n: String, o: String, p: String, q: String, r: String, s: String, t: String, u: String, v: String, w: String, x: String, y: String, z: String) object BigCaseClass { import play.api.libs.functional.syntax._ implicit def jsonFormatter: Format[BigCaseClass] = { val fields1 = ((__ \ "a").formatNullable[String] ~ (__ \ "b").format[String] ~ (__ \ "c").format[String] ~ (__ \ "d").format[String] ~ (__ \ "e").format[String] ~ (__ \ "f").format[String] ~ (__ \ "g").format[String] ~ (__ \ "h").format[String] ~ (__ \ "i").format[String] ~ (__ \ "j").format[String] ~ (__ \ "k").format[String] ~ (__ \ "l").format[String] ~ (__ \ "m").format[String] ~ (__ \ "n").format[String] ~ (__ \ "o").format[String] ~ (__ \ "p").format[String] ~ (__ \ "q").format[String] ~ (__ \ "r").format[String] ~ (__ \ "s").format[String] ~ (__ \ "t").format[String] ~ (__ \ "u").format[String]).tupled val fields2 = ((__ \ "v").format[String] ~ (__ \ "w").format[String] ~ (__ \ "x").format[String] ~ (__ \ "y").format[String] ~ (__ \ "z").format[String]).tupled def pack: ((Option[String], String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String), (String, String, String, String, String)) => BigCaseClass = { case ((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u), (v, w, x, y, z)) => BigCaseClass.apply(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z) } def unpack: BigCaseClass => ((Option[String], String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String), (String, String, String, String, String)) = { bcc => ((bcc.a, bcc.b, bcc.c, bcc.d, bcc.e, bcc.f, bcc.g, bcc.h, bcc.i, bcc.j, bcc.k, bcc.l, bcc.m, bcc.n, bcc.o, bcc.p, bcc.q, bcc.r, bcc.s, bcc.t, bcc.u), (bcc.v, bcc.w, bcc.x, bcc.y, bcc.z)) } (fields1 and fields2).apply(pack, unpack) } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/htmldoc/IndexDocGenerator.scala
<reponame>atomicbits/scramlgen /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.htmldoc import io.atomicbits.scraml.generator.codegen.GenerationAggr import io.atomicbits.scraml.generator.platform.SourceGenerator import io.atomicbits.scraml.generator.typemodel.ClientClassDefinition import io.atomicbits.scraml.ramlparser.parser.SourceFile import com.github.mustachejava.DefaultMustacheFactory import java.io.StringWriter import io.atomicbits.scraml.generator.platform.Platform._ import io.atomicbits.scraml.generator.platform.htmldoc.simplifiedmodel.ClientDocModel import scala.collection.JavaConverters._ /** * Created by peter on 9/05/18. */ object IndexDocGenerator extends SourceGenerator { implicit val platform: HtmlDoc.type = HtmlDoc def generate(generationAggr: GenerationAggr, clientClassDefinition: ClientClassDefinition): GenerationAggr = { val writer = new StringWriter() val mf = new DefaultMustacheFactory() val mustache = mf.compile("platform/htmldoc/index.mustache") val clientDocModel = ClientDocModel(clientClassDefinition, generationAggr) mustache.execute(writer, toJavaMap(clientDocModel)) writer.flush() val content = writer.toString generationAggr.addSourceFile(SourceFile(clientClassDefinition.classReference.toFilePath, content)) } /** * Transforms a (case) class content to a Java map recursively. * * See: https://stackoverflow.com/questions/1226555/case-class-to-map-in-scala * */ def toJavaMap(cc: Product, visited: Set[Any] = Set.empty): java.util.Map[String, Any] = { def mapValue(f: Any): Any = { f match { case None => null case Some(v) => mapValue(v) case Nil => null case l: List[_] => l.map(mapValue).asJava case m: Map[_, _] => m.mapValues(mapValue).asJava case p: Product if p.productArity > 0 && !visited.contains(p) => toJavaMap(p, visited + cc) case x => x } } // println(s"Processing class ${cc.getClass.getSimpleName}") cc.getClass.getDeclaredFields .foldLeft(Map.empty[String, Any]) { (fieldMap, field) => field.setAccessible(true) val name = field.getName val value = mapValue(field.get(cc)) fieldMap + (name -> value) }.asJava } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/CanonicalTypeCollectorTest.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser import io.atomicbits.scraml.ramlparser.lookup.{ CanonicalNameGenerator, CanonicalTypeCollector } import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.model.canonicaltypes._ import io.atomicbits.scraml.ramlparser.model.parsedtypes.{ ParsedArray, ParsedNumber, ParsedString, ParsedTypeReference } import io.atomicbits.scraml.ramlparser.parser.RamlParser import org.scalatest.featurespec.AnyFeatureSpec import org.scalatest.matchers.should.Matchers._ import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import scala.language.postfixOps import scala.util.Try /** * Created by peter on 30/12/16. */ class CanonicalTypeCollectorTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll { Feature("Collect the canonical representations of a simple fragmented json-schema definition") { Scenario("test collecting of all canonical types") { Given("a RAML specification containing a json-schema definition with fragments") val defaultBasePath = List("io", "atomicbits", "schema") val parser = RamlParser("/fragments/TestFragmentsApi.raml", "UTF-8") When("we parse the specification") val parsedModel: Try[Raml] = parser.parse implicit val canonicalNameGenerator: CanonicalNameGenerator = CanonicalNameGenerator(defaultBasePath) val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator) Then("we all our relative fragment IDs and their references are expanded to absolute IDs") val raml = parsedModel.get val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml) val fragments = canonicalLookup(CanonicalName.create(name = "Fragments", packagePath = List("io", "atomicbits", "schema"))) .asInstanceOf[ObjectType] val foobarPointer = fragments.properties("foobarpointer").asInstanceOf[Property[ArrayTypeReference]].ttype foobarPointer.genericType.isInstanceOf[NumberType.type] shouldBe true val foobarList = fragments.properties("foobarlist").asInstanceOf[Property[ArrayTypeReference]].ttype foobarList.genericType.isInstanceOf[NumberType.type] shouldBe true val foobars = fragments.properties("foobars").asInstanceOf[Property[ArrayTypeReference]].ttype foobars.genericType.isInstanceOf[NonPrimitiveTypeReference] shouldBe true foobars.genericType.asInstanceOf[NonPrimitiveTypeReference].refers shouldBe CanonicalName.create(name = "FragmentsDefinitionsBars", packagePath = List("io", "atomicbits", "schema")) val foo = fragments.properties("foo").asInstanceOf[Property[ArrayTypeReference]].ttype foo.genericType.isInstanceOf[NonPrimitiveTypeReference] shouldBe true foo.genericType.asInstanceOf[NonPrimitiveTypeReference].refers shouldBe CanonicalName.create(name = "FragmentsDefinitionsAddress", packagePath = List("io", "atomicbits", "schema")) val fragmentDefBars = canonicalLookup(CanonicalName.create(name = "FragmentsDefinitionsBars", packagePath = List("io", "atomicbits", "schema"))) .asInstanceOf[ObjectType] fragmentDefBars.properties("baz").isInstanceOf[Property[_]] shouldBe true fragmentDefBars.properties("baz").ttype.isInstanceOf[StringType.type] shouldBe true val fragmentDefAddress = canonicalLookup(CanonicalName.create(name = "FragmentsDefinitionsAddress", packagePath = List("io", "atomicbits", "schema"))) .asInstanceOf[ObjectType] fragmentDefAddress.properties("city").isInstanceOf[Property[_]] shouldBe true fragmentDefAddress.properties("city").ttype.isInstanceOf[StringType.type] shouldBe true fragmentDefAddress.properties("state").isInstanceOf[Property[_]] shouldBe true fragmentDefAddress.properties("state").ttype.isInstanceOf[StringType.type] shouldBe true fragmentDefAddress.properties("zip").isInstanceOf[Property[_]] shouldBe true fragmentDefAddress.properties("zip").ttype.isInstanceOf[IntegerType.type] shouldBe true fragmentDefAddress.properties("streetAddress").isInstanceOf[Property[_]] shouldBe true fragmentDefAddress.properties("streetAddress").ttype.isInstanceOf[StringType.type] shouldBe true } } Feature("Collect the canonical representations of a complex and mixed json-schema/RAML1.0 definition") { Scenario("test collecting json-schema types in a RAML model") { Given("a RAML specification containing json-schema definitions") val defaultBasePath = List("io", "atomicbits", "schema") val parser = RamlParser("/raml08/TestApi.raml", "UTF-8") When("we parse the specification") val parsedModel: Try[Raml] = parser.parse val canonicalTypeCollector = CanonicalTypeCollector(CanonicalNameGenerator(defaultBasePath)) Then("we get all expected canonical representations") val raml = parsedModel.get val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml) val pagedList = CanonicalName.create(name = "PagedList", packagePath = List("io", "atomicbits", "schema")) val method = CanonicalName.create(name = "Method", packagePath = List("io", "atomicbits", "schema")) val geometry = CanonicalName.create(name = "Geometry", packagePath = List("io", "atomicbits", "schema")) val point = CanonicalName.create(name = "Point", packagePath = List("io", "atomicbits", "schema")) val multiPoint = CanonicalName.create(name = "MultiPoint", packagePath = List("io", "atomicbits", "schema")) val lineString = CanonicalName.create(name = "LineString", packagePath = List("io", "atomicbits", "schema")) val multiLineString = CanonicalName.create(name = "MultiLineString", packagePath = List("io", "atomicbits", "schema")) val polygon = CanonicalName.create(name = "Polygon", packagePath = List("io", "atomicbits", "schema")) val multiPolygon = CanonicalName.create(name = "MultiPolygon", packagePath = List("io", "atomicbits", "schema")) val geometryCollection = CanonicalName.create(name = "GeometryCollection", packagePath = List("io", "atomicbits", "schema")) val crs = CanonicalName.create(name = "Crs", packagePath = List("io", "atomicbits", "schema")) val namedCrsProperty = CanonicalName.create(name = "NamedCrsProperty", packagePath = List("io", "atomicbits", "schema")) val animal = CanonicalName.create(name = "Animal", packagePath = List("io", "atomicbits", "schema")) val dog = CanonicalName.create(name = "Dog", packagePath = List("io", "atomicbits", "schema")) val cat = CanonicalName.create(name = "Cat", packagePath = List("io", "atomicbits", "schema")) val fish = CanonicalName.create(name = "Fish", packagePath = List("io", "atomicbits", "schema")) val link = CanonicalName.create(name = "Link", packagePath = List("io", "atomicbits", "schema")) val book = CanonicalName.create(name = "Book", packagePath = List("io", "atomicbits", "schema")) val userDefinitionsAddress = CanonicalName.create(name = "UserDefinitionsAddress", packagePath = List("io", "atomicbits", "schema")) val user = CanonicalName.create(name = "User", packagePath = List("io", "atomicbits", "schema")) val author = CanonicalName.create(name = "Author", packagePath = List("io", "atomicbits", "schema")) val error = CanonicalName.create(name = "Error", packagePath = List("io", "atomicbits", "schema")) val expectedCanonicalNames = Set( pagedList, method, geometry, point, multiPoint, lineString, multiLineString, polygon, multiPolygon, geometryCollection, namedCrsProperty, crs, animal, dog, cat, fish, link, book, userDefinitionsAddress, user, author, error ) val collectedCanonicalNames = canonicalLookup.map.map { case (canonicalName, theType) => canonicalName }.toSet expectedCanonicalNames -- collectedCanonicalNames shouldBe Set.empty collectedCanonicalNames -- expectedCanonicalNames shouldBe Set.empty val dogType = canonicalLookup(dog).asInstanceOf[ObjectType] dogType.typeDiscriminator shouldBe Some("_type") dogType.typeDiscriminatorValue shouldBe Some("Dog") dogType.parents shouldBe List(NonPrimitiveTypeReference(refers = animal)) dogType.properties("name") shouldBe Property(name = "name", ttype = StringType, required = false, typeConstraints = None) dogType.properties("canBark") shouldBe Property(name = "canBark", ttype = BooleanType, typeConstraints = None) dogType.properties("gender") shouldBe Property(name = "gender", ttype = StringType, typeConstraints = None) dogType.canonicalName shouldBe dog // Check the updated RAML model val restResource = ramlUpdated.resourceMap("rest") val userResource = restResource.resourceMap("user") val userGetAction = userResource.actionMap(Get) val queryParameterMap = userGetAction.queryParameters.valueMap queryParameterMap("age").required shouldBe true queryParameterMap("age").parameterType.parsed.isInstanceOf[ParsedNumber] shouldBe true queryParameterMap("age").parameterType.canonical shouldBe Some(NumberType) queryParameterMap("organization").required shouldBe true queryParameterMap("organization").parameterType.parsed.isInstanceOf[ParsedArray] shouldBe true queryParameterMap("organization").parameterType.canonical shouldBe Some(ArrayTypeReference(genericType = StringType)) val okResponse = userGetAction.responses.responseMap(StatusCode("200")) val okResponseBodyContent = okResponse.body.contentMap(MediaType("application/vnd-v1.0+json")) okResponseBodyContent.bodyType.get.parsed.isInstanceOf[ParsedArray] shouldBe true okResponseBodyContent.bodyType.get.canonical shouldBe Some( ArrayTypeReference(genericType = NonPrimitiveTypeReference(refers = user)) ) val userIdResource = userResource.resourceMap("userid") val userIdDogsResource = userIdResource.resourceMap("dogs") val userIdDogsGetAction = userIdDogsResource.actionMap(Get) // Check the paged list type representation val pagedListTypeRepresentation = userIdDogsGetAction.responses.responseMap(StatusCode("200")).body.contentMap(MediaType("application/vnd-v1.0+json")).bodyType.get val parsedPagedListType: ParsedTypeReference = pagedListTypeRepresentation.parsed.asInstanceOf[ParsedTypeReference] parsedPagedListType.refersTo shouldBe RootId("http://atomicbits.io/schema/paged-list.json") val dogTypeReference = parsedPagedListType.genericTypes.head.asInstanceOf[ParsedTypeReference] dogTypeReference.refersTo shouldBe RootId("http://atomicbits.io/schema/dog.json") parsedPagedListType.genericTypes.tail.head.isInstanceOf[ParsedString] shouldBe true val canonicalPagedListType: NonPrimitiveTypeReference = pagedListTypeRepresentation.canonical.get.asInstanceOf[NonPrimitiveTypeReference] canonicalPagedListType.genericTypes.head.isInstanceOf[NonPrimitiveTypeReference] canonicalPagedListType.genericTypes.tail.head.isInstanceOf[NonPrimitiveTypeReference] // Check the paged list type model val pagedListType = canonicalLookup(pagedList).asInstanceOf[ObjectType] pagedListType.properties("elements") shouldBe Property(name = "elements", ttype = ArrayTypeReference(genericType = TypeParameter("T")), required = true, typeConstraints = None) val userType = canonicalLookup(user).asInstanceOf[ObjectType] userType.properties("address").required shouldBe false } Scenario("test collecting RAML 1.0 types in a RAML model") { Given("a RAML specification containing RAML 1.0 definitions") val defaultBasePath = List("io", "atomicbits", "schema") val parser = RamlParser("/nativeidlookup/NativeIdLookupTest.raml", "UTF-8") When("we parse the specification") val parsedModel: Try[Raml] = parser.parse val canonicalTypeCollector = CanonicalTypeCollector(CanonicalNameGenerator(defaultBasePath)) Then("we get all expected canonical representations") val raml = parsedModel.get val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml) val restResource = ramlUpdated.resourceMap("rest") val booksResource = restResource.resourceMap("books") val booksGetAction = booksResource.actionMap(Get) val booksReturnType: TypeRepresentation = booksGetAction.responses.responseMap(StatusCode("200")).body.contentMap(MediaType("application/json")).bodyType.get val book = CanonicalName.create(name = "Book", packagePath = List("io", "atomicbits", "schema")) val booksArrayTypeReference = booksReturnType.canonical.get.asInstanceOf[ArrayTypeReference] booksArrayTypeReference.genericType.asInstanceOf[NonPrimitiveTypeReference].refers shouldBe book } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/ObjectType.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.canonicaltypes /** * Created by peter on 9/12/16. */ case class ObjectType(canonicalName: CanonicalName, properties: Map[String, Property[_ <: GenericReferrable]], parents: List[TypeReference] = List.empty, typeParameters: List[TypeParameter] = List.empty, typeDiscriminator: Option[String] = None, typeDiscriminatorValue: Option[String] = None) extends NonPrimitiveType
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/EnumGenerator.scala
<filename>modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/EnumGenerator.scala /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.scalaplay import io.atomicbits.scraml.generator.codegen.GenerationAggr import io.atomicbits.scraml.generator.platform.{ Platform, SourceGenerator } import io.atomicbits.scraml.generator.typemodel.EnumDefinition import io.atomicbits.scraml.generator.platform.Platform._ import io.atomicbits.scraml.generator.util.CleanNameUtil import io.atomicbits.scraml.ramlparser.parser.SourceFile /** * Created by peter on 14/01/17. */ case class EnumGenerator(scalaPlay: ScalaPlay) extends SourceGenerator { implicit val platform: ScalaPlay = scalaPlay def generate(generationAggr: GenerationAggr, enumDefinition: EnumDefinition): GenerationAggr = { val imports: Set[String] = platform.importStatements(enumDefinition.reference) val source = s""" package ${enumDefinition.reference.packageName} import play.api.libs.json.{Format, Json, JsResult, JsValue, JsString} ${imports.mkString("\n")} sealed trait ${enumDefinition.reference.name} { def name:String } ${generateEnumCompanionObject(enumDefinition)} """ val sourceFile = SourceFile( filePath = enumDefinition.reference.toFilePath, content = source ) generationAggr.addSourceFile(sourceFile) } private def generateEnumCompanionObject(enumDefinition: EnumDefinition): String = { // Accompany the enum names with their 'Scala-safe' name. val enumsValuesWithSafeName = enumDefinition.values map { value => val safeName = scalaPlay.escapeScalaKeyword(CleanNameUtil.cleanEnumName(value)) value -> safeName } def enumValue(valueWithSafeName: (String, String)): String = { val (value, safeName) = valueWithSafeName s""" case object $safeName extends ${enumDefinition.reference.name} { val name = "$value" } """ } val enumMapValues = enumsValuesWithSafeName .map { case (value, safeName) => s"$safeName.name -> $safeName" } .mkString(",") val name = enumDefinition.reference.name s""" object $name { ${enumsValuesWithSafeName.map(enumValue).mkString("\n")} val byName = Map($enumMapValues) implicit val ${name}Format = new Format[$name] { override def reads(json: JsValue): JsResult[$name] = { json.validate[String].map($name.byName(_)) } override def writes(o: $name): JsValue = { JsString(o.name) } } } """ } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/CanonicalNameGenerator.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.lookup import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName /** * Created by peter on 17/12/16. */ case class CanonicalNameGenerator(defaultBasePath: List[String]) { def generate(id: Id): CanonicalName = id match { case absoluteId: AbsoluteId => absoluteIdToCanonicalName(absoluteId) case relId: RelativeId => CanonicalName.create(name = relId.name, packagePath = defaultBasePath ++ relId.path) case nativeId: NativeId => CanonicalName.create(name = nativeId.id, packagePath = defaultBasePath) case ImplicitId => CanonicalName.noName(packagePath = defaultBasePath) case x => sys.error(s"Cannot create a canonical name from a ${x.getClass.getSimpleName}") } def toRootId(id: Id): RootId = RootId.fromCanonical(generate(id)) private def absoluteIdToCanonicalName(origin: AbsoluteId): CanonicalName = { val hostPathReversed = origin.hostPath.reverse val relativePath = origin.rootPath.dropRight(1) val originalFileName = origin.rootPath.takeRight(1).head val fragmentPath = origin.fragments // E.g. when the origin is: http://atomicbits.io/api/schemas/myschema.json#/definitions/schema2 // then: // hostPathReversed = List("io", "atomicbits") // relativePath = List("api", "schemas") // originalFileName = "myschema.json" // fragmentPath = List("definitions", "schema2") val classBaseName = CanonicalName.cleanClassNameFromFileName(originalFileName) val path = hostPathReversed ++ relativePath val fragment = fragmentPath val className = fragment.foldLeft(classBaseName) { (classNm, fragmentPart) => s"$classNm${CanonicalName.cleanClassName(fragmentPart)}" } CanonicalName.create(name = className, packagePath = path) } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedUnionType.scala
<reponame>atomicbits/scramlgen /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.parsedtypes import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.parser.{ ParseContext, RamlParseException } import io.atomicbits.scraml.util.TryUtils import io.atomicbits.scraml.ramlparser.parser.JsUtils._ import play.api.libs.json.{ JsString, JsValue } import scala.util.{ Failure, Success, Try } /** * Created by peter on 1/11/16. */ case class ParsedUnionType(types: Set[ParsedType], required: Option[Boolean] = None, model: TypeModel = RamlModel, id: Id = ImplicitId) extends NonPrimitiveType with AllowedAsObjectField { override def updated(updatedId: Id): ParsedUnionType = copy(id = updatedId) override def asTypeModel(typeModel: TypeModel): ParsedType = copy(model = typeModel, types = types.map(_.asTypeModel(typeModel))) def asRequired = copy(required = Some(true)) } object ParsedUnionType { def unapply(unionExpression: String)(implicit parseContext: ParseContext): Option[Try[ParsedUnionType]] = { addUnionTypes(ParsedUnionType(Set.empty), unionExpression) } def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[ParsedUnionType]] = { (ParsedType.typeDeclaration(json), json) match { case (Some(JsString(unionExpression)), _) => val required = json.fieldBooleanValue("required") addUnionTypes(ParsedUnionType(Set.empty, required), unionExpression) case (_, JsString(unionExpression)) => addUnionTypes(ParsedUnionType(Set.empty), unionExpression) case _ => None } } private def addUnionTypes(unionType: ParsedUnionType, unionExpression: String)( implicit parseContext: ParseContext): Option[Try[ParsedUnionType]] = { typeExpressions(unionExpression).map { triedExpressions => val triedTypes = triedExpressions.flatMap { stringExpressions => TryUtils.accumulate(stringExpressions.map(ParsedType(_))) } triedTypes.map { types => unionType.copy(types = types.toSet) } } } private def typeExpressions(unionExpression: String)(implicit parseContext: ParseContext): Option[Try[List[String]]] = { val unionExprTrimmed = unionExpression.trim val unionExprUnwrapped: Try[String] = if (unionExprTrimmed.startsWith("(")) { if (unionExprTrimmed.endsWith(")")) Success(unionExprTrimmed.drop(1).dropRight(1)) else Failure(RamlParseException(s"Union expression $unionExprTrimmed starts with a '(' but doesn't end with a ')'.")) } else { Success(unionExprTrimmed) } val typeExpressions = unionExprUnwrapped.map { unionExpr => unionExpr.split('|').toList.map(_.trim) } typeExpressions match { case Success(exp1 :: exp2 :: exps) => Some(typeExpressions) case Success(_) => None case Failure(exc) => Some(typeExpressions) } } }
atomicbits/scramlgen
modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/RequestBuilder.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.dsl.scalaplay import play.api.libs.json.{ Format, JsValue } import scala.concurrent.Future /** * Created by peter on 21/05/15, Atomic BITS (http://atomicbits.io). */ case class RequestBuilder(client: Client, reversePath: List[String] = Nil, method: Method = Get, queryParameters: Map[String, HttpParam] = Map.empty, formParameters: Map[String, HttpParam] = Map.empty, multipartParams: List[BodyPart] = List.empty, binaryBody: Option[BinaryRequest] = None, headers: HeaderMap = HeaderMap()) { def relativePath: String = reversePath.reverse.mkString("/", "/", "") def defaultHeaders: Map[String, String] = client.defaultHeaders lazy val allHeaders: HeaderMap = HeaderMap() ++ (defaultHeaders.toList: _*) ++ headers // headers last to overwrite defaults! def isFormPost: Boolean = method == Post && formParameters.nonEmpty def isMultipartFormUpload: Boolean = allHeaders.get("Content-Type").exists(_.contains("multipart/form-data")) def callToStringResponse(body: Option[String]): Future[Response[String]] = client.callToStringResponse(this, body) def callToJsonResponse(body: Option[String]): Future[Response[JsValue]] = client.callToJsonResponse(this, body) def callToTypeResponse[R](body: Option[String])(implicit responseFormat: Format[R]): Future[Response[R]] = client.callToTypeResponse(this, body) def callToBinaryResponse(body: Option[String]): Future[Response[BinaryData]] = client.callToBinaryResponse(this, body) def summary: String = s"$method request to ${reversePath.reverse.mkString("/")}" def withAddedHeaders(additionalHeaders: (String, String)*): RequestBuilder = { this.copy(headers = this.headers ++ (additionalHeaders: _*)) } def withSetHeaders(additionalHeaders: (String, String)*): RequestBuilder = { this.copy(headers = this.headers set (additionalHeaders: _*)) } def withAddedPathSegment(additionalPathSegment: Any): RequestBuilder = { this.copy(reversePath = additionalPathSegment.toString :: this.reversePath) } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/TraitGenerator.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.scalaplay import io.atomicbits.scraml.generator.codegen.{ DslSourceRewriter, GenerationAggr } import io.atomicbits.scraml.generator.platform.{ Platform, SourceGenerator } import io.atomicbits.scraml.generator.typemodel._ import io.atomicbits.scraml.generator.platform.Platform._ import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName import io.atomicbits.scraml.ramlparser.parser.SourceFile /** * Created by peter on 14/01/17. */ case class TraitGenerator(scalaPlay: ScalaPlay) extends SourceGenerator { implicit val platform: ScalaPlay = scalaPlay def generate(generationAggr: GenerationAggr, toInterfaceDefinition: TransferObjectInterfaceDefinition): GenerationAggr = { val toCanonicalName = toInterfaceDefinition.origin.reference.canonicalName val parentNames: List[CanonicalName] = generationAggr.allParents(toCanonicalName) val fields: Seq[Field] = parentNames.foldLeft(toInterfaceDefinition.origin.fields) { (collectedFields, parentName) => val parentDefinition: TransferObjectClassDefinition = generationAggr.toMap.getOrElse(parentName, sys.error(s"Expected to find $parentName in the generation aggregate.")) collectedFields ++ parentDefinition.fields } val traitsToImplement = generationAggr .directParents(toCanonicalName) .foldLeft(Seq.empty[TransferObjectClassDefinition]) { (traitsToImpl, parentName) => val parentDefinition = generationAggr.toMap.getOrElse(parentName, sys.error(s"Expected to find $parentName in the generation aggregate.")) traitsToImpl :+ parentDefinition } .map(TransferObjectInterfaceDefinition(_, toInterfaceDefinition.discriminator)) val implementingNonLeafClassNames = generationAggr.nonLeafChildren(toCanonicalName) + toCanonicalName val implementingLeafClassNames = generationAggr.leafChildren(toCanonicalName) val implementingNonLeafClasses: Set[TransferObjectClassDefinition] = implementingNonLeafClassNames.map(generationAggr.toMap) val implementingLeafClasses: Set[TransferObjectClassDefinition] = implementingLeafClassNames.map(generationAggr.toMap) generateTrait(fields, traitsToImplement, toInterfaceDefinition, implementingNonLeafClasses, implementingLeafClasses, generationAggr) } private def generateTrait(fields: Seq[Field], traitsToImplement: Seq[TransferObjectInterfaceDefinition], toInterfaceDefinition: TransferObjectInterfaceDefinition, implementingNonLeafClasses: Set[TransferObjectClassDefinition], implementingLeafClasses: Set[TransferObjectClassDefinition], generationAggr: GenerationAggr): GenerationAggr = { def childClassRepToWithTypeHintExpression(childClassRep: TransferObjectClassDefinition, isLeaf: Boolean): String = { val discriminatorValue = childClassRep.actualTypeDiscriminatorValue val childClassName = if (isLeaf) childClassRep.reference.name else childClassRep.implementingInterfaceReference.name s"""$childClassName.jsonFormatter.withTypeHint("$discriminatorValue")""" } val imports: Set[String] = platform .importStatements( toInterfaceDefinition.classReference, fields.map(_.classPointer).toSet ++ implementingNonLeafClasses.map(_.implementingInterfaceReference) ++ implementingLeafClasses.map(_.reference) ++ traitsToImplement.map(_.classReference) ) val fieldDefinitions = fields.map(_.fieldDeclaration).map(fieldExpr => s"def $fieldExpr") val typeHintExpressions = implementingNonLeafClasses.map(childClassRepToWithTypeHintExpression(_, isLeaf = false)) ++ implementingLeafClasses.map(childClassRepToWithTypeHintExpression(_, isLeaf = true)) val extendedTraitDefs = traitsToImplement.map(_.classReference.classDefinition) val extendsExpression = if (extendedTraitDefs.nonEmpty) extendedTraitDefs.mkString("extends ", " with ", "") else "" val dslBasePackage = platform.rewrittenDslBasePackage.mkString(".") val source = s""" package ${toInterfaceDefinition.classReference.packageName} import play.api.libs.json._ import $dslBasePackage.json.TypedJson._ ${imports.mkString("\n")} trait ${toInterfaceDefinition.classReference.classDefinition} $extendsExpression { ${fieldDefinitions.mkString("\n\n")} } object ${toInterfaceDefinition.classReference.name} { implicit val jsonFormat: Format[${toInterfaceDefinition.classReference.classDefinition}] = TypeHintFormat( "${toInterfaceDefinition.discriminator}", ${typeHintExpressions.mkString(",\n")} ) } """ val sourceFile = SourceFile( filePath = toInterfaceDefinition.classReference.toFilePath, content = source ) generationAggr.addSourceFile(sourceFile) } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/Sourced.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.parser import play.api.libs.json.{ JsObject, JsString, JsValue } /** * Created by peter on 26/02/16. */ object Sourced { val sourcefield = "_source" /** * Unwraps a JSON object that has a "_source" field into the source value and the original json object. */ def unapply(json: JsValue): Option[(JsValue, String)] = { json match { case jsObj: JsObject => (jsObj \ sourcefield).toOption.collect { case JsString(includeFile) => (jsObj - sourcefield, includeFile) } case _ => None } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/NativeIdResourceBodyLookupTest.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser import io.atomicbits.scraml.ramlparser.lookup.{ CanonicalNameGenerator, CanonicalTypeCollector } import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.model.canonicaltypes._ import io.atomicbits.scraml.ramlparser.parser.RamlParser import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import org.scalatest.featurespec.AnyFeatureSpec import org.scalatest.matchers.should.Matchers._ /** * Created by peter on 5/02/17. */ class NativeIdResourceBodyLookupTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll { Feature("json schema native id lookup test") { Scenario("test json-schema native id lookup") { Given("a RAML 1.0 specification with json-schema types") val defaultBasePath = List("io", "atomicbits", "model") val parser = RamlParser("/json-schema-types/TestApi.raml", "UTF-8") When("we parse the specification") val parsedModel = parser.parse Then("we are able to to a lookup of json-schema types using a native id in the resource definition") val raml = parsedModel.get implicit val canonicalNameGenerator: CanonicalNameGenerator = CanonicalNameGenerator(defaultBasePath) val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator) val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml) val userResource = ramlUpdated.resources.filter(_.urlSegment == "user").head val getBody = userResource.actionMap(Get).responses.responseMap(StatusCode("200")).body val canonicalType: TypeReference = getBody.contentMap(MediaType("application/json")).bodyType.get.canonical.get canonicalType.isInstanceOf[NonPrimitiveTypeReference] shouldBe true val user = canonicalType.asInstanceOf[NonPrimitiveTypeReference] user.refers shouldBe CanonicalName.create("User", List("io", "atomicbits", "model")) } } Feature("json schema with required fields defined outside the properties list of the object") { Scenario("a test json-schema with required fields list defined outside the properties") { Given("A RAML 0.8 specification with a json-schema that has its required fields defined outside the object properties") val defaultBasePath = List("io", "atomicbits", "model") val parser = RamlParser("/json-schema-types/TestApi.raml", "UTF-8") When("we parse the spec") val parsedModel = parser.parse Then("the required fields are marked as required") val raml = parsedModel.get implicit val canonicalNameGenerator: CanonicalNameGenerator = CanonicalNameGenerator(defaultBasePath) val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator) val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml) val userExtReq = canonicalLookup.map(CanonicalName.create("UserExtReq", List("io", "atomicbits", "model"))).asInstanceOf[ObjectType] val idProperty = userExtReq.properties("id").asInstanceOf[Property[StringType.type]] idProperty.required shouldBe true val firstNameProperty = userExtReq.properties("firstName").asInstanceOf[Property[StringType.type]] firstNameProperty.required shouldBe true val lastNameProperty = userExtReq.properties("lastName").asInstanceOf[Property[StringType.type]] lastNameProperty.required shouldBe true val ageProperty = userExtReq.properties("age").asInstanceOf[Property[NumberType.type]] ageProperty.required shouldBe false } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/StatusCodeTest.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser import io.atomicbits.scraml.ramlparser.model.StatusCode import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import org.scalatest.featurespec.AnyFeatureSpec import org.scalatest.matchers.should.Matchers._ /** * Created by peter on 16/03/17. */ class StatusCodeTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll { Feature("Status code test") { Scenario("test the ordering of the status codes") { Given("a set containing status codes") val statusCodes = Set(StatusCode("401"), StatusCode("201"), StatusCode("404")) When("the min value of the set is retrieved") val minStatusCode = statusCodes.min Then("we get the status code with the smallest code") minStatusCode shouldBe StatusCode("201") } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Id.scala
<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Id.scala /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName /** * Created by peter on 25/03/16. */ /** * The base class for all Id's. */ sealed trait Id /** * UniqueId's are Id's that are expected to be unique by value within a RAML document. */ sealed trait UniqueId extends Id trait AbsoluteId extends UniqueId { def id: String def rootPart: RootId def rootPath: List[String] def hostPath: List[String] def fragments: List[String] = List.empty } /** * An absolute id uniquely identifies a schema. A schema with an absolute id is the root for its child-schemas that * don't have an absolute or relative id. * An absolute id is of the form "http://atomicbits.io/schema/User.json" and often it ends with a "#". * * */ case class RootId(hostPath: List[String], path: List[String], name: String) extends AbsoluteId { val anchor: String = s"http://${hostPath.mkString(".")}/${path.mkString("/")}" def toAbsoluteId(id: Id, path: List[String] = List.empty): AbsoluteId = { id match { case absoluteId: RootId => absoluteId case relativeId: RelativeId => RootId(s"$anchor/${relativeId.id}") case fragmentId: FragmentId => AbsoluteFragmentId(this, fragmentId.fragments) case absFragmentId: AbsoluteFragmentId => absFragmentId case ImplicitId => AbsoluteFragmentId(this, path) case nativeId: NativeId => // We should not expect native ids inside a json-schema, but our parser doesn't separate json-schema and RAML 1.0 types, // so we can get fragments that are interpreted as having a native ID. This is OK, but we need to resolve them here // by using the NoId. NoId case absId: AbsoluteId => sys.error("All absolute IDs should be covered already.") case other => sys.error(s"Cannot transform $other to an absolute id.") } } val rootPart: RootId = this val fileName: String = s"$name.json" val rootPath: List[String] = path :+ fileName val id = s"$anchor/$fileName" } object RootId { /** * @param id The string representation of the id */ def apply(id: String): RootId = { val protocolParts = id.split("://") val protocol = protocolParts.head val withoutProtocol = protocolParts.takeRight(1).head val parts = withoutProtocol.split('/').filter(_.nonEmpty) val host = parts.take(1).head val hostPath = host.split('.').toList val name = fileNameToName(parts.takeRight(1).head) val path = parts.drop(1).dropRight(1).toList RootId( hostPath = hostPath, path = path, name = name ) } def fileNameToName(fileNameRep: String): String = { val filenameWithoutHashtags = fileNameRep.split('#').take(1).head val name = filenameWithoutHashtags.split('.').take(1).head name } def fromPackagePath(packagePath: List[String], name: String): RootId = { packagePath match { case p1 :: p2 :: ps => RootId(hostPath = List(p2, p1), path = ps, name = name) case _ => sys.error(s"A package path must contain at least two elements: $packagePath") } } def fromCanonical(canonicalName: CanonicalName): RootId = { val domain = canonicalName.packagePath.take(2).reverse.mkString(".") val path = canonicalName.packagePath.drop(2) match { case Nil => "/" case somePath => somePath.mkString("/", "/", "/") } RootId(s"http://$domain$path${canonicalName.name}.json") } } /** * A relative id identifies its schema uniquely when expanded with the anchor of its root schema. Its root schema * is its nearest parent that has an absolute id. A schema with a relative id is the root for its child-schemas that * don't have an absolute or relative id. * A relative id is of the form "contact/ShippingAddress.json". * * @param id The string representation of the id */ case class RelativeId(id: String) extends Id { val name: String = RootId.fileNameToName(id.split('/').filter(_.nonEmpty).takeRight(1).head) val path: List[String] = id.split('/').filter(_.nonEmpty).dropRight(1).toList } /** * A native id is like a relative id, but it is not expected to have an absolute parent id. NativeId's should not be used in * json-schema definitions. They have been added to cope with the native RAML 1.0 types that either have an NativeId or an ImplicitId. * * We cannot use the RootId concept here, because a NativeID has a free format whereas the RootId is a json-schema concept that * has to meet strict formatting rules. */ case class NativeId(id: String) extends UniqueId /** * A fragment id identifies its schema uniquely by the schema path (JSON path in the original JSON representation) * from its nearest root schema towards itself. In other words, the fragment id should always match this schema * path and is redundant from that point of view. * It is of the form "#/some/schema/path/license" * * @param fragments The path that composes the fragment id. */ case class FragmentId(fragments: List[String]) extends Id { def id: String = s"#/${fragments.mkString("/")}" } /** * This is the absolute version of a fragment id. It is prepended with its root's achor. * E.g. "http://atomicbits.io/schema/User.json#/some/schema/path/license" * * @param root The root of this absolute fragment id. * @param fragments The path that composes the fragment id. */ case class AbsoluteFragmentId(root: RootId, override val fragments: List[String]) extends AbsoluteId { def id: String = s"${root.id}#/${fragments.mkString("/")}" val rootPart: RootId = root val rootPath = root.rootPath val hostPath = root.hostPath } /** * An implicit id marks the absense of an id. It implies that the schema should be uniquely identified by the schema * path (JSON path in the original JSON representation) from its nearest root schema towards itself. In other words, * an implicit id is a fragment id that hasn't been set. * * It is not a UniqueId since may items can have ImplicitId's. */ case object ImplicitId extends Id /** * Placeholder object for an ID that points to nowhere. */ case object NoId extends AbsoluteId { override def id: String = "http://no.where" override def rootPart: RootId = RootId(id) override def rootPath: List[String] = rootPart.rootPath override def hostPath: List[String] = List("no", "where") }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/htmldoc/simplifiedmodel/SimpleAction.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.htmldoc.simplifiedmodel import io.atomicbits.scraml.generator.codegen.GenerationAggr import io.atomicbits.scraml.ramlparser.model._ /** * Created by peter on 6/06/18. */ case class SimpleAction(actionType: Method, headers: List[SimpleParameter], queryParameters: List[SimpleParameter], body: SimpleBody, responses: List[SimpleResponse], queryString: Option[QueryString] = None, description: Option[String] = None) object SimpleAction { def apply(action: Action, generationAggr: GenerationAggr): SimpleAction = { SimpleAction( actionType = action.actionType, headers = action.headers.values.map(SimpleParameter(_, generationAggr)), queryParameters = action.queryParameters.values.map(SimpleParameter(_, generationAggr)), body = SimpleBody(action.body, generationAggr), responses = action.responses.values.map(res => SimpleResponse(res, generationAggr)), queryString = action.queryString, description = action.description ) } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/typescript/InterfaceGenerator.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.typescript import io.atomicbits.scraml.generator.codegen.GenerationAggr import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform, SourceGenerator } import io.atomicbits.scraml.generator.typemodel.{ Field, TransferObjectClassDefinition, TransferObjectInterfaceDefinition } import Platform._ import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName import io.atomicbits.scraml.ramlparser.parser.SourceFile /** * Created by peter on 15/12/17. */ case class InterfaceGenerator(typeScript: TypeScript) extends SourceGenerator { implicit val platform: TypeScript = typeScript def generate(generationAggr: GenerationAggr, toInterfaceDefinition: TransferObjectInterfaceDefinition): GenerationAggr = { val classReference = toInterfaceDefinition.classReference val extendsInterfaces: String = { val parentClassDefs = toInterfaceDefinition.origin.parents.map(_.classDefinition) parentClassDefs match { case Nil => "" case nonEmptyList => s"extends ${nonEmptyList.mkString(", ")}" } } val originalToCanonicalName = toInterfaceDefinition.origin.reference.canonicalName def childTypeDiscriminatorValues: List[String] = { val childNames: List[CanonicalName] = generationAggr.allChildren(originalToCanonicalName) childNames.map { childName => val childDefinition: TransferObjectClassDefinition = generationAggr.toMap.getOrElse(childName, sys.error(s"Expected to find $childName in the generation aggregate.")) childDefinition.actualTypeDiscriminatorValue } } val (typeDiscriminatorFieldDefinition, fields): (Seq[String], List[Field]) = { if (generationAggr.isInHierarchy(originalToCanonicalName)) { val typeDiscriminator = toInterfaceDefinition.discriminator val typeDiscriminatorValue = toInterfaceDefinition.origin.actualTypeDiscriminatorValue val allTypeDiscriminatorValues = typeDiscriminatorValue :: childTypeDiscriminatorValues val typeDiscriminatorUnionString = allTypeDiscriminatorValues.map(CleanNameTools.quoteString).mkString(" | ") val typeDiscFieldDef = Seq(s"${CleanNameTools.quoteString(typeDiscriminator)}: $typeDiscriminatorUnionString,") val fields = toInterfaceDefinition.fields.collect { case field if field.fieldName != typeDiscriminator => field } (typeDiscFieldDef, fields) } else { (Seq.empty, toInterfaceDefinition.fields) } } val fieldDefinitions: Seq[String] = fields.map(_.fieldDeclaration) val source = s""" |export interface ${classReference.classDefinition} $extendsInterfaces { | ${(fieldDefinitions ++ typeDiscriminatorFieldDefinition).mkString(",\n ")} |} """.stripMargin val sourceFile = SourceFile( filePath = classReference.toFilePath, content = source ) generationAggr.addSourceFile(sourceFile) } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/CanonicalType.scala
<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/CanonicalType.scala /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.canonicaltypes /** * Created by peter on 9/12/16. */ trait CanonicalType { def canonicalName: CanonicalName // def typeReference: TypeReference } /** * A primitive type is interpreted in the broad sense of all types that are not customly made by the user in the RAML model. * These are all types that are not an Object or an Enum. * * A primitive type is also its own type reference since it has no user-defined properties that can be configured in the RAML model. */ trait PrimitiveType extends CanonicalType with TypeReference { def genericTypes: List[TypeReference] = List.empty def genericTypeParameters: List[TypeParameter] = List.empty } /** * Nonprimitive types are the custom types created by the RAML model that will need to be generated as 'new' types. */ trait NonPrimitiveType extends CanonicalType
atomicbits/scramlgen
modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/JsonSchemaParseTest.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser import io.atomicbits.scraml.ramlparser.model.parsedtypes._ import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.parser.RamlParser import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import org.scalatest.featurespec.AnyFeatureSpec import org.scalatest.matchers.should.Matchers._ import scala.language.postfixOps import scala.util.Try /** * Created by peter on 6/02/16. */ class JsonSchemaParseTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll { Feature("json schema parsing") { Scenario("test parsing fragments in json-schema") { Given("a json-schema containing fragments") val parser = RamlParser("/fragments/TestFragmentsApi.raml", "UTF-8") When("we parse the specification") val parsedModel: Try[Raml] = parser.parse Then("we get a properly parsed fragments object") val raml = parsedModel.get val objectWithFragments: ParsedObject = raml.types.typeReferences(NativeId("myfragments")).asInstanceOf[ParsedObject] val barType: ParsedType = objectWithFragments.fragments.fragmentMap("bar") barType shouldBe a[ParsedTypeReference] barType.asInstanceOf[ParsedTypeReference].refersTo shouldBe NativeId("baz") val definitionFragment: Fragments = objectWithFragments.fragments.fragmentMap("definitions").asInstanceOf[Fragments] val addressType = definitionFragment.fragmentMap("address") addressType shouldBe a[ParsedObject] val address = addressType.asInstanceOf[ParsedObject] address.id shouldBe FragmentId(List("definitions", "address")) address.properties("city").propertyType.parsed shouldBe a[ParsedString] address.properties("state").propertyType.parsed shouldBe a[ParsedString] address.properties("zip").propertyType.parsed shouldBe a[ParsedInteger] address.properties("streetAddress").propertyType.parsed shouldBe a[ParsedString] // val prettyModel = TestUtils.prettyPrint(parsedModel) // println(s"Parsed raml: $prettyModel") } Scenario("test collecting of all types in a complex json-schema type declaration with RAML 1.0 type declarations") { Given("a RAML specification containing complex json-schema definitions and RAML 1.0 type definitions") val defaultBasePath = List("io", "atomicbits", "schemas") val parser = RamlParser("/raml08/TestApi.raml", "UTF-8") When("we parse the specification") val parsedModel: Try[Raml] = parser.parse Then("we get all four actions in the userid resource") val raml = parsedModel.get val userObject = raml.types.typeReferences(NativeId("user")).asInstanceOf[ParsedObject] val addressParsedProperty: ParsedProperty = userObject.properties.valueMap("address") addressParsedProperty.required shouldBe false } } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/ScalaPlay.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.scalaplay import java.nio.file.{ Path, Paths } import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform } import io.atomicbits.scraml.generator.typemodel._ import Platform._ import io.atomicbits.scraml.generator.codegen.GenerationAggr /** * Created by peter on 10/01/17. */ case class ScalaPlay(apiBasePackageParts: List[String]) extends Platform with CleanNameTools { val name: String = "Scala Play" implicit val platform: ScalaPlay = this val dslBasePackageParts: List[String] = List("io", "atomicbits", "scraml", "dsl", "scalaplay") val rewrittenDslBasePackage: List[String] = apiBasePackageParts ++ List("dsl", "scalaplay") override def classPointerToNativeClassReference(classPointer: ClassPointer): ClassReference = { classPointer match { case classReference: ClassReference => classReference case ArrayClassPointer(arrayType) => val typeParameter = TypeParameter("T") ClassReference(name = "Array", typeParameters = List(typeParameter), typeParamValues = List(arrayType), predef = true) case StringClassPointer => ClassReference(name = "String", packageParts = List("java", "lang"), predef = true) case ByteClassPointer => ClassReference(name = "Byte", packageParts = List("scala"), predef = true) case BinaryDataClassPointer => ClassReference(name = "BinaryData", packageParts = rewrittenDslBasePackage, library = true) case FileClassPointer => ClassReference(name = "File", packageParts = List("java", "io"), library = true) case InputStreamClassPointer => ClassReference(name = "InputStream", packageParts = List("java", "io"), library = true) case JsObjectClassPointer => ClassReference(name = "JsObject", packageParts = List("play", "api", "libs", "json"), library = true) case JsValueClassPointer => ClassReference(name = "JsValue", packageParts = List("play", "api", "libs", "json"), library = true) case BodyPartClassPointer => ClassReference(name = "BodyPart", packageParts = rewrittenDslBasePackage, library = true) case LongClassPointer(primitive) => ClassReference(name = "Long", packageParts = List("java", "lang"), predef = true) case DoubleClassPointer(primitive) => ClassReference(name = "Double", packageParts = List("java", "lang"), predef = true) case BooleanClassPointer(primitive) => ClassReference(name = "Boolean", packageParts = List("java", "lang"), predef = true) case DateTimeRFC3339ClassPointer => ClassReference(name = "DateTimeRFC3339", packageParts = rewrittenDslBasePackage, library = true) case DateTimeRFC2616ClassPointer => ClassReference(name = "DateTimeRFC2616", packageParts = rewrittenDslBasePackage, library = true) case DateTimeOnlyClassPointer => ClassReference(name = "DateTimeOnly", packageParts = rewrittenDslBasePackage, library = true) case TimeOnlyClassPointer => ClassReference(name = "TimeOnly", packageParts = rewrittenDslBasePackage, library = true) case DateOnlyClassPointer => ClassReference(name = "DateOnly", packageParts = rewrittenDslBasePackage, library = true) case ListClassPointer(typeParamValue) => val typeParameter = TypeParameter("T") val typeParamValues = List(typeParamValue) ClassReference(name = "List", typeParameters = List(typeParameter), typeParamValues = typeParamValues, predef = true) case typeParameter: TypeParameter => ClassReference(name = typeParameter.name, predef = true, isTypeParameter = true) case _: io.atomicbits.scraml.generator.typemodel.PrimitiveClassPointer => ??? } } override def implementingInterfaceReference(classReference: ClassReference): ClassReference = ClassReference( name = s"${classReference.name}Impl", packageParts = classReference.packageParts ) override def classDefinition(classPointer: ClassPointer, fullyQualified: Boolean = false): String = { val classReference = classPointer.native val classDef = (classReference.typeParameters, classReference.typeParamValues) match { case (Nil, _) => classReference.name case (tps, Nil) => val typeParameterNames = tps.map(_.name) s"${classReference.name}[${typeParameterNames.mkString(",")}]" case (tps, tpvs) if tps.size == tpvs.size => val typeParameterValueClassDefinitions = tpvs.map { classPointer => if (fullyQualified) classPointer.native.fullyQualifiedClassDefinition else classPointer.native.classDefinition } s"${classReference.name}[${typeParameterValueClassDefinitions.mkString(",")}]" case (tps, tpvs) => val message = s""" |The following class definition has a different number of type parameter |values than there are type parameters: |$classPointer """.stripMargin sys.error(message) } if (fullyQualified) { val parts = safePackageParts(classPointer) :+ classDef parts.mkString(".") } else { classDef } } override def className(classPointer: ClassPointer): String = classPointer.native.name override def packageName(classPointer: ClassPointer): String = safePackageParts(classPointer).mkString(".") override def fullyQualifiedName(classPointer: ClassPointer): String = { val parts: List[String] = safePackageParts(classPointer) :+ className(classPointer) parts.mkString(".") } override def safePackageParts(classPointer: ClassPointer): List[String] = classPointer.native.packageParts.map(escapeScalaKeyword(_, "esc")) override def safeFieldName(fieldName: String): String = { val cleanName = cleanFieldName(fieldName) escapeScalaKeyword(cleanName) } override def safeDeconstructionName(fieldName: String): String = { val cleanName = cleanFieldName(fieldName) if (reservedKeywords.contains(cleanName)) s"${cleanName}_" else cleanName } override def fieldDeclarationWithDefaultValue(field: Field): String = { if (field.required) { s"${safeFieldName(field)}: ${classDefinition(field.classPointer)}" } else { s"${safeFieldName(field)}: Option[${classDefinition(field.classPointer)}] = None" } } override def fieldDeclaration(field: Field): String = { if (field.required) s"${safeFieldName(field)}: ${classDefinition(field.classPointer)}" else s"${safeFieldName(field)}: Option[${classDefinition(field.classPointer)}]" } // format: off def fieldFormatUnlift(field: Field, recursiveFields: Set[Field]): String = (field.required, recursiveFields.contains(field)) match { case (true, false) => s""" (__ \\ "${field.fieldName}").format[${classDefinition(field.classPointer)}]""" case (true, true) => s""" (__ \\ "${field.fieldName}").lazyFormat[${classDefinition(field.classPointer)}](Format.of[${classDefinition(field.classPointer)}])""" case (false, false) => s""" (__ \\ "${field.fieldName}").formatNullable[${classDefinition(field.classPointer)}]""" case (false, true) => s""" (__ \\ "${field.fieldName}").lazyFormatNullable[${classDefinition(field.classPointer)}](Format.of[${classDefinition(field.classPointer)}])""" } // format: on override def importStatements(targetClassReference: ClassPointer, dependencies: Set[ClassPointer] = Set.empty): Set[String] = { val ownPackage = targetClassReference.packageName def collectTypeImports(collected: Set[String], classPtr: ClassPointer): Set[String] = { def importFromClassReference(classRef: ClassReference): Option[String] = { if (classRef.packageName != ownPackage && !classRef.predef) Some(s"import ${classRef.fullyQualifiedName}") else None } val classReference = classPtr.native val collectedWithClassRef = importFromClassReference(classReference).map(classRefImport => collected + classRefImport).getOrElse(collected) classReference.typeParamValues.foldLeft(collectedWithClassRef)(collectTypeImports) } val targetClassImports: Set[String] = collectTypeImports(Set.empty, targetClassReference) val dependencyImports: Set[String] = dependencies.foldLeft(targetClassImports)(collectTypeImports) dependencyImports } override def toSourceFile(generationAggr: GenerationAggr, toClassDefinition: TransferObjectClassDefinition): GenerationAggr = CaseClassGenerator(this).generate(generationAggr, toClassDefinition) override def toSourceFile(generationAggr: GenerationAggr, toInterfaceDefinition: TransferObjectInterfaceDefinition): GenerationAggr = TraitGenerator(this).generate(generationAggr, toInterfaceDefinition) override def toSourceFile(generationAggr: GenerationAggr, enumDefinition: EnumDefinition): GenerationAggr = EnumGenerator(this).generate(generationAggr, enumDefinition) override def toSourceFile(generationAggr: GenerationAggr, clientClassDefinition: ClientClassDefinition): GenerationAggr = ClientClassGenerator(this).generate(generationAggr, clientClassDefinition) override def toSourceFile(generationAggr: GenerationAggr, resourceClassDefinition: ResourceClassDefinition): GenerationAggr = ResourceClassGenerator(this).generate(generationAggr, resourceClassDefinition) override def toSourceFile(generationAggr: GenerationAggr, headerSegmentClassDefinition: HeaderSegmentClassDefinition): GenerationAggr = HeaderSegmentClassGenerator(this).generate(generationAggr, headerSegmentClassDefinition) override def toSourceFile(generationAggr: GenerationAggr, unionClassDefinition: UnionClassDefinition): GenerationAggr = UnionClassGenerator(this).generate(generationAggr, unionClassDefinition) override val classFileExtension: String = "scala" override def toFilePath(classPointer: ClassPointer): Path = { classPointer match { case classReference: ClassReference => val parts = classReference.safePackageParts :+ s"${classReference.name}.$classFileExtension" Paths.get("", parts: _*) // This results in a relative path both on Windows as on Linux/Mac case _ => sys.error(s"Cannot create a file path from a class pointer that is not a class reference!") } } val reservedKeywords = Set( "Byte", "Short", "Char", "Int", "Long", "Float", "Double", "Boolean", "Unit", "String", "abstract", "case", "catch", "class", "def", "do", "else", "extends", "false", "final", "finally", "for", "forSome", "if", "implicit", "import", "lazy", "match", "new", "null", "object", "override", "package", "private", "protected", "return", "sealed", "super", "this", "throw", "trait", "try", "true", "type", "val", "var", "while", "with", "yield" ) def escapeScalaKeyword(someName: String, escape: String = "$"): String = reservedKeywords.foldLeft(someName) { (name, resWord) => if (name == resWord) s"`$name`" else name } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/InlineTypeDeclaration.scala
<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/InlineTypeDeclaration.scala /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.parsedtypes import io.atomicbits.scraml.ramlparser.parser.ParseContext import play.api.libs.json.JsValue import scala.util.Try /** * Created by peter on 1/09/16. */ object InlineTypeDeclaration { /** * An inline type declaration is of the form: * * . /activate: * . put: * . body: * . application/vnd-v1.0+json: * . schema: | * . { * . "type": "array", * . "items": { * . "$ref": "user.json" * . } * . } * * Here, the 'schema' (or 'type') field does not refer to the type but to an object that defines the type. * */ def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[ParsedType]] = { ParsedType.typeDeclaration(json) match { case Some(ParsedType(tryType)) => Some(tryType) case _ => None } } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/htmldoc/simplifiedmodel/ClientDocModel.scala
<reponame>atomicbits/scramlgen /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.htmldoc.simplifiedmodel import io.atomicbits.scraml.generator.codegen.GenerationAggr import io.atomicbits.scraml.generator.typemodel.ClientClassDefinition /** * Created by peter on 4/06/18. */ case class ClientDocModel(apiName: String, baseUri: Option[String], combinedResources: List[CombinedResource], title: String, version: String, description: String) object ClientDocModel { def apply(clientClassDefinition: ClientClassDefinition, generationAggr: GenerationAggr): ClientDocModel = { ClientDocModel( apiName = clientClassDefinition.apiName, baseUri = clientClassDefinition.baseUri, combinedResources = clientClassDefinition.topLevelResourceDefinitions.flatMap(rd => CombinedResource(rd, generationAggr)), title = clientClassDefinition.title, version = clientClassDefinition.version, description = clientClassDefinition.description ) } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedString.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.parsedtypes import io.atomicbits.scraml.ramlparser.model._ import play.api.libs.json.{ JsObject, JsString, JsValue, Json } import scala.util.{ Success, Try } import io.atomicbits.scraml.ramlparser.parser.JsUtils._ /** * Created by peter on 1/04/16. */ case class ParsedString(id: Id = ImplicitId, format: Option[String] = None, pattern: Option[String] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None, required: Option[Boolean] = None, model: TypeModel = RamlModel) extends PrimitiveType with AllowedAsObjectField { override def updated(updatedId: Id): ParsedString = copy(id = updatedId) override def asTypeModel(typeModel: TypeModel): ParsedType = copy(model = typeModel) } object ParsedString { val value = "string" def apply(json: JsValue): Try[ParsedString] = { val model: TypeModel = TypeModel(json) val id = JsonSchemaIdExtractor(json) Success( ParsedString( id = id, format = json.fieldStringValue("pattern"), pattern = json.fieldStringValue("format"), minLength = json.fieldIntValue("minLength"), maxLength = json.fieldIntValue("maxLength"), required = json.fieldBooleanValue("required"), model = model ) ) } def unapply(json: JsValue): Option[Try[ParsedString]] = { (ParsedType.typeDeclaration(json), (json \ ParsedEnum.value).toOption, json) match { case (Some(JsString(ParsedString.value)), None, _) => Some(ParsedString(json)) case (_, _, JsString(ParsedString.value)) => Some(Success(ParsedString())) case _ => None } } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/ResourceClassGenerator.scala
<reponame>atomicbits/scramlgen<filename>modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/ResourceClassGenerator.scala /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.scalaplay import io.atomicbits.scraml.generator.codegen.{ ActionGenerator, DslSourceRewriter, GenerationAggr, SourceCodeFragment } import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform, SourceGenerator } import io.atomicbits.scraml.generator.typemodel.ResourceClassDefinition import io.atomicbits.scraml.generator.platform.Platform._ import io.atomicbits.scraml.ramlparser.parser.SourceFile /** * Created by peter on 14/01/17. */ case class ResourceClassGenerator(scalaPlay: ScalaPlay) extends SourceGenerator { implicit val platform: ScalaPlay = scalaPlay def generate(generationAggr: GenerationAggr, resourceClassDefinition: ResourceClassDefinition): GenerationAggr = { val classDefinition = generateClassDefinition(resourceClassDefinition) val resourceClassReference = resourceClassDefinition.classReference val dslFields = resourceClassDefinition.childResourceDefinitions.map(generateResourceDslField) val SourceCodeFragment(actionImports, actionFunctions, headerPathSourceDefs) = ActionGenerator(ScalaActionCodeGenerator(platform)).generateActionFunctions(resourceClassDefinition) val imports = platform.importStatements(resourceClassReference, actionImports) val addHeaderConstructorArgs = generateAddHeaderConstructorArguments(resourceClassDefinition) val setHeaderConstructorArgs = generateSetHeaderConstructorArguments(resourceClassDefinition) val dslBasePackage = platform.rewrittenDslBasePackage.mkString(".") val sourcecode = s""" package ${resourceClassReference.packageName} import $dslBasePackage._ import play.api.libs.json._ import java.io._ ${imports.mkString("\n")} $classDefinition /** * addHeaders will add the given headers and append the values for existing headers. */ def addHeaders(newHeaders: (String, String)*) = new ${resourceClassReference.name}$addHeaderConstructorArgs /** * setHeaders will add the given headers and set (overwrite) the values for existing headers. */ def setHeaders(newHeaders: (String, String)*) = new ${resourceClassReference.name}$setHeaderConstructorArgs ${dslFields.mkString("\n\n")} ${actionFunctions.mkString("\n\n")} } """ generationAggr .addSourceDefinitions(resourceClassDefinition.childResourceDefinitions) .addSourceDefinitions(headerPathSourceDefs) .addSourceFile(SourceFile(filePath = resourceClassReference.toFilePath, content = sourcecode)) } def generateClassDefinition(resourceClassDefinition: ResourceClassDefinition): String = { val resource = resourceClassDefinition.resource val resourceClassRef = resourceClassDefinition.classReference resourceClassDefinition.urlParamClassPointer().map(_.native) match { case Some(urlParamClassReference) => val urlParamClassName = urlParamClassReference.name s"""class ${resourceClassRef.name}(_value: $urlParamClassName, _req: RequestBuilder) extends ParamSegment[$urlParamClassName](_value, _req) { """ case None => s"""class ${resourceClassRef.name}(private val _req: RequestBuilder) extends PlainSegment("${resource.urlSegment}", _req) { """ } } def generateResourceDslField(resourceClassDefinition: ResourceClassDefinition): String = { val resource = resourceClassDefinition.resource val cleanUrlSegment = platform.escapeScalaKeyword(CleanNameTools.cleanMethodName(resource.urlSegment)) val resourceClassRef = resourceClassDefinition.classReference resourceClassDefinition.urlParamClassPointer().map(_.native) match { case Some(urlParamClassReference) => val urlParamClassName = urlParamClassReference.name s"""def $cleanUrlSegment(value: $urlParamClassName) = new ${resourceClassRef.fullyQualifiedName}(value, _requestBuilder.withAddedPathSegment(value))""" case None => s"""def $cleanUrlSegment = new ${resourceClassRef.fullyQualifiedName}(_requestBuilder.withAddedPathSegment("${resource.urlSegment}"))""" } } def generateAddHeaderConstructorArguments(resourceClassDefinition: ResourceClassDefinition): String = resourceClassDefinition.urlParamClassPointer() match { case Some(parameter) => "(_value, _requestBuilder.withAddedHeaders(newHeaders: _*))" case None => "(_requestBuilder.withAddedHeaders(newHeaders: _*))" } def generateSetHeaderConstructorArguments(resourceClassDefinition: ResourceClassDefinition): String = resourceClassDefinition.urlParamClassPointer() match { case Some(parameter) => "(_value, _requestBuilder.withSetHeaders(newHeaders: _*))" case None => "(_requestBuilder.withSetHeaders(newHeaders: _*))" } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/SourceFile.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.parser import java.nio.file.Path import play.api.libs.json.JsValue /** * Created by peter on 14/01/17. */ trait FileContent[T] { def filePath: Path def content: T } case class SourceFile(filePath: Path, content: String) extends FileContent[String] case class JsonFile(filePath: Path, content: JsValue) extends FileContent[JsValue]
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/ScramlGenerator.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator import io.atomicbits.scraml.generator.formatting.{ JavaFormatter, ScalaFormatter } import scala.collection.JavaConverters._ import scala.language.postfixOps import java.util.{ Map => JMap } import io.atomicbits.scraml.generator.license.{ LicenseData, LicenseVerifier } import io.atomicbits.scraml.generator.platform.Platform import io.atomicbits.scraml.ramlparser.model.Raml import io.atomicbits.scraml.ramlparser.parser.{ RamlParseException, RamlParser, SourceFile } import scala.util.{ Failure, Success, Try } import io.atomicbits.scraml.generator.platform.Platform._ import io.atomicbits.scraml.generator.platform.javajackson.JavaJackson import io.atomicbits.scraml.generator.platform.scalaplay.ScalaPlay import io.atomicbits.scraml.generator.codegen.{ DslSourceExtractor, DslSourceRewriter, GenerationAggr } import io.atomicbits.scraml.generator.platform.androidjavajackson.AndroidJavaJackson import io.atomicbits.scraml.generator.platform.htmldoc.HtmlDoc import io.atomicbits.scraml.generator.platform.typescript.TypeScript /** * The main Scraml generator class. * This class is thread-safe and may be used by mutiple threads simultaneously. */ object ScramlGenerator { val JAVA_JACKSON: String = "JavaJackson".toLowerCase val SCALA_PLAY: String = "ScalaPlay".toLowerCase val ANDROID_JAVA_JACKSON: String = "AndroidJavaJackson".toLowerCase val TYPESCRIPT: String = "TypeScript".toLowerCase val HTML_DOC: String = "HtmlDoc".toLowerCase val OSX_SWIFT: String = "OsxSwift".toLowerCase val PYTHON: String = "Python".toLowerCase val CSHARP: String = "C#".toLowerCase /** * This is (and must be) a Java-friendly interface! */ def generateScramlCode(platform: String, ramlApiPath: String, apiPackageName: String, apiClassName: String, licenseKey: String, thirdPartyClassHeader: String, singleTargeSourceFileName: String): JMap[String, String] = platform.toLowerCase match { case JAVA_JACKSON => generateFor( JavaJackson(packageNameToPackagParts(apiPackageName)), ramlApiPath, apiClassName, thirdPartyClassHeader, singleTargeSourceFileName ) case SCALA_PLAY => generateFor( ScalaPlay(packageNameToPackagParts(apiPackageName)), ramlApiPath, apiClassName, thirdPartyClassHeader, singleTargeSourceFileName ) case ANDROID_JAVA_JACKSON => generateFor( AndroidJavaJackson(packageNameToPackagParts(apiPackageName)), ramlApiPath, apiClassName, thirdPartyClassHeader, singleTargeSourceFileName ) case TYPESCRIPT => { generateFor( TypeScript(), ramlApiPath, apiClassName, thirdPartyClassHeader, singleTargeSourceFileName ) } case HTML_DOC => { generateFor( HtmlDoc, ramlApiPath, apiClassName, thirdPartyClassHeader, singleTargeSourceFileName ) } case OSX_SWIFT => sys.error(s"There is no iOS support yet.") case PYTHON => sys.error(s"There is no Python support yet.") case CSHARP => sys.error(s"There is no C# support yet.") case unknown => sys.error(s"Unknown platform: $unknown") } private[generator] def generateFor(platform: Platform, ramlApiPath: String, apiClassName: String, thirdPartyClassHeader: String, singleTargeSourceFileName: String): JMap[String, String] = { println(s"Generating client for platform ${platform.name}.") implicit val thePlatform = platform // We transform the scramlLicenseKey and thirdPartyClassHeader fields to optionals here. We don't take them as optional parameters // higher up the chain to maintain a Java-compatible interface for the ScramlGenerator. val classHeader: Option[String] = if (thirdPartyClassHeader == null || thirdPartyClassHeader.isEmpty) None else Some(thirdPartyClassHeader) val licenseHeader: String = deferLicenseHeader(classHeader) val generationAggregator = buildGenerationAggr(ramlApiPath, apiClassName, platform) val sources: Seq[SourceFile] = generationAggregator.generate.sourceFilesGenerated val dslSources: Set[SourceFile] = DslSourceExtractor .extract() .map(DslSourceRewriter.rewrite) val singleSourceFile = Option(singleTargeSourceFileName).collect { case name if name.nonEmpty => name } val combinedSources = platform.mapSourceFiles((sources ++ dslSources).toSet, singleSourceFile) val tupleList = combinedSources .map(addLicenseAndFormat(_, platform, licenseHeader)) .map(sourceFile => (sourceFile.filePath.toString, sourceFile.content)) mapAsJavaMap[String, String](tupleList.toMap) } def packageNameToPackagParts(packageName: String): List[String] = packageName.split('.').toList.filter(!_.isEmpty) private[generator] def buildGenerationAggr(ramlApiPath: String, apiClassName: String, thePlatform: Platform): GenerationAggr = { val charsetName = "UTF-8" // ToDo: Get the charset as input parameter. // Generate the RAML model println("Running RAML model generation") val tryRaml: Try[Raml] = RamlParser(ramlApiPath, charsetName).parse val raml = tryRaml match { case Success(rml) => rml case Failure(rpe: RamlParseException) => sys.error(s""" |- - - Invalid RAML model: - - - |${rpe.messages.mkString("\n")} |- - - - - - - - - - - - - - - - """.stripMargin) case Failure(e) => sys.error(s""" |- - - Unexpected parse error: - - - |${e.printStackTrace()} |- - - - - - - - - - - - - - - - - - """.stripMargin) } println(s"RAML model generated") // We need an implicit reference to the language we're generating the DSL for. implicit val lang = language implicit val platform = thePlatform val host = thePlatform.apiBasePackageParts.take(2).reverse.mkString(".") val urlPath = thePlatform.apiBasePackageParts.drop(2).mkString("/") val defaultBasePath: List[String] = thePlatform.apiBasePackageParts val (ramlExp, canonicalLookup) = raml.collectCanonicals(defaultBasePath) // new version val generationAggregator: GenerationAggr = GenerationAggr(apiName = apiClassName, apiBasePackage = thePlatform.apiBasePackageParts, raml = ramlExp, canonicalToMap = canonicalLookup.map) generationAggregator } private def addLicenseAndFormat(sourceFile: SourceFile, platform: Platform, licenseHeader: String): SourceFile = { val content = s"$licenseHeader\n${sourceFile.content}" val formattedContent = platform match { case ScalaPlay(_) => Try(ScalaFormatter.format(content)).getOrElse(content) case JavaJackson(_) => Try(JavaFormatter.format(content)).getOrElse(content) case AndroidJavaJackson(_) => Try(JavaFormatter.format(content)).getOrElse(content) case _ => content } sourceFile.copy(content = formattedContent) } private def deferLicenseHeader(thirdPartyLicenseHeader: Option[String], commentPrefix: String = " * ", headerPrefix: String = "/**\n", headerSuffix: String = "\n */"): String = { thirdPartyLicenseHeader.map { licenseHeader => licenseHeader.split('\n').map(line => s"$commentPrefix${line.trim}").mkString(headerPrefix, "\n", headerSuffix) } getOrElse "" } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/codegen/DslSourceRewriter.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.codegen import java.nio.file.{ FileSystems, Path, Paths } import java.util.regex.Pattern import io.atomicbits.scraml.generator.platform.Platform import io.atomicbits.scraml.ramlparser.parser.SourceFile /** * Created by peter on 18/04/17. */ object DslSourceRewriter { /** * * put the DSL support codebase under * basepackage.dsl.javajackson.* * basepackage.dsl.scalaplay.* * * @param dslSource * @param platform * @return */ def rewrite(dslSource: SourceFile)(implicit platform: Platform): SourceFile = { val fromPackage: String = platform.dslBasePackage val toPackageParts: List[String] = platform.rewrittenDslBasePackage val toPackage: String = toPackageParts.mkString(".") val rewritten: String = dslSource.content.replaceAll(Pattern.quote(fromPackage), toPackage) /** * Paths.get("", ...) makes a relative path under Linux/Mac (starts without slash) and Windows (starts with a single backslash '\') * * makeAbsolute(paths.get("", ...)) makes the path absolute under Linux/Mac (starts with a slash) and on Windows it remains with a * single slash * * Paths.get(FileSystems.getDefault.getSeparator, ...) makes an absolute path under Linux/Mac (start with a slash), and makes an * UNC path under Windows (start with two backslashes '\\'). Mind that a Windows path that starts with a single backslash is not * compatible with a path that starts with double backslashes. The function 'relativize' cannot be applied to incompatible * path types. * * ! ALWAYS TEST SCRAML THOUROUGHLY ON LINUX/MAC/WINDOWS WHEN CHANGING FILESYSTEM RELATED CODE LIKE THIS ! */ val dslBasePath: Path = makeAbsoluteOnLinuxMacKeepRelativeOnWindows(Paths.get("", platform.dslBasePackageParts: _*)) // dslSource.filePath is an absolute path on Linux/Mac, a directory relative path on Windows val relativeFilePath: Path = dslBasePath.relativize(dslSource.filePath) val toPath: Path = Paths.get(toPackageParts.head, toPackageParts.tail: _*) val newFilePath: Path = toPath.resolve(relativeFilePath) dslSource.copy(filePath = newFilePath, content = rewritten) } def makeAbsoluteOnLinuxMacKeepRelativeOnWindows(path: Path): Path = { if (path.isAbsolute) path else { // Beware! The code below will make an absolute path from a relative path on Linux/Mac. It will keep a directory relative path // on windows as a directory relative path (that starts with a single backslash '\'). It may be confusing. Paths.get(FileSystems.getDefault.getSeparator).resolve(path) } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/TypeModel.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model import play.api.libs.json.{ JsObject, JsString, JsValue } /** * Created by peter on 26/09/16. */ sealed trait TypeModel { def mark(json: JsValue): JsValue } case object RamlModel extends TypeModel { def mark(json: JsValue): JsValue = json } case object JsonSchemaModel extends TypeModel { val markerField = "$schema" val markerValue = "http://json-schema.org/draft-04/schema" def mark(json: JsValue): JsValue = json match { case jsObj: JsObject => jsObj + (markerField -> JsString(markerValue)) case other => other } } object TypeModel { def apply(json: JsValue): TypeModel = { (json \ "$schema").toOption.collect { case JsString(schema) if schema.contains("http://json-schema.org") => JsonSchemaModel } getOrElse RamlModel } }
atomicbits/scramlgen
modules/scraml-generator/src/test/scala/io/atomicbits/scraml/generator/MultipleAcceptHeadersTest.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator import io.atomicbits.scraml.generator.codegen.GenerationAggr import io.atomicbits.scraml.generator.platform.scalaplay.ScalaPlay import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import org.scalatest.concurrent.ScalaFutures import io.atomicbits.scraml.ramlparser.model.Raml import io.atomicbits.scraml.ramlparser.parser.RamlParser import org.scalatest.featurespec.AnyFeatureSpec /** * Created by peter on 12/03/17. */ class MultipleAcceptHeadersTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll with ScalaFutures { Feature("A RAML model may have multiple equal or different content type or accept headers") { Scenario("test multiple equal accept headers in a RAML model") { Given("a json-schema containing an object hierarcy") val packageBasePath = List("io", "atomicbits") When("we generate the RAMl specification into a resource DSL") implicit val platform: ScalaPlay = ScalaPlay(packageBasePath) val raml: Raml = RamlParser("multipleacceptheaders/TestMultipleAcceptHeaders.raml", "UTF-8").parse.get val (ramlExp, canonicalLookup) = raml.collectCanonicals(packageBasePath) val generationAggregator: GenerationAggr = GenerationAggr(apiName = "TestMultipleAcceptHeaders", apiBasePackage = packageBasePath, raml = ramlExp, canonicalToMap = canonicalLookup.map) generationAggregator.generate Then("we should get valid DSL code in the presense of multple accept headers") } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/JsonSchemaIdExtractor.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model import io.atomicbits.scraml.ramlparser.model.parsedtypes.ParsedTypeReference import play.api.libs.json.{ JsObject, JsValue } /** * Created by peter on 25/03/16. */ object JsonSchemaIdExtractor { def apply(json: JsValue): Id = List(JsonSchemaIdAnalyser.idFromField(json, "id"), JsonSchemaIdAnalyser.idFromField(json, "title")).flatten.headOption .getOrElse(ImplicitId) } object RefExtractor { def unapply(json: JsValue): Option[Id] = JsonSchemaIdAnalyser.idFromField(json, ParsedTypeReference.value) } object JsonSchemaIdAnalyser { /** * Transform the given field of the schema to an Id if possible. * * @param json The schema * @param field The id field * @return The Id */ def idFromField(json: JsValue, field: String): Option[Id] = (json \ field).asOpt[String] map idFromString def idFromString(id: String): Id = { if (isRoot(id)) RootId(id = cleanRoot(id)) else if (isFragment(id)) idFromFragment(id) else if (isAbsoluteFragment(id)) idFromAbsoluteFragment(id) else RelativeId(id = id.trim.stripPrefix("/")) } def isRoot(id: String): Boolean = id.contains("://") && !isAbsoluteFragment(id) def isFragment(id: String): Boolean = { id.trim.startsWith("#") } def idFromFragment(id: String): FragmentId = { FragmentId(id.trim.stripPrefix("#").stripPrefix("/").split('/').toList) } def isAbsoluteFragment(id: String): Boolean = { val parts = id.trim.split('#') parts.length == 2 && parts(0).contains("://") } def idFromAbsoluteFragment(id: String): AbsoluteFragmentId = { val parts = id.trim.split('#') AbsoluteFragmentId(RootId(parts(0)), parts(1).split('/').toList.collect { case part if part.nonEmpty => part }) } def cleanRoot(root: String): String = { root.trim.stripSuffix("#") } def isModelObject(json: JsObject): Boolean = { (json \ "type").asOpt[String].exists(_ == "object") } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/JsUtils.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.parser import play.api.libs.json._ /** * Created by peter on 19/08/16. */ object JsUtils { implicit class JsOps(val jsValue: JsValue) { def fieldStringValue(field: String): Option[String] = { (jsValue \ field).toOption.collect { case JsString(value) => value } } def fieldIntValue(field: String): Option[Int] = { (jsValue \ field).toOption.collect { case JsNumber(value) => value.intValue } } def fieldDoubleValue(field: String): Option[Double] = { (jsValue \ field).toOption.collect { case JsNumber(value) => value.doubleValue } } def fieldBooleanValue(field: String): Option[Boolean] = { (jsValue \ field).toOption.collect { case JsBoolean(bool) => bool } } def fieldStringListValue(field: String): Option[Seq[String]] = { (jsValue \ field).toOption.collect { case JsArray(values) => values.collect { case JsString(value) => value } } map(_.toSeq) } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/DateTypesTest.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser import io.atomicbits.scraml.ramlparser.lookup.{ CanonicalNameGenerator, CanonicalTypeCollector } import io.atomicbits.scraml.ramlparser.model.{ NativeId, Raml } import io.atomicbits.scraml.ramlparser.model.parsedtypes.{ ParsedObject, ParsedString } import io.atomicbits.scraml.ramlparser.parser.RamlParser import io.atomicbits.util.TestUtils import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import org.scalatest.featurespec.AnyFeatureSpec import scala.util.Try /** * Created by peter on 6/07/17. */ class DateTypesTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll { Scenario("test parsing date types in a RAML 1.0 model") { Given("a RAML 1.0 specification with date types") val defaultBasePath = List("io", "atomicbits", "types") val parser = RamlParser("/date-types/DateTypesTest.raml", "UTF-8") When("we parse the specification") val parsedModel: Try[Raml] = parser.parse Then("we get the parsed date times") val raml = parsedModel.get // val bookType = raml.types(NativeId("Book")).asInstanceOf[ParsedObject] // bookType.properties("title").propertyType.parsed match { // case stringType: ParsedString => stringType.required shouldBe Some(true) // case _ => fail(s"The title property of a book should be a StringType.") // } val prettyModel = TestUtils.prettyPrint(parsedModel) val canonicalTypeCollector = CanonicalTypeCollector(CanonicalNameGenerator(defaultBasePath)) val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml) } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/javajackson/ResourceClassGenerator.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.javajackson import io.atomicbits.scraml.generator.codegen.{ ActionGenerator, DslSourceRewriter, GenerationAggr, SourceCodeFragment } import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform, SourceGenerator } import io.atomicbits.scraml.generator.typemodel.ResourceClassDefinition import io.atomicbits.scraml.generator.platform.Platform._ import io.atomicbits.scraml.generator.util.CleanNameUtil import io.atomicbits.scraml.ramlparser.parser.SourceFile /** * Created by peter on 1/03/17. */ case class ResourceClassGenerator(javaJackson: CommonJavaJacksonPlatform) extends SourceGenerator { implicit val platform: CommonJavaJacksonPlatform = javaJackson def generate(generationAggr: GenerationAggr, resourceClassDefinition: ResourceClassDefinition): GenerationAggr = { val classDefinition = generateClassDefinition(resourceClassDefinition) val resourceClassReference = resourceClassDefinition.classReference val dslFields = resourceClassDefinition.childResourceDefinitions.map(generateResourceDslField) val SourceCodeFragment(actionImports, actionFunctions, headerPathSourceDefs) = ActionGenerator(new JavaActionCodeGenerator(platform)).generateActionFunctions(resourceClassDefinition) val imports = platform.importStatements(resourceClassReference, actionImports) val resourceConstructors = generateResourceConstructors(resourceClassDefinition) val addHeaderConstructorArgs = generateAddHeaderConstructorArguments(resourceClassDefinition) val setHeaderConstructorArgs = generateSetHeaderConstructorArguments(resourceClassDefinition) val className = resourceClassReference.name val classNameCamel = CleanNameUtil.camelCased(className) val dslBasePackage = platform.rewrittenDslBasePackage.mkString(".") val sourcecode = s""" package ${resourceClassReference.packageName}; import $dslBasePackage.*; import java.util.*; import java.util.concurrent.CompletableFuture; import java.io.*; ${imports.mkString("\n")} $classDefinition public $className(){ } ${resourceConstructors.mkString("\n\n")} public $className addHeader(String key, String value) { $className $classNameCamel = new $className(getRequestBuilder(), true); $classNameCamel._requestBuilder.addHeader(key, value); return $classNameCamel; } public $className setHeader(String key, String value) { $className $classNameCamel = new $className(getRequestBuilder(), true); $classNameCamel._requestBuilder.setHeader(key, value); return $classNameCamel; } ${dslFields.mkString("\n\n")} ${actionFunctions.mkString("\n\n")} } """ generationAggr .addSourceDefinitions(resourceClassDefinition.childResourceDefinitions) .addSourceDefinitions(headerPathSourceDefs) .addSourceFile(SourceFile(filePath = resourceClassReference.toFilePath, content = sourcecode)) } def generateResourceConstructors(resourceClassDefinition: ResourceClassDefinition): List[String] = { val resourceClassReference = resourceClassDefinition.classReference val resource = resourceClassDefinition.resource resourceClassDefinition.urlParamClassPointer().map(_.native) match { case Some(paramClassReference) => List( s""" public ${resourceClassReference.name}(${paramClassReference.name} value, RequestBuilder requestBuilder) { super(value, requestBuilder); } """, s""" public ${resourceClassReference.name}(RequestBuilder requestBuilder, Boolean noPath) { super(requestBuilder); } """ ) case None => List( s""" public ${resourceClassReference.name}(RequestBuilder requestBuilder) { super("${resource.urlSegment}", requestBuilder); } """, s""" public ${resourceClassReference.name}(RequestBuilder requestBuilder, Boolean noPath) { super(requestBuilder); } """ ) } } def generateClassDefinition(resourceClassDefinition: ResourceClassDefinition): String = { val resource = resourceClassDefinition.resource val resourceClassRef = resourceClassDefinition.classReference resourceClassDefinition.urlParamClassPointer().map(_.native) match { case Some(urlParamClassReference) => val urlParamClassName = urlParamClassReference.name s"""public class ${resourceClassRef.name} extends ParamSegment<$urlParamClassName> { """ case None => s"""public class ${resourceClassRef.name} extends PlainSegment {""" } } def generateResourceDslField(resourceClassDefinition: ResourceClassDefinition): String = { val resource = resourceClassDefinition.resource val cleanUrlSegment = platform.escapeJavaKeyword(CleanNameTools.cleanMethodName(resource.urlSegment)) val resourceClassRef = resourceClassDefinition.classReference resourceClassDefinition.urlParamClassPointer().map(_.native) match { case Some(urlParamClassReference) => val urlParamClassName = urlParamClassReference.name s""" public ${resourceClassRef.fullyQualifiedName} $cleanUrlSegment($urlParamClassName value) { return new ${resourceClassRef.fullyQualifiedName}(value, this.getRequestBuilder()); } """ case None => s""" public ${resourceClassRef.fullyQualifiedName} $cleanUrlSegment = new ${resourceClassRef.fullyQualifiedName}(this.getRequestBuilder()); """ } } def generateAddHeaderConstructorArguments(resourceClassDefinition: ResourceClassDefinition): String = resourceClassDefinition.urlParamClassPointer() match { case Some(parameter) => "(_value, _requestBuilder.withAddedHeaders(newHeaders: _*))" case None => "(_requestBuilder.withAddedHeaders(newHeaders: _*))" } def generateSetHeaderConstructorArguments(resourceClassDefinition: ResourceClassDefinition): String = resourceClassDefinition.urlParamClassPointer() match { case Some(parameter) => "(_value, _requestBuilder.withSetHeaders(newHeaders: _*))" case None => "(_requestBuilder.withSetHeaders(newHeaders: _*))" } }
atomicbits/scramlgen
modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/client/FactoryLoader.scala
<filename>modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/client/FactoryLoader.scala<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.dsl.scalaplay.client import scala.language.postfixOps import scala.util.{ Failure, Try } /** * Created by peter on 8/01/16. */ object FactoryLoader { val defaultClientFactoryClass = "io.atomicbits.scraml.dsl.scalaplay.client.ning.Ning2ClientFactory" def load(clientFactoryClass: Option[String] = None): Try[ClientFactory] = { val factoryClass = clientFactoryClass.getOrElse(defaultClientFactoryClass) Try { Class.forName(factoryClass).newInstance().asInstanceOf[ClientFactory] } recoverWith { case cnfe: NoClassDefFoundError => Failure( new NoClassDefFoundError( s"${cnfe.getMessage} The scraml FactoryLoader cannot load factory class $factoryClass. Did you add the dependency to this factory?" ) ) case e => Failure(e) } } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/codegen/ActionCode.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.codegen import io.atomicbits.scraml.generator.restmodel.{ ActionSelection, ContentType, ResponseType } import io.atomicbits.scraml.generator.typemodel._ import io.atomicbits.scraml.ramlparser.model.{ Parameter, QueryString } /** * Created by peter on 20/01/17. */ trait ActionCode { def contentHeaderSegmentField(contentHeaderMethodName: String, headerSegment: ClassReference): String def queryStringType(actionSelection: ActionSelection): Option[ClassPointer] /** * The list of body types that need to be available on a specific action function. */ def bodyTypes(action: ActionSelection): List[Option[ClassPointer]] def responseTypes(action: ActionSelection): List[Option[ClassPointer]] def expandMethodParameter(parameters: List[(String, ClassPointer)]): List[String] def hasPrimitiveBody(optBodyType: Option[ClassPointer]): Boolean = { optBodyType.collect { case StringClassPointer | ByteClassPointer | BooleanClassPointer(_) | LongClassPointer(_) | DoubleClassPointer(_) => true } getOrElse false } def responseClassDefinition(responseType: ResponseType): String def sortQueryOrFormParameters(fieldParams: List[(String, Parameter)]): List[(String, Parameter)] def expandQueryOrFormParameterAsMethodParameter(qParam: (String, Parameter), noDefault: Boolean = false): SourceCodeFragment def expandQueryStringAsMethodParameter(queryString: QueryString): SourceCodeFragment def expandQueryOrFormParameterAsMapEntry(qParam: (String, Parameter)): String def generateAction(actionSelection: ActionSelection, bodyType: Option[ClassPointer], queryStringType: Option[ClassPointer], isBinary: Boolean, actionParameters: List[String] = List.empty, formParameterMapEntries: List[String] = List.empty, isTypedBodyParam: Boolean = false, isMultipartParams: Boolean = false, isBinaryParam: Boolean = false, contentType: ContentType, responseType: ResponseType): String }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/DateType.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.canonicaltypes import io.atomicbits.scraml.ramlparser.model._ /** * Created by peter on 11/12/16. */ trait DateType extends PrimitiveType { def format: DateFormat } case object DateOnlyType extends DateType { val format = RFC3339FullDate val canonicalName = CanonicalName.create("DateOnly") val refers: CanonicalName = canonicalName } case object TimeOnlyType extends DateType { val format = RFC3339PartialTime val canonicalName = CanonicalName.create("TimeOnly") val refers: CanonicalName = canonicalName } case object DateTimeOnlyType extends DateType { val format = DateOnlyTimeOnly val canonicalName = CanonicalName.create("DateTimeOnly") val refers: CanonicalName = canonicalName } case object DateTimeDefaultType extends DateType { val format = RFC3339DateTime val canonicalName = CanonicalName.create("DateTimeRFC3339") val refers: CanonicalName = canonicalName } case object DateTimeRFC2616Type extends DateType { val format = RFC2616 val canonicalName = CanonicalName.create("DateTimeRFC2616") val refers: CanonicalName = canonicalName }
atomicbits/scramlgen
modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/QueryParameterParseTest.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser import io.atomicbits.scraml.ramlparser.model.parsedtypes._ import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.parser.RamlParser import org.scalatest.featurespec.AnyFeatureSpec import org.scalatest.matchers.should.Matchers._ import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import scala.util.Try /** * Created by peter on 1/11/16. */ class QueryParameterParseTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll { Feature("query parameter parsing") { Scenario("test parsing query parameters in a complex RAML 1.0 model") { Given("a RAML 1.0 specification") val parser = RamlParser("/raml08/TestApi.raml", "UTF-8") When("we parse the specification") val parsedModel: Try[Raml] = parser.parse Then("we get the expected query parameters") val raml = parsedModel.get val restResource: Resource = raml.resources.filter(_.urlSegment == "rest").head val userResource: Resource = restResource.resources.filter(_.urlSegment == "user").head val getAction: Action = userResource.actions.filter(_.actionType == Get).head val organizationQueryParameter: Parameter = getAction.queryParameters.byName("organization").get organizationQueryParameter.parameterType.parsed shouldBe a[ParsedArray] organizationQueryParameter.parameterType.parsed.asInstanceOf[ParsedArray].items shouldBe a[ParsedString] // val prettyModel = TestUtils.prettyPrint(parsedModel) // println(s"Parsed raml: $prettyModel") } } }
atomicbits/scramlgen
project/BuildSettings.scala
<reponame>atomicbits/scramlgen /* * * (C) Copyright 2018 Atomic BITS (https://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ import sbt._ import sbt.Keys._ object BuildSettings { val Organization = "io.atomicbits" val snapshotSuffix = "-SNAPSHOT" val scala2_12 = "2.12.10" val ScalaVersion = scala2_12 val defaultCrossScalaVersions = Seq(scala2_12) val scalacBuildOptions = Seq( "-unchecked", "-deprecation", "-feature", // "-Xfatal-warnings", // "-Xlint:-infer-any", // "-Ywarn-value-discard", "-encoding", "UTF-8" // "-target:jvm-1.8", // "-Ydelambdafy:method" ) def projectSettings(extraDependencies: Seq[ModuleID]) = Seq( organization := Organization, isSnapshot := version.value.endsWith(snapshotSuffix), scalaVersion := ScalaVersion, crossScalaVersions := defaultCrossScalaVersions, scalacOptions := scalacBuildOptions, parallelExecution := false, // Sonatype snapshot resolver is needed to fetch rxhttpclient-scala_2.11:0.2.0-SNAPSHOT. // resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots", libraryDependencies ++= extraDependencies ) val publishingCredentials = (for { username <- Option(System.getenv().get("SONATYPE_USERNAME")) password <- Option(System.getenv().get("SONATYPE_PASSWORD")) } yield Seq(Credentials("Sonatype Nexus Repository Manager", "oss.sonatype.org", username, password))).getOrElse(Seq()) val publishSettings = Seq( publishMavenStyle := true, pomIncludeRepository := { _ => false }, publishTo := { val nexus = "https://oss.sonatype.org/" if (isSnapshot.value) Some("snapshots" at nexus + "content/repositories/snapshots") else Some("releases" at nexus + "service/local/staging/deploy/maven2") }, pomExtra := pomInfo, credentials ++= publishingCredentials ) def projSettings(dependencies: Seq[ModuleID]) = { projectSettings(dependencies) ++ publishSettings } lazy val pomInfo = <url>https://github.com/atomicbits/scraml</url> <licenses> <license> <name>AGPL licencse</name> <url>http://www.gnu.org/licenses/agpl-3.0.en.html</url> <distribution>repo</distribution> </license> </licenses> <scm> <url><EMAIL>:atomicbits/scraml.git</url> <connection>scm:git:git@github.com:atomicbits/scraml.git</connection> </scm> <developers> <developer> <id>rigolepe</id> <name><NAME></name> <url>http://atomicbits.io</url> </developer> </developers> }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/javajackson/CommonJavaJacksonPlatform.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.javajackson import java.nio.file.{ Path, Paths } import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform } import io.atomicbits.scraml.generator.typemodel._ import Platform._ import io.atomicbits.scraml.generator.codegen.GenerationAggr /** * Created by peter on 1/11/17. */ trait CommonJavaJacksonPlatform extends Platform with CleanNameTools { implicit val platform: Platform def dslBasePackageParts: List[String] def rewrittenDslBasePackage: List[String] override def classPointerToNativeClassReference(classPointer: ClassPointer): ClassReference = { classPointer match { case classReference: ClassReference => classReference case ArrayClassPointer(arrayType) => ClassReference(name = arrayType.native.name, packageParts = arrayType.native.safePackageParts, arrayType = Some(arrayType.native)) case StringClassPointer => ClassReference(name = "String", packageParts = List("java", "lang"), predef = true) case ByteClassPointer => ClassReference(name = "byte", packageParts = List.empty, predef = true) case BinaryDataClassPointer => ClassReference(name = "BinaryData", packageParts = rewrittenDslBasePackage, library = true) case FileClassPointer => ClassReference(name = "File", packageParts = List("java", "io"), library = true) case InputStreamClassPointer => ClassReference(name = "InputStream", packageParts = List("java", "io"), library = true) case JsObjectClassPointer => ClassReference(name = "JsonNode", packageParts = List("com", "fasterxml", "jackson", "databind"), library = true) case JsValueClassPointer => ClassReference(name = "JsonNode", packageParts = List("com", "fasterxml", "jackson", "databind"), library = true) case BodyPartClassPointer => ClassReference(name = "BodyPart", packageParts = rewrittenDslBasePackage, library = true) case LongClassPointer(primitive) => if (primitive) { ClassReference(name = "long", packageParts = List("java", "lang"), predef = true) } else { ClassReference(name = "Long", packageParts = List("java", "lang"), predef = true) } case DoubleClassPointer(primitive) => if (primitive) { ClassReference(name = "double", packageParts = List("java", "lang"), predef = true) } else { ClassReference(name = "Double", packageParts = List("java", "lang"), predef = true) } case BooleanClassPointer(primitive) => if (primitive) { ClassReference(name = "boolean", packageParts = List("java", "lang"), predef = true) } else { ClassReference(name = "Boolean", packageParts = List("java", "lang"), predef = true) } case DateTimeRFC3339ClassPointer => ClassReference(name = "DateTimeRFC3339", packageParts = rewrittenDslBasePackage, library = true) case DateTimeRFC2616ClassPointer => ClassReference(name = "DateTimeRFC2616", packageParts = rewrittenDslBasePackage, library = true) case DateTimeOnlyClassPointer => ClassReference(name = "DateTimeOnly", packageParts = rewrittenDslBasePackage, library = true) case TimeOnlyClassPointer => ClassReference(name = "TimeOnly", packageParts = rewrittenDslBasePackage, library = true) case DateOnlyClassPointer => ClassReference(name = "DateOnly", packageParts = rewrittenDslBasePackage, library = true) case ListClassPointer(typeParamValue) => val typeParameter = TypeParameter("T") val typeParamValues = List(typeParamValue) ClassReference( name = "List", packageParts = List("java", "util"), typeParameters = List(typeParameter), typeParamValues = typeParamValues, library = true ) case typeParameter: TypeParameter => ClassReference(name = typeParameter.name, predef = true, isTypeParameter = true) case _: io.atomicbits.scraml.generator.typemodel.PrimitiveClassPointer => ??? } } override def implementingInterfaceReference(classReference: ClassReference): ClassReference = ClassReference( name = s"${classReference.name}Impl", packageParts = classReference.packageParts ) override def classDefinition(classPointer: ClassPointer, fullyQualified: Boolean = false): String = { val classReference = classPointer.native val typedClassDefinition = (classReference.typeParameters, classReference.typeParamValues) match { case (Nil, _) => classReference.name case (tps, Nil) => val typeParameterNames = tps.map(_.name) s"${classReference.name}<${typeParameterNames.mkString(",")}>" case (tps, tpvs) if tps.size == tpvs.size => val typeParameterValueClassDefinitions = tpvs.map { classPointer => if (fullyQualified) classPointer.native.fullyQualifiedClassDefinition else classPointer.native.classDefinition } s"${classReference.name}<${typeParameterValueClassDefinitions.mkString(",")}>" case (tps, tpvs) => val message = s""" |The following class definition has a different number of type parameter |values than there are type parameters: |$classPointer """.stripMargin sys.error(message) } val arrayedClassDefinition = if (classReference.isArray) s"$typedClassDefinition[]" else typedClassDefinition if (fullyQualified) { val parts = safePackageParts(classPointer) :+ arrayedClassDefinition parts.mkString(".") } else { arrayedClassDefinition } } override def className(classPointer: ClassPointer): String = classPointer.native.name override def packageName(classPointer: ClassPointer): String = safePackageParts(classPointer).mkString(".") override def fullyQualifiedName(classPointer: ClassPointer): String = { val parts: List[String] = safePackageParts(classPointer) :+ className(classPointer) parts.mkString(".") } override def safePackageParts(classPointer: ClassPointer): List[String] = { classPointer.native.packageParts.map(part => escapeJavaKeyword(cleanPackageName(part), "esc")) } override def safeFieldName(fieldName: String): String = { val cleanName = cleanFieldName(fieldName) escapeJavaKeyword(cleanName) } override def fieldDeclarationWithDefaultValue(field: Field): String = fieldDeclaration(field) override def fieldDeclaration(field: Field): String = { s"${classDefinition(field.classPointer)} ${safeFieldName(field)}" } override def importStatements(targetClassReference: ClassPointer, dependencies: Set[ClassPointer] = Set.empty): Set[String] = { val ownPackage = targetClassReference.packageName def collectTypeImports(collected: Set[String], classPtr: ClassPointer): Set[String] = { def importFromClassReference(classRef: ClassReference): Option[String] = { if (classRef.isArray) { importFromClassReference(classRef.arrayType.get) } else { if (classRef.packageName != ownPackage && !classRef.predef) Some(s"import ${classRef.fullyQualifiedName};") else None } } val classReference = classPtr.native val collectedWithClassRef = importFromClassReference(classReference).map(classRefImport => collected + classRefImport).getOrElse(collected) classReference.typeParamValues.foldLeft(collectedWithClassRef)(collectTypeImports) } val targetClassImports: Set[String] = collectTypeImports(Set.empty, targetClassReference) val dependencyImports: Set[String] = dependencies.foldLeft(targetClassImports)(collectTypeImports) dependencyImports } override def toSourceFile(generationAggr: GenerationAggr, toClassDefinition: TransferObjectClassDefinition): GenerationAggr = PojoGenerator(this).generate(generationAggr, toClassDefinition) override def toSourceFile(generationAggr: GenerationAggr, toInterfaceDefinition: TransferObjectInterfaceDefinition): GenerationAggr = InterfaceGenerator(this).generate(generationAggr, toInterfaceDefinition) override def toSourceFile(generationAggr: GenerationAggr, enumDefinition: EnumDefinition): GenerationAggr = EnumGenerator(this).generate(generationAggr, enumDefinition) override def toSourceFile(generationAggr: GenerationAggr, clientClassDefinition: ClientClassDefinition): GenerationAggr = ClientClassGenerator(this).generate(generationAggr, clientClassDefinition) override def toSourceFile(generationAggr: GenerationAggr, resourceClassDefinition: ResourceClassDefinition): GenerationAggr = ResourceClassGenerator(this).generate(generationAggr, resourceClassDefinition) override def toSourceFile(generationAggr: GenerationAggr, headerSegmentClassDefinition: HeaderSegmentClassDefinition): GenerationAggr = HeaderSegmentClassGenerator(this).generate(generationAggr, headerSegmentClassDefinition) override def toSourceFile(generationAggr: GenerationAggr, unionClassDefinition: UnionClassDefinition): GenerationAggr = UnionClassGenerator(this).generate(generationAggr, unionClassDefinition) override val classFileExtension: String = "java" override def toFilePath(classPointer: ClassPointer): Path = { classPointer match { case classReference: ClassReference => val parts = classReference.safePackageParts :+ s"${classReference.name}.$classFileExtension" Paths.get("", parts: _*) // This results in a relative path both on Windows as on Linux/Mac case _ => sys.error(s"Cannot create a file path from a class pointer that is not a class reference!") } } val reservedKeywords = Set( "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while" ) def escapeJavaKeyword(someName: String, escape: String = "$"): String = reservedKeywords.foldLeft(someName) { (name, resWord) => if (name == resWord) s"$name$escape" else name } }
atomicbits/scramlgen
modules/scraml-gen-simulation/src/test/scala/io/atomicbits/scraml/client/manual/ManualScramlGeneratorTest.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.client.manual import java.net.URL import java.nio.charset.Charset import com.github.tomakehurst.wiremock.WireMockServer import com.github.tomakehurst.wiremock.client.WireMock import com.github.tomakehurst.wiremock.client.WireMock._ import com.github.tomakehurst.wiremock.core.WireMockConfiguration._ import io.atomicbits.scraml.dsl.scalaplay.RequestBuilder import io.atomicbits.scraml.dsl.scalaplay.client.ning.Ning2ClientFactory import org.scalatest.concurrent.ScalaFutures import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import io.atomicbits.scraml.dsl.scalaplay.client.{ ClientConfig, ClientFactory } import org.scalatest.featurespec.AnyFeatureSpec import scala.concurrent._ import scala.concurrent.duration._ import scala.language.{ postfixOps, reflectiveCalls } /** * The client in this test is manually written to understand what kind of code we need to generate to support the DSL. */ class XoClient(private val _requestBuilder: RequestBuilder) { def rest = new RestResource(_requestBuilder.withAddedPathSegment("rest")) def _close() = _requestBuilder.client.close() } object XoClient { import io.atomicbits.scraml.dsl.scalaplay.Response import play.api.libs.json._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future def apply(url: URL, config: ClientConfig = ClientConfig(), defaultHeaders: Map[String, String] = Map(), clientFactory: Option[ClientFactory] = None): XoClient = { val requestBuilder = RequestBuilder( clientFactory .getOrElse(Ning2ClientFactory) .createClient( protocol = url.getProtocol, host = url.getHost, port = if (url.getPort == -1) url.getDefaultPort else url.getPort, prefix = if (url.getPath.isEmpty) None else Some(url.getPath), config = config, defaultHeaders = defaultHeaders ) .get ) new XoClient(requestBuilder) } def apply(host: String, port: Int, protocol: String, prefix: Option[String], config: ClientConfig, defaultHeaders: Map[String, String], clientFactory: Option[ClientFactory]) = { val requestBuilder = RequestBuilder( clientFactory .getOrElse(Ning2ClientFactory) .createClient( protocol = protocol, host = host, port = port, prefix = prefix, config = config, defaultHeaders = defaultHeaders ) .get ) new XoClient(requestBuilder) } implicit class FutureResponseOps[T](val futureResponse: Future[Response[T]]) extends AnyVal { def asString: Future[String] = futureResponse.map { resp => resp.stringBody getOrElse { val message = if (resp.status != 200) s"The response has no string body because the request was not successful (status = ${resp.status})." else "The response has no string body despite status 200." throw new IllegalArgumentException(message) } } def asJson: Future[JsValue] = futureResponse.map { resp => resp.jsonBody.getOrElse { val message = if (resp.status != 200) s"The response has no JSON body because the request was not successful (status = ${resp.status})." else "The response has no JSON body despite status 200." throw new IllegalArgumentException(message) } } def asType: Future[T] = futureResponse.map { resp => resp.body.getOrElse { val message = if (resp.status != 200) s"The response has no typed body because the request was not successful (status = ${resp.status})." else "The response has no typed body despite status 200." throw new IllegalArgumentException(message) } } } } class ManualScramlGeneratorTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll with ScalaFutures { import XoClient._ val port = 8181 val host = "localhost" val wireMockServer = new WireMockServer(wireMockConfig().port(port)) override def beforeAll(): Unit = { wireMockServer.start() WireMock.configureFor(host, port) } override def afterAll(): Unit = { wireMockServer.stop() } Feature("build a restful request using a Scala DSL") { Scenario("test manually written Scala DSL") { Given("some manually written DSL code and a mock service that listens for client calls") stubFor( get(urlEqualTo(s"/rest/some/webservice/pathparamvalue?queryparX=2.0&queryparY=50&queryParZ=123")) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withBody("""{"firstName":"John", "lastName": "Doe", "age": 21}""") .withStatus(200))) stubFor( put(urlEqualTo(s"/rest/some/webservice/pathparamvalue")) .withHeader("Content-Type", equalTo("application/json; charset=UTF-8")) .withHeader("Accept", equalTo("application/json")) .withRequestBody(equalTo("""{"firstName":"John","lastName":"Doe","age":21}""")) .willReturn(aResponse() .withBody("""{"street":"Mulholland Drive", "city": "LA", "zip": "90210", "number": 105}""") .withStatus(200))) When("we execute some restful requests using the DSL") val futureResultGet: Future[User] = XoClient(protocol = "http", host = host, port = port, prefix = None, config = ClientConfig(), defaultHeaders = Map.empty, clientFactory = None).rest.some.webservice .pathparam("pathparamvalue") .withHeaders("Accept" -> "application/json") .get(queryparX = 2.0, queryparY = 50, queryParZ = Option(123)) .call() .asType val futureResultPut: Future[Address] = XoClient( protocol = "http", host = host, port = port, prefix = None, config = ClientConfig(requestCharset = Charset.forName("UTF-8")), defaultHeaders = Map.empty, clientFactory = None ).rest.some.webservice .pathparam("pathparamvalue") .withHeaders( "Content-Type" -> "application/json; charset=UTF-8", "Accept" -> "application/json" ) .put(User("John", "Doe", 21)) .call() .asType Then("we should see the expected response values") val resultGet = Await.result(futureResultGet, 2 seconds) assertResult(User("John", "Doe", 21))(resultGet) val resultPut = Await.result(futureResultPut, 2 seconds) assertResult(Address("Mulholland Drive", "LA", "90210", 105))(resultPut) } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/TypeUtils.scala
<reponame>atomicbits/scramlgen /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.lookup import io.atomicbits.scraml.ramlparser.model._ /** * Created by peter on 22/07/15. * * ToDo: move this functionality inside the TypeLookupTable to simplify its interface. */ object TypeUtils { def asUniqueId(id: Id): UniqueId = { id match { case uniqueId: UniqueId => uniqueId case _ => sys.error(s"$id is not a unique id.") } } def asAbsoluteId(id: Id, nativeToRootId: NativeId => AbsoluteId): AbsoluteId = { id match { case nativeId: NativeId => nativeToRootId(nativeId) case absoluteId: AbsoluteId => absoluteId case other => sys.error(s"Cannot transform $other into an absolute id.") } } }
atomicbits/scramlgen
modules/scraml-gen-simulation/src/test/java/io/atomicbits/scraml/client/java/ObjectMapperTest.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.client.java import java.util import java.util.{ List => JList } import com.fasterxml.jackson.databind.`type`.TypeFactory import com.fasterxml.jackson.databind.{ JavaType, ObjectMapper, ObjectWriter } import org.scalatest.concurrent.ScalaFutures import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import org.scalatest.featurespec.AnyFeatureSpec /** * Created by peter on 12/10/15. */ class ObjectMapperTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll with ScalaFutures { Feature("We have an Object Mapper to serialize and deserialize objects") { Scenario("Test the Object Mapper on canonical object representations") { Given("An object mapper") val objectMapper: ObjectMapper = new ObjectMapper When("Some data is provided to the object mapper to read") val person = new Person() person.setFirstName("John") person.setLastName("Doe") person.setAge(21L) val personList: JList[Person] = util.Arrays.asList(person) val javaType: JavaType = TypeFactory.defaultInstance.constructFromCanonical("java.util.List<io.atomicbits.scraml.client.java.Person>") val readPerson: JList[Person] = objectMapper.readValue("""[{"firstName":"John", "lastName": "Doe", "age": 21}]""", javaType) Then("The correct data type is read") println(s"Person list is: $readPerson") assertResult(personList)(readPerson) // equals is overriden in Person // see if we can overcome type erasure // val writer: ObjectWriter = objectMapper.writerFor(javaType) val serializedPersonList: String = objectMapper.writeValueAsString(personList) // writer.writeValueAsString(personList) assertResult("""[{"firstName":"John","lastName":"Doe","age":21}]""")(serializedPersonList) } Scenario("Test the Object Mapper on a type hierarcy") { val objectMapper: ObjectMapper = new ObjectMapper val dog: Dog = new Dog(true, "female", "Ziva") val serializedDog: String = objectMapper.writeValueAsString(dog) assertResult("""{"_type":"Dog","canBark":true,"gender":"female","name":"Ziva"}""")(serializedDog) } Scenario("Test the object mapper on a type hierarcy in the type erased context of Java Lists") { val objectMapper: ObjectMapper = new ObjectMapper val animals: JList[Animal] = util.Arrays.asList(new Dog(true, "male", "Wiskey"), new Fish("Wanda"), new Cat("male", "Duster")) val javaType: JavaType = TypeFactory.defaultInstance.constructFromCanonical("java.util.List<io.atomicbits.scraml.client.java.Animal>") val writer: ObjectWriter = objectMapper.writerFor(javaType) val serializedAnimals: String = writer.writeValueAsString(animals) // objectMapper.writeValueAsString(animals) println("animals: " + serializedAnimals) assertResult( """[{"_type":"Dog","canBark":true,"gender":"male","name":"Wiskey"},{"_type":"Fish","gender":"Wanda"},{"_type":"Cat","gender":"male","name":"Duster"}]""")( serializedAnimals) } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/transformers/ParsedTypeReferenceTransformer.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.lookup.transformers import io.atomicbits.scraml.ramlparser.lookup.{ CanonicalLookupHelper, CanonicalNameGenerator, ParsedToCanonicalTypeTransformer } import io.atomicbits.scraml.ramlparser.model.canonicaltypes._ import io.atomicbits.scraml.ramlparser.model.parsedtypes.{ PrimitiveType => ParsedPrimitiveType, _ } /** * Created by peter on 23/12/16. */ object ParsedTypeReferenceTransformer { // format: off def unapply(parsedTypeContext: ParsedTypeContext) (implicit canonicalNameGenerator: CanonicalNameGenerator): Option[(TypeReference, CanonicalLookupHelper)] = { // format: on val parsed: ParsedType = parsedTypeContext.parsedType val canonicalLookupHelper: CanonicalLookupHelper = parsedTypeContext.canonicalLookupHelper val canonicalNameOpt: Option[CanonicalName] = parsedTypeContext.canonicalNameOpt val parentNameOpt: Option[CanonicalName] = parsedTypeContext.parentNameOpt // If this is a type reference to a (fragmented) json-schema type, then we need to register it as such with the canonicalLookupHelper. // In this case, we also need to use the parsedTypeContext.canonicalLookupHelper.declaredTypes map to look up the canonical name // as defined by the json-schema id (and not the native id of the RAML definition). def registerParsedTypeReference(parsedTypeReference: ParsedTypeReference, canonicalLH: CanonicalLookupHelper, referencesFollowed: List[ParsedTypeReference] = List.empty): (TypeReference, CanonicalLookupHelper) = { val (typeRefAsGenericReferrable, updatedCanonicalLH) = canonicalLookupHelper.getParsedTypeWithProperId(parsedTypeReference.refersTo).map { case _: ParsedNull => (NullType, canonicalLH) case primitiveType: ParsedPrimitiveType => val (typeRef, unusedCanonicalLH) = ParsedToCanonicalTypeTransformer.transform(primitiveType, canonicalLH) (typeRef, canonicalLH) case parsedDate: ParsedDate => val (typeRef, unusedCanonicalLH) = ParsedToCanonicalTypeTransformer.transform(parsedDate, canonicalLH) (typeRef, canonicalLH) case parsedArray: ParsedArray => val (typeRef, unusedCanonicalLH) = ParsedToCanonicalTypeTransformer.transform(parsedArray, canonicalLH) (typeRef, canonicalLH) case parsedFile: ParsedFile => val (typeRef, unusedCanonicalLH) = ParsedToCanonicalTypeTransformer.transform(parsedFile, canonicalLH) (typeRef, canonicalLH) case parsedEnum: ParsedEnum => val canonicalName = canonicalNameGenerator.generate(parsedEnum.id) val typeReference = NonPrimitiveTypeReference(canonicalName) (typeReference, canonicalLH) case parsedObject: ParsedObject if parsedObject.isEmpty => (JsonType, canonicalLH) case parsedObject: ParsedObject => val canonicalName = canonicalNameGenerator.generate(parsedObject.id) val (genericTypes, unusedCanonicalLH) = transformGenericTypes(parsedTypeReference.genericTypes, canonicalLH) val typeReference = NonPrimitiveTypeReference( refers = canonicalName, genericTypes = genericTypes, genericTypeParameters = parsedObject.typeParameters.map(TypeParameter) ) (typeReference, canonicalLH) case parsedUnionType: ParsedUnionType => val canonicalName = canonicalNameGenerator.generate(parsedUnionType.id) val (genericTypes, unusedCanonicalLH) = transformGenericTypes(parsedTypeReference.genericTypes, canonicalLH) val typeReference = NonPrimitiveTypeReference(refers = canonicalName) (typeReference, canonicalLH) case parsedMultipleInheritance: ParsedMultipleInheritance => val canonicalName = canonicalNameGenerator.generate(parsedMultipleInheritance.id) val (genericTypes, unusedCanonicalLH) = transformGenericTypes(parsedTypeReference.genericTypes, canonicalLH) val typeReference = NonPrimitiveTypeReference( refers = canonicalName, genericTypes = genericTypes, // Can we have generic types here? genericTypeParameters = parsedMultipleInheritance.typeParameters.map(TypeParameter) ) (typeReference, canonicalLH) case parsedTRef: ParsedTypeReference => if (referencesFollowed.contains(parsedTRef)) sys.error(s"Cyclic reference detected when following $parsedTRef") else registerParsedTypeReference(parsedTRef, canonicalLH, parsedTypeReference :: referencesFollowed) case unexpected => sys.error(s"Didn't expect to find a type reference to a $unexpected in $parsedTypeReference") } getOrElse { sys.error( s"The reference to ${parsedTypeReference.refersTo} was not found in the parsed type index. " + s"Is there a typo in one of the type references? (References are case-sensitive!)") } typeRefAsGenericReferrable match { case typeReference: TypeReference => (typeReference, updatedCanonicalLH) case unexpected => sys.error(s"Expected $unexpected to be a type referece") } } def transformGenericTypes(parsedGenericTypes: List[ParsedType], canonicalLH: CanonicalLookupHelper): (List[GenericReferrable], CanonicalLookupHelper) = { val aggregator: (List[GenericReferrable], CanonicalLookupHelper) = (List.empty, canonicalLH) parsedGenericTypes.foldLeft(aggregator) { (aggr, parsedGenericType) => val (canonicalGenericList, canonicalLookup) = aggr val (genericReferrable, unusedCanonicalLookup) = ParsedToCanonicalTypeTransformer.transform(parsedGenericType, canonicalLookup) val updatedCanonicalGenericList = canonicalGenericList :+ genericReferrable (updatedCanonicalGenericList, unusedCanonicalLookup) } } parsed match { case parsedTypeReference: ParsedTypeReference => Some(registerParsedTypeReference(parsedTypeReference, canonicalLookupHelper)) case _ => None } } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/javajackson/PojoGeneratorSupport.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.platform.javajackson import io.atomicbits.scraml.generator.codegen.GenerationAggr import io.atomicbits.scraml.generator.platform.Platform import io.atomicbits.scraml.generator.typemodel.{ ClassReference, JsonTypeInfo, TransferObjectClassDefinition } import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName /** * Created by peter on 8/03/17. */ trait PojoGeneratorSupport { implicit def platform: Platform def hasOwnInterface(canonicalName: CanonicalName, generationAggr: GenerationAggr): Boolean = { generationAggr.isParentInMultipleInheritanceRelation(canonicalName) } def compileChildrenToSerialize(canonicalName: CanonicalName, toClassDefinition: TransferObjectClassDefinition, generationAggr: GenerationAggr): Set[ChildToSerialize] = { val isTopLevelParent = !generationAggr.hasParents(canonicalName) val hasChildren = generationAggr.hasChildren(canonicalName) if (isTopLevelParent && hasChildren) { val selfAndChildrenWithClassDefinitions = generationAggr .allChildren(canonicalName) .map { child => val toClassDefinition = generationAggr.toMap.getOrElse(child, sys.error(s"Expected to find $child in the generation aggregate.")) child -> toClassDefinition } .toMap + (canonicalName -> toClassDefinition) selfAndChildrenWithClassDefinitions.map { case (child, classDefinition) => val actualClassReference = if (hasOwnInterface(child, generationAggr)) classDefinition.implementingInterfaceReference else classDefinition.reference ChildToSerialize(classReference = actualClassReference, discriminatorValue = classDefinition.actualTypeDiscriminatorValue) }.toSet } else { Set.empty[ChildToSerialize] } } def generateJsonTypeAnnotations(childrenToSerialize: Set[ChildToSerialize], jsonTypeInfo: Option[JsonTypeInfo]): String = { if (childrenToSerialize.nonEmpty) { val jsonSubTypes = childrenToSerialize.map { toSerialize => val discriminatorValue = toSerialize.discriminatorValue val name = toSerialize.classReference.name s""" @JsonSubTypes.Type(value = $name.class, name = "$discriminatorValue") """ } val typeDiscriminator = jsonTypeInfo.map(_.discriminator).getOrElse("type") s""" @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "$typeDiscriminator") @JsonSubTypes({ ${jsonSubTypes.mkString(",\n")} }) """ } else { "" } } case class ChildToSerialize(classReference: ClassReference, discriminatorValue: String) }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/ArrayType.scala
<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.canonicaltypes /** * Created by peter on 9/12/16. */ case object ArrayType extends CanonicalType { val typeParameter = TypeParameter("T") val canonicalName = CanonicalName.create("Array") val typeParameters: List[TypeParameter] = List(ArrayType.typeParameter) // val typeReference = ArrayTypeReference() }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Responses.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model import io.atomicbits.scraml.ramlparser.parser.ParseContext import play.api.libs.json.{ JsObject, JsValue } import scala.util.{ Success, Try } import io.atomicbits.scraml.util.TryUtils._ /** * Created by peter on 26/08/16. */ case class Responses(responseMap: Map[StatusCode, Response] = Map.empty) { val isEmpty = responseMap.isEmpty val values = responseMap.values.toList def get(statusCode: String): Option[Response] = responseMap.get(StatusCode(statusCode)) } object Responses { def apply(jsValue: JsValue)(implicit parseContext: ParseContext): Try[Responses] = { def fromJsObject(json: JsObject): Try[Responses] = { val tryResponseMap: Seq[Try[(StatusCode, Response)]] = json.value.collect { case Response(tryResponse) => tryResponse.map { response => response.status -> response } }.toSeq accumulate(tryResponseMap).map(responses => Responses(responses.toMap)) } (jsValue \ Response.value).toOption match { case Some(jsObject: JsObject) => fromJsObject(jsObject) case _ => Success(Responses()) } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/RamlParseException.scala
<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/RamlParseException.scala /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.parser /** * Created by peter on 10/02/16. */ class RamlParseException(val messages: List[String]) extends RuntimeException(messages.mkString("\n")) { def ++(ramlParseException: RamlParseException): RamlParseException = new RamlParseException(messages ++ ramlParseException.messages) } object RamlParseException { def apply(message: String): RamlParseException = new RamlParseException(List(message)) }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/Fragments.scala
<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/Fragments.scala /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.parsedtypes import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.parser.ParseContext import io.atomicbits.scraml.util.TryUtils import play.api.libs.json.{ JsObject, JsString, JsValue } import scala.util.{ Success, Try } /** * Created by peter on 1/04/16. */ case class Fragments(id: Id = ImplicitId, fragmentMap: Map[String, ParsedType] = Map.empty) extends ParsedType with Fragmented { override def updated(updatedId: Id): Fragments = copy(id = updatedId) override def model = JsonSchemaModel override def asTypeModel(typeModel: TypeModel): ParsedType = this def isEmpty: Boolean = fragmentMap.isEmpty def fragments: Fragments = this def map[T](fn: ((String, ParsedType)) => (String, ParsedType)): Fragments = copy(fragmentMap = fragmentMap.map(fn)) override def required: Option[Boolean] = None def values = fragmentMap.values.toList } object Fragments { def apply(json: JsObject)(implicit parseContext: ParseContext): Try[Fragments] = { val id = JsonSchemaIdExtractor(json) val fragmentsToKeep = keysToExclude.foldLeft[Map[String, JsValue]](json.value.toMap) { (schemaMap, excludeKey) => schemaMap - excludeKey } val fragments = fragmentsToKeep collect { case (fragmentFieldName, ParsedType(fragment)) => (fragmentFieldName, fragment.map(_.asTypeModel(JsonSchemaModel))) case (fragmentFieldName, Fragments(fragment)) => (fragmentFieldName, fragment) } TryUtils.withSuccess( Success(id), TryUtils.accumulate(fragments) )(Fragments(_, _)) } def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[Fragments]] = { json match { case jsObject: JsObject => Some(Fragments(jsObject)) case _ => None } } // Process the fragments and exclude the json-schema fields that we don't need to consider // (should be only objects as other fields are ignored as fragments) ToDo: check this private val keysToExclude = Seq( "id", "type", "properties", "required", "oneOf", "anyOf", "allOf", "typeVariables", "genericTypes", "genericType", "$ref", "_source", "description", "$schema", "items", "formParameters", "queryParameters", "typeDiscriminator" ) }
atomicbits/scramlgen
modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/json/TypedJson.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.dsl.scalaplay.json import play.api.libs.json._ import scala.reflect.ClassTag import scala.reflect.runtime.universe._ import scala.language.experimental.macros /** * Created by <NAME> and <NAME>. */ object TypedJson { implicit class FormatsOpts[T](val format: Format[T]) extends AnyVal { /** * Creates a TypeHintFormat that will use the classname of the type T as the typeHint of the TypeHintFormat */ def withTypeHint(implicit typeTag: TypeTag[T], classTag: ClassTag[T]): TypeHint[T] = { TypeHint(format) } /** * Creates a TypeHintFormat that will use the passed value as the type hint of the TypeHintFormat */ def withTypeHint(typeHint: String)(implicit classTag: ClassTag[T]): TypeHint[T] = { TypeHint(format = format, typeHint = typeHint) } } /** * A decorator for a regular Format that can add a type hint to the serialised json. * That same type hint is then used again when deserialising. */ case class TypeHint[T](typeHint: String, format: Format[T])(implicit classTag: ClassTag[T]) { def canWrite(obj: Any): Boolean = { obj.getClass.isAssignableFrom(classTag.runtimeClass) } def uncheckedWrites(typeHintKey: String, obj: Any) = writes(typeHintKey, obj.asInstanceOf[T]) def writes(typeHintKey: String, obj: T): JsValue = { val jsValue = format.writes(obj) jsValue match { // toevoegen van type informatie case jsObject: JsObject => Json.obj(typeHintKey -> typeHint) ++ jsObject // het heeft geen zin om een type discriminator toe te voegen op een 'primitive' JsValue case js => js } } def reads(json: JsValue): JsResult[T] = format.reads(json) } object TypeHint { /** * Create a new TypeHintFormat, using the classname as the tagValue. */ def apply[T](format: Format[T])(implicit typeTag: TypeTag[T], classTag: ClassTag[T]): TypeHint[T] = { new TypeHint[T](typeHint = typeOf[T].toString, format = format)(classTag) } } /** * Create a Format that will find the correct format amongst the passed formats when serialising/deserialising, * using the type hint in the TypeFormat. * The field that holds the type hint will be the value of `typeKey` */ case class TypeHintFormat[A](typeHintKey: String, typeHintFormats: TypeHint[_ <: A]*) extends Format[A] { require(typeHintFormats.map(_.typeHint).toSet.size == typeHintFormats.size, "Duplicate type hints in the passed typeHintFormats") override def writes(obj: A): JsValue = { val formatOpt = typeHintFormats.find(_.canWrite(obj)) formatOpt match { case Some(typedFormat) => typedFormat.uncheckedWrites(typeHintKey, obj) case None => sys.error( s""" |No json format found for class of runtime type ${obj.getClass} |There where TypeHintFormats defined for the following typeValues: ${typeHintFormats.map(_.typeHint)} |Did you pass a TypeHintFormat for the type ${obj.getClass} to the TaggedFormats?""".stripMargin ) } } def reads(json: JsValue): JsResult[A] = { val typeHintOpt = (json \ typeHintKey).asOpt[String] typeHintOpt match { case None => JsError( s"Expected a field named $typeHintKey in the json to use as typeHint. Now I do not now what Format to use to read the json." ) case Some(typeHint) => val formatOpt = typeHintFormats.find(_.typeHint == typeHint) formatOpt match { case Some(typedFormat) => typedFormat.reads(json) case None => JsError( s""" |No json format found for the json with typeHint $typeHint |There where TypeHintFormats defined for the following typeHints: ${typeHintFormats.map(_.typeHint)} |Did you pass a TypeHintFormat for the type $typeHint to the TaggedFormats?""".stripMargin ) } } } def ++[U >: A, B <: U](that: TypeHintFormat[B]): TypeHintFormat[U] = { require(this.typeHintKey == that.typeHintKey, "Merged TypeHintFormats must have the same typeHintKey") val aHints = this.typeHintFormats.asInstanceOf[Seq[TypeHint[U]]] val bHints = that.typeHintFormats.asInstanceOf[Seq[TypeHint[U]]] val mergedHints = aHints ++ bHints TypeHintFormat[U](this.typeHintKey, mergedHints: _*) } } object TypeHintFormat { /** * Create a Format that will find the correct format amongst the passed formats when serialising/deserialising, * using the type hint in the TypeFormat. * The field that holds the type hint will be "_type" */ def apply[A](typedFormats: TypeHint[_ <: A]*): TypeHintFormat[A] = { TypeHintFormat[A](typeHintKey = "_type", typedFormats: _*) } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedMultipleInheritance.scala
<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedMultipleInheritance.scala<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.parsedtypes import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.parser.{ ParseContext, RamlParseException } import play.api.libs.json.{ JsArray, JsBoolean, JsString, JsValue } import io.atomicbits.scraml.ramlparser.parser.JsUtils._ import io.atomicbits.scraml.util.TryUtils import io.atomicbits.scraml.util.TryUtils._ import scala.util.{ Failure, Success, Try } /** * Created by peter on 1/11/16. */ case class ParsedMultipleInheritance(parents: Set[ParsedTypeReference], properties: ParsedProperties, requiredProperties: List[String] = List.empty, typeParameters: List[String] = List.empty, // unused for now typeDiscriminator: Option[String] = None, // unused for now typeDiscriminatorValue: Option[String] = None, // unused for now required: Option[Boolean] = None, model: TypeModel = RamlModel, id: Id = ImplicitId) extends NonPrimitiveType with AllowedAsObjectField { override def updated(updatedId: Id): ParsedMultipleInheritance = copy(id = updatedId) override def asTypeModel(typeModel: TypeModel): ParsedType = { val updatedProperties = properties.map { property => property.copy(propertyType = TypeRepresentation(property.propertyType.parsed.asTypeModel(typeModel))) } copy(model = typeModel, parents = parents.map(_.asTypeModel(typeModel)), properties = updatedProperties) } def asRequired = copy(required = Some(true)) } object ParsedMultipleInheritance { def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[ParsedMultipleInheritance]] = { def processParentReferences(parents: Seq[JsValue]): Option[Try[Set[ParsedTypeReference]]] = { val parentRefs = parents.collect { case JsString(parentRef) => ParsedType(parentRef) } val typeReferences = parentRefs.collect { case Success(typeReference: ParsedTypeReference) => Success(typeReference) case Success(unionType: ParsedUnionType) => Failure( RamlParseException(s"We do not yet support multiple inheritance where one of the parents is a union type expression.") ) } val triedTypeReferences: Try[Seq[ParsedTypeReference]] = accumulate(typeReferences) if (typeReferences.size > 1) Some(triedTypeReferences.map(_.toSet)) else None } // Process the id val id: Id = JsonSchemaIdExtractor(json) val model: TypeModel = TypeModel(json) // Process the properties val properties: Try[ParsedProperties] = ParsedProperties((json \ "properties").toOption, model) // Process the required field val (required, requiredFields) = (json \ "required").toOption match { case Some(req: JsArray) => (None, Some(req.value.toList collect { case JsString(value) => value })) case Some(JsBoolean(b)) => (Some(b), None) case _ => (None, None) } val triedParentsOpt = (ParsedType.typeDeclaration(json), json) match { case (Some(JsArray(parentReferences)), _) => processParentReferences(parentReferences.toSeq) case (_, JsArray(parentReferences)) => processParentReferences(parentReferences.toSeq) case _ => None } triedParentsOpt.map { triedParents => TryUtils.withSuccess( triedParents, properties, Success(requiredFields.getOrElse(List.empty)), Success(List()), Success(None), Success(None), Success(required), Success(model), Success(id) )(new ParsedMultipleInheritance(_, _, _, _, _, _, _, _, _)) } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedFile.scala
<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedFile.scala /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.parsedtypes import io.atomicbits.scraml.ramlparser.model.{ Id, ImplicitId, RamlModel, TypeModel } import play.api.libs.json.{ JsString, JsValue } import io.atomicbits.scraml.ramlparser.parser.JsUtils._ import scala.util.{ Success, Try } /** * Created by peter on 26/08/16. */ case class ParsedFile(id: Id = ImplicitId, fileTypes: Option[Seq[String]] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None, required: Option[Boolean] = None) extends NonPrimitiveType with AllowedAsObjectField { def asRequired = copy(required = Some(true)) override def updated(updatedId: Id): ParsedFile = copy(id = updatedId) override def asTypeModel(typeModel: TypeModel): ParsedType = this override def model = RamlModel } case object ParsedFile { val value = "file" def unapply(json: JsValue): Option[Try[ParsedFile]] = { ParsedType.typeDeclaration(json).collect { case JsString(ParsedFile.value) => Success( ParsedFile( fileTypes = json.fieldStringListValue("fileTypes"), minLength = json.fieldIntValue("minLength"), maxLength = json.fieldIntValue("maxLength"), required = json.fieldBooleanValue("required") ) ) } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/InlineQueryparameterTest.scala
<reponame>atomicbits/scramlgen /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser import io.atomicbits.scraml.ramlparser.lookup.{ CanonicalNameGenerator, CanonicalTypeCollector } import io.atomicbits.scraml.ramlparser.model.Raml import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName import io.atomicbits.scraml.ramlparser.parser.RamlParser import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen } import org.scalatest.featurespec.AnyFeatureSpec import org.scalatest.matchers.should.Matchers._ /** * Created by peter on 6/04/17. */ class InlineQueryparameterTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll { Feature("Parsing of complex inline query parameters") { Scenario("An inline enum query parameter must be parsed, indexed and properly typed") { Given("a RAML specification with an inline enum query parameter") val defaultBasePath = List("io", "atomicbits", "raml10") val parser = RamlParser("/inlinequeryparameter/inlinequeryparameter-api.raml", "UTF-8") When("we parse the RAML spec") val raml: Raml = parser.parse.get implicit val canonicalNameGenerator: CanonicalNameGenerator = CanonicalNameGenerator(defaultBasePath) val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator) val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml) Then("we should see that the query parameter type is generated") println(canonicalLookup) canonicalLookup.get(CanonicalName.create(name = "Food", packagePath = defaultBasePath)).isDefined shouldBe true } } }
atomicbits/scramlgen
modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/typemodel/ClassName.scala
<filename>modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/typemodel/ClassName.scala /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.generator.typemodel /** * Created by peter on 7/02/17. * * A class name is the final platform-specific class name for a generated class. * It is similar to a canonical name (which is a RAML parser term in our context), but then platform specific and matching the * final fully qualified class name. */ case class ClassName(name: String, packagePath: List[String] = List.empty)
atomicbits/scramlgen
modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/RestException.scala
<reponame>atomicbits/scramlgen<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.dsl.scalaplay /** * An exception that wraps the status code and error message of a response. */ case class RestException(message: String, status: Int) extends RuntimeException(message) {} object RestException { /** * Find the last thrown RestException in the cause stack of Exceptions. */ def findRestException(exception: Throwable): Option[RestException] = { exception match { case e: RestException => Some(e) case e => val cause = getCause(e) cause match { case Some(x: RestException) => Some(x) case Some(x: Throwable) => findRestException(x) case None => None } } } private def getCause(exception: Throwable): Option[Throwable] = { if (exception.getCause != null && exception.getCause != exception) { Some(exception.getCause) } else { None } } }
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/TypeReference.scala
<reponame>atomicbits/scramlgen<gh_stars>10-100 /* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.model.canonicaltypes /** * Created by peter on 9/12/16. */ trait TypeReference extends GenericReferrable { def refers: CanonicalName def genericTypes: List[GenericReferrable] def genericTypeParameters: List[TypeParameter] } case class NonPrimitiveTypeReference(refers: CanonicalName, genericTypes: List[GenericReferrable] = List.empty, genericTypeParameters: List[TypeParameter] = List.empty) extends TypeReference case class ArrayTypeReference(genericType: GenericReferrable) extends TypeReference { val refers = ArrayType.canonicalName val genericTypes: List[GenericReferrable] = List(genericType) val genericTypeParameters: List[TypeParameter] = List(TypeParameter("T")) } object TypeReference { def apply(ttype: CanonicalType): TypeReference = ttype match { case primitive: PrimitiveType => primitive case nonPrimitive: NonPrimitiveType => NonPrimitiveTypeReference(nonPrimitive.canonicalName) case arrayType: ArrayType.type => sys.error(s"Cannot create a type reference from an array type without knowing the type of elements it contains.") } }
atomicbits/scramlgen
build.sbt
<filename>build.sbt import BuildSettings._ import Dependencies._ lazy val scramlDslScala = Project( id = "scraml-dsl-scala", base = file("modules/scraml-dsl-scala") ).settings ( projSettings(dependencies = scramlDslDepsScala ++ testDeps) ++ Seq( // Copy all source files into the artifact. (unmanagedResourceDirectories in Compile) += (scalaSource in Compile).value ) ) lazy val scramlDslJava = Project( id = "scraml-dsl-java", base = file("modules/scraml-dsl-java") // This is a pure Java project without scala versioning, // see http://stackoverflow.com/questions/8296280/use-sbt-to-build-pure-java-project // We also override the crossScalaVersions to avoid publish overwrite problems during release publishing, and because that // doesn't work (although I think it should), we also override the publishArtifact property. ).settings( projSettings(dependencies = scramlDslDepsJava ++ testDeps) ++ Seq( crossPaths := false, autoScalaLibrary := false, // Copy all source files into the artifact. (unmanagedResourceDirectories in Compile) += (javaSource in Compile).value ) ) lazy val scramlDslAndroid = Project( id = "scraml-dsl-android", base = file("modules/scraml-dsl-android") // This is a pure Java project without scala versioning, // see http://stackoverflow.com/questions/8296280/use-sbt-to-build-pure-java-project // We also override the crossScalaVersions to avoid publish overwrite problems during release publishing, and because that // doesn't work (although I think it should), we also override the publishArtifact property. ).settings( projSettings(dependencies = scramlDslDepsAndroid ++ testDeps) ++ Seq( crossPaths := false, autoScalaLibrary := false, javacOptions ++= Seq("-source", "1.7"), // Android 4 till android 7 and above are on Java 1.7 // Copy all source files into the artifact. (unmanagedResourceDirectories in Compile) += (javaSource in Compile).value ) ) lazy val scramlGenSimulation = Project( id = "scraml-gen-simulation", base = file("modules/scraml-gen-simulation") ).settings( projSettings(dependencies = scramlGeneratorDeps ++ testDeps) ) dependsOn (scramlDslScala, scramlDslJava) lazy val scramlRamlParser = Project( id = "scraml-raml-parser", base = file("modules/scraml-raml-parser") ).settings( projSettings(dependencies = scramlRamlParserDeps ++ testDeps) ) lazy val scramlGenerator = Project( id = "scraml-generator", base = file("modules/scraml-generator") ).settings( projSettings(dependencies = scramlGeneratorDeps ++ testDeps) ) dependsOn (scramlRamlParser, scramlDslScala, scramlDslJava, scramlDslAndroid) lazy val main = Project( id = "scraml-project", base = file(".") ).settings( projSettings(dependencies = allDeps), publish := ((): Unit), publishLocal := ((): Unit) ) aggregate (scramlRamlParser, scramlDslScala, scramlDslJava, scramlDslAndroid, scramlGenSimulation, scramlGenerator)
atomicbits/scramlgen
modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/CanonicalTypeCollector.scala
/* * * (C) Copyright 2018 Atomic BITS (http://atomicbits.io). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> * */ package io.atomicbits.scraml.ramlparser.lookup import io.atomicbits.scraml.ramlparser.model._ import io.atomicbits.scraml.ramlparser.model.canonicaltypes.{ CanonicalName, TypeReference } import io.atomicbits.scraml.ramlparser.model.parsedtypes._ import org.slf4j.{ Logger, LoggerFactory } /** * Created by peter on 17/12/16. * * */ case class CanonicalTypeCollector(canonicalNameGenerator: CanonicalNameGenerator) { implicit val cNGenerator: CanonicalNameGenerator = canonicalNameGenerator val indexer = ParsedTypeIndexer(canonicalNameGenerator) def collect(raml: Raml): (Raml, CanonicalLookup) = { val canonicalLookupHelper = CanonicalLookupHelper() val canonicalLookupWithIndexedParsedTypes = indexer.indexParsedTypes(raml, canonicalLookupHelper) val (ramlWithCanonicalReferences, canonicalLookupHelperWithCanonicalTypes) = collectCanonicals(raml, canonicalLookupWithIndexedParsedTypes) val canonicalLookup = CanonicalLookup(canonicalLookupHelperWithCanonicalTypes.lookupTable) (ramlWithCanonicalReferences, canonicalLookup) } /** * Collect all types in the canonical lookup helper and add the canonical references to the Raml object. */ def collectCanonicals(raml: Raml, canonicalLookupHelper: CanonicalLookupHelper): (Raml, CanonicalLookupHelper) = { // Now, we can create all canonical types and fill in all the TypeReferences in the RAML model's TypeRepresentation instances, // which are located in the BodyContent and ParsedParameter objects. val canonicalLookupWithCanonicals = transformParsedTypeIndexToCanonicalTypes(canonicalLookupHelper) val ramlUpdated = transformResourceParsedTypesToCanonicalTypes(raml, canonicalLookupWithCanonicals) (ramlUpdated, canonicalLookupWithCanonicals) } private def transformParsedTypeIndexToCanonicalTypes(canonicalLookupHelper: CanonicalLookupHelper): CanonicalLookupHelper = { canonicalLookupHelper.parsedTypeIndex.foldLeft(canonicalLookupHelper) { (canonicalLH, idWithParsedType) => val (id, parsedType) = idWithParsedType parsedType.id match { case ImplicitId => val generatedCanonicalName = canonicalNameGenerator.generate(id) val (canonicalType, updatedCanonicalLH) = ParsedToCanonicalTypeTransformer.transform(parsedType, canonicalLH, Some(generatedCanonicalName)) updatedCanonicalLH case otherId => val (canonicalType, updatedCanonicalLH) = ParsedToCanonicalTypeTransformer.transform(parsedType, canonicalLH, None) updatedCanonicalLH } } } private def transformResourceParsedTypesToCanonicalTypes(raml: Raml, canonicalLookupHelper: CanonicalLookupHelper): Raml = { def injectCanonicalTypeRepresentation(typeRepresentation: TypeRepresentation, nameSuggestion: Option[CanonicalName] = None): TypeRepresentation = { val expandedParsedType = indexer.expandRelativeToAbsoluteIds(typeRepresentation.parsed) val (genericReferrable, updatedCanonicalLH) = ParsedToCanonicalTypeTransformer.transform(expandedParsedType, canonicalLookupHelper, nameSuggestion) // We can ignore the updatedCanonicalLH here because we know this parsed type is already registered by transformParsedTypeIndexToCanonicalTypes genericReferrable match { case typeReference: TypeReference => typeRepresentation.copy(canonical = Some(typeReference)) case other => sys.error(s"We did not expect a generic type reference directly in the RAML model: ${typeRepresentation.parsed}.") } } def transformQueryString(queryString: QueryString): QueryString = { val updatedQueryStringType = injectCanonicalTypeRepresentation(queryString.queryStringType) queryString.copy(queryStringType = updatedQueryStringType) } def transformParsedParameter(parsedParameter: Parameter): Parameter = { val canonicalNameSuggestion = canonicalNameGenerator.generate(NativeId(parsedParameter.name)) val updatedParameterType = injectCanonicalTypeRepresentation(parsedParameter.parameterType, Some(canonicalNameSuggestion)) parsedParameter.copy(parameterType = updatedParameterType) } def transformBodyContent(bodyContent: BodyContent): BodyContent = { val updatedFormParameters = bodyContent.formParameters.mapValues(transformParsedParameter) val updatedBodyType = bodyContent.bodyType.map(injectCanonicalTypeRepresentation(_)) bodyContent.copy(formParameters = updatedFormParameters, bodyType = updatedBodyType) } def transformBody(body: Body): Body = { val updatedContentMap = body.contentMap.mapValues(transformBodyContent).toMap body.copy(contentMap = updatedContentMap) } def transformAction(action: Action): Action = { val updatedHeaders = action.headers.mapValues(transformParsedParameter) val updatedQueryParameters = action.queryParameters.mapValues(transformParsedParameter) val updatedQueryString = action.queryString.map(transformQueryString) val updatedBody = transformBody(action.body) val updatedResponseMap = action.responses.responseMap.mapValues { response => val updatedResponseBody = transformBody(response.body) response.copy(body = updatedResponseBody) }.toMap val updatedResponses = action.responses.copy(responseMap = updatedResponseMap) action.copy(headers = updatedHeaders, queryParameters = updatedQueryParameters, queryString = updatedQueryString, body = updatedBody, responses = updatedResponses) } def transformResource(resource: Resource): Resource = { val transformedUrlParameter = resource.urlParameter.map(transformParsedParameter) val transformedActions = resource.actions.map(transformAction) val transformedSubResources = resource.resources.map(transformResource) resource.copy(urlParameter = transformedUrlParameter, actions = transformedActions, resources = transformedSubResources) } val updatedResources = raml.resources.map(transformResource) raml.copy(resources = updatedResources) } }
dmvk/flink
flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/ExpressionsITCase.scala
<gh_stars>0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.api.scala.batch.table import java.sql.{Date, Time, Timestamp} import org.apache.flink.api.common.typeinfo.BasicTypeInfo import org.apache.flink.api.scala._ import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase.TableConfigMode import org.apache.flink.api.scala.table._ import org.apache.flink.api.table.codegen.CodeGenException import org.apache.flink.api.table.expressions.Null import org.apache.flink.api.table.{Row, TableEnvironment, ValidationException} import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode import org.apache.flink.test.util.TestBaseUtils import org.junit.Assert._ import org.junit._ import org.junit.runner.RunWith import org.junit.runners.Parameterized import scala.collection.JavaConverters._ @RunWith(classOf[Parameterized]) class ExpressionsITCase( mode: TestExecutionMode, configMode: TableConfigMode) extends TableProgramsTestBase(mode, configMode) { @Test def testArithmetic(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val t = env.fromElements((5, 10)).toTable(tEnv, 'a, 'b) .select('a - 5, 'a + 5, 'a / 2, 'a * 2, 'a % 2, -'a) val expected = "0,10,2,10,1,-5" val results = t.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testLogic(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val t = env.fromElements((5, true)).toTable(tEnv, 'a, 'b) .select('b && true, 'b && false, 'b || false, !'b) val expected = "true,false,true,false" val results = t.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testComparisons(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val t = env.fromElements((5, 5, 4)).toTable(tEnv, 'a, 'b, 'c) .select('a > 'c, 'a >= 'b, 'a < 'c, 'a.isNull, 'a.isNotNull) val expected = "true,true,false,false,true" val results = t.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testCaseInsensitiveForAs(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val t = env.fromElements((3, 5.toByte)).toTable(tEnv, 'a, 'b) .groupBy("a").select("a, a.count As cnt") val expected = "3,1" val results = t.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testNullLiteral(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val t = env.fromElements((1, 0)).toTable(tEnv, 'a, 'b) .select( 'a, 'b, Null(BasicTypeInfo.INT_TYPE_INFO), Null(BasicTypeInfo.STRING_TYPE_INFO) === "") try { val ds = t.toDataSet[Row] if (!config.getNullCheck) { fail("Exception expected if null check is disabled.") } val results = ds.collect() val expected = "1,0,null,null" TestBaseUtils.compareResultAsText(results.asJava, expected) } catch { case e: CodeGenException => if (config.getNullCheck) { throw e } } } @Test def testIf(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val t = env.fromElements((5, true)).toTable(tEnv, 'a, 'b) .select( ('b && true).?("true", "false"), false.?("true", "false"), true.?(true.?(true.?(10, 4), 4), 4)) val expected = "true,false,10" val results = t.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test(expected = classOf[ValidationException]) def testIfInvalidTypes(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val t = env.fromElements((5, true)).toTable(tEnv, 'a, 'b) .select(('b && true).?(5, "false")) val expected = "true,false,3,10" val results = t.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testAdvancedDataTypes(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val t = env .fromElements(( BigDecimal("78.454654654654654").bigDecimal, BigDecimal("4E+9999").bigDecimal, Date.valueOf("1984-07-12"), Time.valueOf("14:34:24"), Timestamp.valueOf("1984-07-12 14:34:24"))) .toTable(tEnv, 'a, 'b, 'c, 'd, 'e) .select('a, 'b, 'c, 'd, 'e, BigDecimal("11.2"), BigDecimal("11.2").bigDecimal, Date.valueOf("1984-07-12"), Time.valueOf("14:34:24"), Timestamp.valueOf("1984-07-12 14:34:24")) val expected = "78.454654654654654,4E+9999,1984-07-12,14:34:24,1984-07-12 14:34:24.0," + "11.2,11.2,1984-07-12,14:34:24,1984-07-12 14:34:24.0" val results = t.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } }
dmvk/flink
flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/call.scala
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.api.table.expressions import org.apache.calcite.rex.RexNode import org.apache.calcite.tools.RelBuilder import org.apache.flink.api.table.UnresolvedException import org.apache.flink.api.table.validate.{ExprValidationResult, ValidationFailure} /** * General expression for unresolved function calls. The function can be a built-in * scalar function or a user-defined scalar function. */ case class Call(functionName: String, args: Seq[Expression]) extends Expression { override private[flink] def children: Seq[Expression] = args override private[flink] def toRexNode(implicit relBuilder: RelBuilder): RexNode = { throw new UnresolvedException(s"trying to convert UnresolvedFunction $functionName to RexNode") } override def toString = s"\\$functionName(${args.mkString(", ")})" override private[flink] def resultType = throw new UnresolvedException(s"calling resultType on UnresolvedFunction $functionName") override private[flink] def validateInput(): ExprValidationResult = ValidationFailure(s"Unresolved function call: $functionName") }
dmvk/flink
flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/sql/SetOperatorsITCase.scala
<reponame>dmvk/flink /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.api.scala.batch.sql import org.apache.flink.api.scala._ import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase.TableConfigMode import org.apache.flink.api.scala.table._ import org.apache.flink.api.scala.util.CollectionDataSets import org.apache.flink.api.table.{Row, TableEnvironment} import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode import org.apache.flink.test.util.TestBaseUtils import org.junit._ import org.junit.runner.RunWith import org.junit.runners.Parameterized import scala.collection.JavaConverters._ import scala.collection.mutable import scala.util.Random @RunWith(classOf[Parameterized]) class SetOperatorsITCase( mode: TestExecutionMode, configMode: TableConfigMode) extends TableProgramsTestBase(mode, configMode) { @Test def testUnionAll(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT c FROM t1 UNION ALL (SELECT c FROM t2)" val ds1 = CollectionDataSets.getSmall3TupleDataSet(env) val ds2 = CollectionDataSets.getSmall3TupleDataSet(env) tEnv.registerDataSet("t1", ds1, 'a, 'b, 'c) tEnv.registerDataSet("t2", ds2, 'a, 'b, 'c) val result = tEnv.sql(sqlQuery) val expected = "Hi\n" + "Hello\n" + "Hello world\n" + "Hi\n" + "Hello\n" + "Hello world\n" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testUnion(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT c FROM t1 UNION (SELECT c FROM t2)" val ds1 = CollectionDataSets.getSmall3TupleDataSet(env) val ds2 = CollectionDataSets.getSmall3TupleDataSet(env) tEnv.registerDataSet("t1", ds1, 'a, 'b, 'c) tEnv.registerDataSet("t2", ds2, 'a, 'b, 'c) val result = tEnv.sql(sqlQuery) val expected = "Hi\n" + "Hello\n" + "Hello world\n" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testUnionWithFilter(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT c FROM (" + "SELECT * FROM t1 UNION ALL (SELECT a, b, c FROM t2))" + "WHERE b < 2" val ds1 = CollectionDataSets.getSmall3TupleDataSet(env) val ds2 = CollectionDataSets.get5TupleDataSet(env) tEnv.registerDataSet("t1", ds1, 'a, 'b, 'c) tEnv.registerDataSet("t2", ds2, 'a, 'b, 'd, 'c, 'e) val result = tEnv.sql(sqlQuery) val expected = "Hi\n" + "Hallo\n" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testUnionWithAggregation(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT count(c) FROM (" + "SELECT * FROM t1 UNION ALL (SELECT a, b, c FROM t2))" val ds1 = CollectionDataSets.getSmall3TupleDataSet(env) val ds2 = CollectionDataSets.get5TupleDataSet(env) tEnv.registerDataSet("t1", ds1, 'a, 'b, 'c) tEnv.registerDataSet("t2", ds2, 'a, 'b, 'd, 'c, 'e) val result = tEnv.sql(sqlQuery) val expected = "18" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testExcept(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT c FROM t1 EXCEPT (SELECT c FROM t2)" val ds1 = CollectionDataSets.getSmall3TupleDataSet(env) val ds2 = env.fromElements((1, 1L, "Hi")) tEnv.registerDataSet("t1", ds1, 'a, 'b, 'c) tEnv.registerDataSet("t2", ds2, 'a, 'b, 'c) val result = tEnv.sql(sqlQuery) val expected = "Hello\n" + "Hello world\n" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Ignore // calcite sql parser doesn't support EXCEPT ALL def testExceptAll(): Unit = { val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT c FROM t1 EXCEPT ALL SELECT c FROM t2" val data1 = new mutable.MutableList[Int] data1 += (1, 1, 1, 2, 2) val data2 = new mutable.MutableList[Int] data2 += (1, 2, 2, 3) val ds1 = env.fromCollection(data1) val ds2 = env.fromCollection(data2) tEnv.registerDataSet("t1", ds1, 'c) tEnv.registerDataSet("t2", ds2, 'c) val result = tEnv.sql(sqlQuery) val expected = "1\n1" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testExceptWithFilter(): Unit = { val env = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT c FROM (" + "SELECT * FROM t1 EXCEPT (SELECT a, b, c FROM t2))" + "WHERE b < 2" val ds1 = CollectionDataSets.getSmall3TupleDataSet(env) val ds2 = CollectionDataSets.get5TupleDataSet(env) tEnv.registerDataSet("t1", ds1, 'a, 'b, 'c) tEnv.registerDataSet("t2", ds2, 'a, 'b, 'd, 'c, 'e) val result = tEnv.sql(sqlQuery) val expected = "Hi\n" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testIntersect(): Unit = { val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT c FROM t1 INTERSECT SELECT c FROM t2" val ds1 = CollectionDataSets.getSmall3TupleDataSet(env) val data = new mutable.MutableList[(Int, Long, String)] data.+=((1, 1L, "Hi")) data.+=((2, 2L, "Hello")) data.+=((2, 2L, "Hello")) data.+=((3, 2L, "Hello world!")) val ds2 = env.fromCollection(Random.shuffle(data)) tEnv.registerDataSet("t1", ds1, 'a, 'b, 'c) tEnv.registerDataSet("t2", ds2, 'a, 'b, 'c) val result = tEnv.sql(sqlQuery) val expected = "Hi\n" + "Hello\n" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Ignore // calcite sql parser doesn't support INTERSECT ALL def testIntersectAll(): Unit = { val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT c FROM t1 INTERSECT ALL SELECT c FROM t2" val data1 = new mutable.MutableList[Int] data1 += (1, 1, 1, 2, 2) val data2 = new mutable.MutableList[Int] data2 += (1, 2, 2, 3) val ds1 = env.fromCollection(data1) val ds2 = env.fromCollection(data2) tEnv.registerDataSet("t1", ds1, 'c) tEnv.registerDataSet("t2", ds2, 'c) val result = tEnv.sql(sqlQuery) val expected = "1\n2\n2" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } @Test def testIntersectWithFilter(): Unit = { val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment val tEnv = TableEnvironment.getTableEnvironment(env, config) val sqlQuery = "SELECT c FROM ((SELECT * FROM t1) INTERSECT (SELECT * FROM t2)) WHERE a > 1" val ds1 = CollectionDataSets.getSmall3TupleDataSet(env) val ds2 = CollectionDataSets.get3TupleDataSet(env) tEnv.registerDataSet("t1", ds1, 'a, 'b, 'c) tEnv.registerDataSet("t2", ds2, 'a, 'b, 'c) val result = tEnv.sql(sqlQuery) val expected = "Hello\n" + "Hello world\n" val results = result.toDataSet[Row].collect() TestBaseUtils.compareResultAsText(results.asJava, expected) } }
dmvk/flink
flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableEnvironment.scala
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.api.table import java.util.concurrent.atomic.AtomicInteger import org.apache.calcite.config.Lex import org.apache.calcite.plan.RelOptPlanner import org.apache.calcite.rel.`type`.RelDataType import org.apache.calcite.schema.SchemaPlus import org.apache.calcite.schema.impl.AbstractTable import org.apache.calcite.sql.parser.SqlParser import org.apache.calcite.tools.{FrameworkConfig, Frameworks} import org.apache.flink.api.common.typeinfo.{AtomicType, TypeInformation} import org.apache.flink.api.java.table.{BatchTableEnvironment => JavaBatchTableEnv, StreamTableEnvironment => JavaStreamTableEnv} import org.apache.flink.api.java.typeutils.{PojoTypeInfo, TupleTypeInfo} import org.apache.flink.api.java.{ExecutionEnvironment => JavaBatchExecEnv} import org.apache.flink.api.scala.table.{BatchTableEnvironment => ScalaBatchTableEnv, StreamTableEnvironment => ScalaStreamTableEnv} import org.apache.flink.api.scala.typeutils.CaseClassTypeInfo import org.apache.flink.api.scala.{ExecutionEnvironment => ScalaBatchExecEnv} import org.apache.flink.api.table.expressions.{Alias, Expression, UnresolvedFieldReference} import org.apache.flink.api.table.plan.cost.DataSetCostFactory import org.apache.flink.api.table.plan.schema.{RelTable, TransStreamTable} import org.apache.flink.api.table.sinks.TableSink import org.apache.flink.api.table.validate.FunctionCatalog import org.apache.flink.streaming.api.environment.{StreamExecutionEnvironment => JavaStreamExecEnv} import org.apache.flink.streaming.api.scala.{StreamExecutionEnvironment => ScalaStreamExecEnv} /** * The abstract base class for batch and stream TableEnvironments. * * @param config The configuration of the TableEnvironment */ abstract class TableEnvironment(val config: TableConfig) { // configure sql parser // we use Java lex because back ticks are easier than double quotes in programming // and cases are preserved private val parserConfig = SqlParser .configBuilder() .setLex(Lex.JAVA) .build() // the catalog to hold all registered and translated tables private val tables: SchemaPlus = Frameworks.createRootSchema(true) // the configuration to create a Calcite planner private val frameworkConfig: FrameworkConfig = Frameworks .newConfigBuilder .defaultSchema(tables) .parserConfig(parserConfig) .costFactory(new DataSetCostFactory) .typeSystem(new FlinkTypeSystem) .build // the builder for Calcite RelNodes, Calcite's representation of a relational expression tree. protected val relBuilder: FlinkRelBuilder = FlinkRelBuilder.create(frameworkConfig) // the planner instance used to optimize queries of this TableEnvironment private val planner: RelOptPlanner = relBuilder.getPlanner private val typeFactory: FlinkTypeFactory = relBuilder.getTypeFactory private val functionCatalog: FunctionCatalog = FunctionCatalog.withBuildIns // a counter for unique attribute names private val attrNameCntr: AtomicInteger = new AtomicInteger(0) /** Returns the table config to define the runtime behavior of the Table API. */ def getConfig = config /** * Registers a [[Table]] under a unique name in the TableEnvironment's catalog. * Registered tables can be referenced in SQL queries. * * @param name The name under which the table is registered. * @param table The table to register. */ def registerTable(name: String, table: Table): Unit = { // check that table belongs to this table environment if (table.tableEnv != this) { throw new ValidationException( "Only tables that belong to this TableEnvironment can be registered.") } checkValidTableName(name) table.tableEnv match { case e: BatchTableEnvironment => val tableTable = new RelTable(table.getRelNode) registerTableInternal(name, tableTable) case e: StreamTableEnvironment => val sTableTable = new TransStreamTable(table.getRelNode, true) tables.add(name, sTableTable) } } /** * Replaces a registered Table with another Table under the same name. * We use this method to replace a [[org.apache.flink.api.table.plan.schema.DataStreamTable]] * with a [[org.apache.calcite.schema.TranslatableTable]]. * * @param name Name of the table to replace. * @param table The table that replaces the previous table. */ protected def replaceRegisteredTable(name: String, table: AbstractTable): Unit = { if (isRegistered(name)) { tables.add(name, table) } else { throw new TableException(s"Table \'$name\' is not registered.") } } /** * Evaluates a SQL query on registered tables and retrieves the result as a [[Table]]. * * All tables referenced by the query must be registered in the TableEnvironment. * * @param query The SQL query to evaluate. * @return The result of the query as Table. */ def sql(query: String): Table /** * Writes a [[Table]] to a [[TableSink]]. * * @param table The [[Table]] to write. * @param sink The [[TableSink]] to write the [[Table]] to. * @tparam T The data type that the [[TableSink]] expects. */ private[flink] def writeToSink[T](table: Table, sink: TableSink[T]): Unit /** * Registers a Calcite [[AbstractTable]] in the TableEnvironment's catalog. * * @param name The name under which the table is registered. * @param table The table to register in the catalog * @throws ValidationException if another table is registered under the provided name. */ @throws[TableException] protected def registerTableInternal(name: String, table: AbstractTable): Unit = { if (isRegistered(name)) { throw new TableException(s"Table \'$name\' already exists. " + s"Please, choose a different name.") } else { tables.add(name, table) } } /** * Checks if the chosen table name is valid. * * @param name The table name to check. */ protected def checkValidTableName(name: String): Unit /** * Checks if a table is registered under the given name. * * @param name The table name to check. * @return true, if a table is registered under the name, false otherwise. */ protected def isRegistered(name: String): Boolean = { tables.getTableNames.contains(name) } protected def getRowType(name: String): RelDataType = { tables.getTable(name).getRowType(typeFactory) } /** Returns a unique temporary attribute name. */ private[flink] def createUniqueAttributeName(): String = { "TMP_" + attrNameCntr.getAndIncrement() } /** Returns the [[FlinkRelBuilder]] of this TableEnvironment. */ private[flink] def getRelBuilder: FlinkRelBuilder = { relBuilder } /** Returns the Calcite [[org.apache.calcite.plan.RelOptPlanner]] of this TableEnvironment. */ private[flink] def getPlanner: RelOptPlanner = { planner } /** Returns the [[FlinkTypeFactory]] of this TableEnvironment. */ private[flink] def getTypeFactory: FlinkTypeFactory = { typeFactory } private[flink] def getFunctionCatalog: FunctionCatalog = { functionCatalog } /** Returns the Calcite [[FrameworkConfig]] of this TableEnvironment. */ private[flink] def getFrameworkConfig: FrameworkConfig = { frameworkConfig } /** * Returns field names and field positions for a given [[TypeInformation]]. * * Field names are automatically extracted for * [[org.apache.flink.api.common.typeutils.CompositeType]]. * The method fails if inputType is not a * [[org.apache.flink.api.common.typeutils.CompositeType]]. * * @param inputType The TypeInformation extract the field names and positions from. * @tparam A The type of the TypeInformation. * @return A tuple of two arrays holding the field names and corresponding field positions. */ protected[flink] def getFieldInfo[A](inputType: TypeInformation[A]): (Array[String], Array[Int]) = { val fieldNames: Array[String] = inputType match { case t: TupleTypeInfo[A] => t.getFieldNames case c: CaseClassTypeInfo[A] => c.getFieldNames case p: PojoTypeInfo[A] => p.getFieldNames case tpe => throw new TableException(s"Type $tpe lacks explicit field naming") } val fieldIndexes = fieldNames.indices.toArray (fieldNames, fieldIndexes) } /** * Returns field names and field positions for a given [[TypeInformation]] and [[Array]] of * [[Expression]]. * * @param inputType The [[TypeInformation]] against which the [[Expression]]s are evaluated. * @param exprs The expressions that define the field names. * @tparam A The type of the TypeInformation. * @return A tuple of two arrays holding the field names and corresponding field positions. */ protected[flink] def getFieldInfo[A]( inputType: TypeInformation[A], exprs: Array[Expression]): (Array[String], Array[Int]) = { val indexedNames: Array[(Int, String)] = inputType match { case a: AtomicType[A] => if (exprs.length != 1) { throw new TableException("Table of atomic type can only have a single field.") } exprs.map { case UnresolvedFieldReference(name) => (0, name) case _ => throw new TableException("Field reference expression expected.") } case t: TupleTypeInfo[A] => exprs.zipWithIndex.map { case (UnresolvedFieldReference(name), idx) => (idx, name) case (Alias(UnresolvedFieldReference(origName), name), _) => val idx = t.getFieldIndex(origName) if (idx < 0) { throw new TableException(s"$origName is not a field of type $t") } (idx, name) case _ => throw new TableException( "Field reference expression or alias on field expression expected.") } case c: CaseClassTypeInfo[A] => exprs.zipWithIndex.map { case (UnresolvedFieldReference(name), idx) => (idx, name) case (Alias(UnresolvedFieldReference(origName), name), _) => val idx = c.getFieldIndex(origName) if (idx < 0) { throw new TableException(s"$origName is not a field of type $c") } (idx, name) case _ => throw new TableException( "Field reference expression or alias on field expression expected.") } case p: PojoTypeInfo[A] => exprs.map { case (UnresolvedFieldReference(name)) => val idx = p.getFieldIndex(name) if (idx < 0) { throw new TableException(s"$name is not a field of type $p") } (idx, name) case Alias(UnresolvedFieldReference(origName), name) => val idx = p.getFieldIndex(origName) if (idx < 0) { throw new TableException(s"$origName is not a field of type $p") } (idx, name) case _ => throw new TableException( "Field reference expression or alias on field expression expected.") } case tpe => throw new TableException( s"Source of type $tpe cannot be converted into Table.") } val (fieldIndexes, fieldNames) = indexedNames.unzip (fieldNames.toArray, fieldIndexes.toArray) } } /** * Object to instantiate a [[TableEnvironment]] depending on the batch or stream execution * environment. */ object TableEnvironment { /** * Returns a [[JavaBatchTableEnv]] for a Java [[JavaBatchExecEnv]]. * * @param executionEnvironment The Java batch ExecutionEnvironment. */ def getTableEnvironment(executionEnvironment: JavaBatchExecEnv): JavaBatchTableEnv = { new JavaBatchTableEnv(executionEnvironment, new TableConfig()) } /** * Returns a [[JavaBatchTableEnv]] for a Java [[JavaBatchExecEnv]] and a given [[TableConfig]]. * * @param executionEnvironment The Java batch ExecutionEnvironment. * @param tableConfig The TableConfig for the new TableEnvironment. */ def getTableEnvironment( executionEnvironment: JavaBatchExecEnv, tableConfig: TableConfig): JavaBatchTableEnv = { new JavaBatchTableEnv(executionEnvironment, tableConfig) } /** * Returns a [[ScalaBatchTableEnv]] for a Scala [[ScalaBatchExecEnv]]. * * @param executionEnvironment The Scala batch ExecutionEnvironment. */ def getTableEnvironment(executionEnvironment: ScalaBatchExecEnv): ScalaBatchTableEnv = { new ScalaBatchTableEnv(executionEnvironment, new TableConfig()) } /** * Returns a [[ScalaBatchTableEnv]] for a Scala [[ScalaBatchExecEnv]] and a given * [[TableConfig]]. * * @param executionEnvironment The Scala batch ExecutionEnvironment. * @param tableConfig The TableConfig for the new TableEnvironment. */ def getTableEnvironment( executionEnvironment: ScalaBatchExecEnv, tableConfig: TableConfig): ScalaBatchTableEnv = { new ScalaBatchTableEnv(executionEnvironment, tableConfig) } /** * Returns a [[JavaStreamTableEnv]] for a Java [[JavaStreamExecEnv]]. * * @param executionEnvironment The Java StreamExecutionEnvironment. */ def getTableEnvironment(executionEnvironment: JavaStreamExecEnv): JavaStreamTableEnv = { new JavaStreamTableEnv(executionEnvironment, new TableConfig()) } /** * Returns a [[JavaStreamTableEnv]] for a Java [[JavaStreamExecEnv]] and a given [[TableConfig]]. * * @param executionEnvironment The Java StreamExecutionEnvironment. * @param tableConfig The TableConfig for the new TableEnvironment. */ def getTableEnvironment( executionEnvironment: JavaStreamExecEnv, tableConfig: TableConfig): JavaStreamTableEnv = { new JavaStreamTableEnv(executionEnvironment, tableConfig) } /** * Returns a [[ScalaStreamTableEnv]] for a Scala stream [[ScalaStreamExecEnv]]. * * @param executionEnvironment The Scala StreamExecutionEnvironment. */ def getTableEnvironment(executionEnvironment: ScalaStreamExecEnv): ScalaStreamTableEnv = { new ScalaStreamTableEnv(executionEnvironment, new TableConfig()) } /** * Returns a [[ScalaStreamTableEnv]] for a Scala stream [[ScalaStreamExecEnv]]. * * @param executionEnvironment The Scala StreamExecutionEnvironment. * @param tableConfig The TableConfig for the new TableEnvironment. */ def getTableEnvironment( executionEnvironment: ScalaStreamExecEnv, tableConfig: TableConfig): ScalaStreamTableEnv = { new ScalaStreamTableEnv(executionEnvironment, tableConfig) } }
vigoo/zio-flow
zio-flow/shared/src/test/scala/zio/flow/utils/MocksForGCExample.scala
<reponame>vigoo/zio-flow package zio.flow.utils import java.net.URI import zio._ import zio.flow.GoodcoverUseCase.Policy import zio.flow.internal.ZFlowExecutor.InMemory import zio.flow.{ActivityError, Operation, OperationExecutor} object MocksForGCExample { def mockOpExec2(map: Map[URI, Any]): OperationExecutor[Console with Clock] = new OperationExecutor[Console with Clock] { override def execute[I, A](input: I, operation: Operation[I, A]): ZIO[Console with Clock, ActivityError, A] = operation match { case Operation.Http(url, _, _, _, _) => Console.printLine(s"Request to : ${url.toString}") *> ZIO.succeed(map.get(url).get.asInstanceOf[A]) case Operation.SendEmail(_, _) => Console.printLine("Sending email") *> ZIO.succeed(().asInstanceOf[A]) } } val mockInMemoryForGCExample: ZIO[Any, Nothing, InMemory[String, Clock with Console]] = Ref .make[Map[String, Ref[InMemory.State]]](Map.empty) .map(ref => InMemory( ZEnvironment(Clock.ClockLive) ++ ZEnvironment(Console.ConsoleLive), mockOpExec2(mockResponseMap), ref ) ) private val mockResponseMap: Map[URI, Any] = Map( new URI("getPolicyClaimStatus.com") -> true, new URI("getFireRiskForProperty.com") -> 0.23, new URI("isManualEvalRequired.com") -> true, new URI("createRenewedPolicy.com") -> Some(Policy("DummyPolicy")) ) }
vigoo/zio-flow
zio-flow/shared/src/main/scala/zio/flow/internal/PersistentExecutor.scala
/* * Copyright 2021-2022 <NAME> and the ZIO Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package zio.flow.internal import java.io.IOException import java.time.Duration import zio._ import zio.flow._ import zio.schema.Schema final case class PersistentExecutor( clock: Clock, durableLog: DurableLog, kvStore: KeyValueStore, opExec: OperationExecutor[Any], workflows: Ref[Map[String, Ref[PersistentExecutor.State[_, _]]]] ) extends ZFlowExecutor[String] { import PersistentExecutor._ type Erased = ZFlow[Any, Any, Any] type ErasedCont = Remote[Any] => ZFlow[Any, Any, Any] def erase(flow: ZFlow[_, _, _]): Erased = flow.asInstanceOf[Erased] def eraseCont(cont: Remote[_] => ZFlow[_, _, _]): ErasedCont = cont.asInstanceOf[ErasedCont] def eval[A](r: Remote[A]): UIO[SchemaAndValue[A]] = UIO( r.evalWithSchema.getOrElse(throw new IllegalStateException("Eval could not be reduced to Right of Either.")) ) def lit[A](a: A): Remote[A] = Remote.Literal(a, Schema.fail("It is not expected to serialize this value")) def coerceRemote[A](remote: Remote[_]): Remote[A] = remote.asInstanceOf[Remote[A]] def applyFunction[R, E, A, B](f: Remote[A] => ZFlow[R, E, B], env: SchemaAndValue[R]): ZFlow[A, E, B] = ZFlow.Apply(remoteA => f(remoteA).provide(env.toRemote)) // // // 1. Read the environment `A` => ZFlow.Input (peek the environment) // // 2. Push R onto the environment // // 3. Run the workflow returned by `f` // // state.update { state => // val cont = Instruction.handleSuccess(ZFlow.input[A]) // state.copy(stack = cont :: state.stack) // // } def getVariable(workflowId: String, variableName: String): UIO[Option[Any]] = (for { map <- workflows.get stateRef <- ZIO.fromOption(map.get(workflowId)) state <- stateRef.get value <- ZIO.fromOption(state.getVariable(variableName)) } yield value).unsome def setVariable(workflowId: String, variableName: String, value: SchemaAndValue[_]): UIO[Boolean] = (for { map <- workflows.get stateRef <- ZIO.fromOption(map.get(workflowId)) _ <- stateRef.update(state => state.copy(variables = state.variables.updated(variableName, value))) // TODO: It is time to retry a workflow that is suspended, because a variable changed. // _ <- stateRef.modify(state => (state.retry.forkDaemon, state.copy(retry = ZIO.unit))).flatten } yield true).catchAll(_ => UIO(false)) def submit[E: Schema, A: Schema](uniqueId: String, flow: ZFlow[Any, E, A]): IO[E, A] = { import zio.flow.ZFlow._ def step(ref: Ref[State[E, A]]): IO[IOException, Unit] = { def onSuccess(value: Remote[_]): IO[IOException, Unit] = ref.get.flatMap { state => state.stack match { case Nil => eval(value).flatMap { schemaAndValue => state.result .succeed(schemaAndValue.value.asInstanceOf[A]) .unit .provideEnvironment(ZEnvironment(durableLog)) } case Instruction.PopEnv :: newStack => ref.update(state => state.copy(stack = newStack, envStack = state.envStack.tail)) *> onSuccess(value) case Instruction.PushEnv(env) :: newStack => eval(env).flatMap { schemaAndValue => ref.update(state => state.copy(stack = newStack, envStack = schemaAndValue :: state.envStack)) } *> onSuccess(value) case Instruction.Continuation(_, onSuccess) :: newStack => ref.update(_.copy(current = onSuccess.provide(coerceRemote(value)), stack = newStack)) *> step(ref) case Instruction.PopFallback :: newStack => ref.update(state => state.copy(stack = newStack, tstate = state.tstate.popFallback.getOrElse(state.tstate)) ) *> onSuccess(value) //TODO : Fail in an elegant way } } def onError(value: Remote[_]): IO[IOException, Unit] = ref.get.flatMap { state => state.stack match { case Nil => eval(value).flatMap { schemaAndValue => state.result .fail(schemaAndValue.value.asInstanceOf[E]) .unit .provideEnvironment(ZEnvironment(durableLog)) } case Instruction.PopEnv :: newStack => ref.update(state => state.copy(stack = newStack, envStack = state.envStack.tail)) *> onError(value) case Instruction.PushEnv(env) :: newStack => eval(env).flatMap { schemaAndValue => ref.update(state => state.copy(stack = newStack, envStack = schemaAndValue :: state.envStack)) } *> onError(value) case Instruction.Continuation(onError, _) :: newStack => ref.update(_.copy(current = onError.provide(coerceRemote(value)), stack = newStack)) *> step(ref) case Instruction.PopFallback :: newStack => ref.update(state => state.copy(stack = newStack, tstate = state.tstate.popFallback.getOrElse(state.tstate)) ) *> onError(value) //TODO : Fail in an elegant way } } ref.get.flatMap(state => state.current match { case Return(value) => onSuccess(value) case Now => clock.instant.flatMap { currInstant => onSuccess(coerceRemote(lit(currInstant))) } case Input() => ref.get.flatMap { state => onSuccess(state.currentEnvironment.toRemote) } case WaitTill(instant) => val wait = for { start <- clock.instant end <- eval(instant).map(_.value) _ <- clock.sleep(Duration.between(start, end)) } yield () wait *> onSuccess(()) case Modify(svar, f0) => def deserializeDurablePromise(bytes: Chunk[Byte]): DurablePromise[_, _] = ??? // TODO: implement deserialization of durable promise def resume[A](variableName: String, oldValue: A, newValue: A): UIO[Unit] = if (oldValue == newValue) ZIO.unit else kvStore .scanAll(s"_zflow_suspended_workflows_readVar_$variableName") .foreach { case (_, value) => val durablePromise = deserializeDurablePromise(value) durablePromise .asInstanceOf[DurablePromise[Nothing, Unit]] .succeed(()) .provideEnvironment(ZEnvironment(durableLog)) } .orDie // TODO: handle errors looking up from key value store val f = f0.asInstanceOf[Remote[Any] => Remote[(A, Any)]] val a: ZIO[Any, Nothing, A] = for { vRefTuple <- eval(svar).map(_.value.asInstanceOf[(String, Ref[Any])]) value <- vRefTuple._2.get tuple <- eval(f(lit(value))).map(_.value) _ <- vRefTuple._2.set(tuple._2) _ <- ref.update(_.addReadVar(vRefTuple._1)) _ <- resume(vRefTuple._1, value, tuple._1) } yield tuple._1 a.flatMap { r => onSuccess(r) } case apply @ Apply(_) => ref.update { state => val env = state.currentEnvironment state.copy(current = apply.lambda(env.toRemote.asInstanceOf[Remote[apply.ValueA]])) } *> step(ref) case fold @ Fold(_, _, _) => ref.update { state => val cont = Instruction.Continuation(fold.ifError, fold.ifSuccess) state.copy(current = fold.value, stack = cont :: state.stack) } *> step(ref) case RunActivity(input, activity) => val a = for { inp <- eval(input) output <- opExec.execute(inp.value, activity.operation) _ <- ref.update(_.addCompensation(activity.compensate.provide(lit(output)))) } yield output a.foldZIO( error => onError(lit(error)), success => onSuccess(lit(success)) ) case Transaction(flow) => val env = state.currentEnvironment.value for { _ <- ref.update( _.enterTransaction(flow.provide(lit(env.asInstanceOf))) ) // TODO : Casting to Nothing will fail _ <- ref.update(_.copy(current = flow)) _ <- step(ref) } yield () case Ensuring(flow, finalizer) => ref.get.flatMap { state => val cont = Instruction.Continuation[Any, Any, Any]( ZFlow.input[Any].flatMap(e => finalizer *> ZFlow.fail(e)), ZFlow.input[Any].flatMap(a => finalizer *> ZFlow.succeed(a)) ) ref.update(_.copy(current = flow, stack = cont :: state.stack)) *> step(ref) } case Unwrap(remote) => (for { evaluatedFlow <- eval(remote) _ <- ref.update(_.copy(current = evaluatedFlow.value)) } yield ()) *> step(ref) case Fork(workflow) => val fiber = for { _ <- ref.update(_.copy(current = workflow)) f <- step(ref).fork } yield f fiber.flatMap(f => onSuccess(f.asInstanceOf)) case Timeout(flow, duration) => ref.get.flatMap { state => for { d <- eval(duration).map(_.value) output <- ref.update(_.copy(current = flow)) *> step(ref).timeout(d).provideEnvironment(ZEnvironment(clock)) _ <- output match { case Some(value) => state.result.succeed(value.asInstanceOf).provideEnvironment(ZEnvironment(durableLog)) case None => state.result.succeed(().asInstanceOf).provideEnvironment(ZEnvironment(durableLog)) } } yield () } case Provide(value, flow) => eval(value).flatMap { schemaAndValue => ref.update(state => state.copy( current = flow, stack = Instruction.PopEnv :: state.stack, envStack = schemaAndValue :: state.envStack ) ) } *> step(ref) case Die => ZIO.die(new IllegalStateException("Could not evaluate ZFlow")) case RetryUntil => def storeSuspended( readVars: Set[String], durablePromise: DurablePromise[Nothing, Unit] ): IO[IOException, Unit] = { def namespace(readVar: String): String = s"_zflow_suspended_workflows_readVar_$readVar" def key(durablePromise: DurablePromise[Nothing, Unit]): Chunk[Byte] = Chunk.fromArray(durablePromise.promiseId.getBytes) def value(durablePromise: DurablePromise[Nothing, Unit]): Chunk[Byte] = ??? // TODO : Implement serialization of DurablePromise ZIO.foreachDiscard(readVars)(readVar => kvStore.put(namespace(readVar), key(durablePromise), value(durablePromise)) ) } ref.modify { state => state.tstate match { case TState.Empty => ZIO.unit -> state.copy(current = ZFlow.unit) case transaction @ TState.Transaction(_, _, _, fallback :: fallbacks) => val tstate = transaction.copy(fallbacks = fallbacks) ZIO.unit -> state.copy(current = fallback, tstate = tstate) case TState.Transaction(_, readVars, _, Nil) => val durablePromise = DurablePromise.make[Nothing, Unit]( s"_zflow_workflow_${state.workflowId}_durablepromise_${state.promiseIdCounter}" ) storeSuspended(readVars, durablePromise) *> durablePromise .awaitEither(Schema.fail("nothing schema"), Schema[Unit]) .provideEnvironment(ZEnvironment(durableLog)) -> state.copy( current = ZFlow.unit, compileStatus = PersistentCompileStatus.Suspended, promiseIdCounter = state.promiseIdCounter + 1 ) } }.flatten *> step(ref) case OrTry(left, right) => for { state <- ref.get _ <- state.tstate.addFallback(erase(right).provide(state.currentEnvironment.toRemote)) match { case None => ZIO.dieMessage("The OrTry operator can only be used inside transactions.") case Some(tstate) => ref.set( state.copy(current = left, tstate = tstate, stack = Instruction.PopFallback :: state.stack) ) *> step(ref) } } yield () case Await(execFlow) => val joined = for { execflow <- eval(execFlow).map(_.asInstanceOf[Fiber[E, A]]) result <- execflow.join } yield result joined.foldZIO( error => onError(lit(error)), success => onSuccess(success) ) case Interrupt(execFlow) => val interrupt = for { exec <- eval(execFlow).map(_.asInstanceOf[Fiber[E, A]]) exit <- exec.interrupt } yield exit.toEither interrupt.flatMap { case Left(error) => onError(lit(error)) case Right(success) => onSuccess(success) } case Fail(error) => onError(error) case NewVar(name, initial) => val variable = for { schemaAndValue <- eval(initial) vref <- Ref.make(schemaAndValue.value.asInstanceOf[A]) _ <- ref.update(_.addVariable(name, schemaAndValue)) } yield vref variable.flatMap(vref => onSuccess(lit((name, vref)))) case Iterate(initial, step0, predicate) => ref.modify { state => val tempVarCounter = state.tempVarCounter val tempVarName = s"_zflow_tempvar_${tempVarCounter}" def iterate[R, E, A]( step: Remote[A] => ZFlow[R, E, A], predicate: Remote[A] => Remote[Boolean], stateVar: Remote[Variable[A]], boolRemote: Remote[Boolean] ): ZFlow[R, E, A] = ZFlow.ifThenElse(boolRemote)( stateVar.get.flatMap { a => step(a).flatMap { a => stateVar.set(a).flatMap { _ => val boolRemote = predicate(a) iterate(step, predicate, stateVar, boolRemote) } } }, stateVar.get ) val zFlow = for { stateVar <- ZFlow.newVar(tempVarName, initial) stateValue <- stateVar.get boolRemote <- predicate(stateValue) _ <- ZFlow.log(s"stateValue = $stateValue") _ <- ZFlow.log(s"boolRemote = $boolRemote") _ <- ZFlow.log(s"boolRemote = $boolRemote") stateValue <- iterate(step0, predicate, stateVar, boolRemote) } yield stateValue val updatedState = state.copy(current = zFlow, tempVarCounter = tempVarCounter + 1) step(ref) -> updatedState }.flatten case Log(message) => val log = Console.printLine(message).provideLayer(Console.live) log *> onSuccess(()) } ) } val durablePromise = DurablePromise.make[E, A](uniqueId + "_result") val state = State(uniqueId, flow, TState.Empty, Nil, Map(), durablePromise, Nil, 0, 0, Nil, PersistentCompileStatus.Running) (for { ref <- Ref.make[State[E, A]](state) _ <- step(ref) result <- state.result.awaitEither.provideEnvironment(ZEnvironment(durableLog)) } yield result).orDie.absolve } } object PersistentExecutor { sealed trait Instruction object Instruction { case object PopEnv extends Instruction final case class PushEnv(env: Remote[_]) extends Instruction final case class Continuation[A, E, B](onError: ZFlow[E, E, B], onSuccess: ZFlow[A, E, B]) extends Instruction case object PopFallback extends Instruction } def make( opEx: OperationExecutor[Any] ): ZLayer[Clock with DurableLog with KeyValueStore, Nothing, ZFlowExecutor[String]] = ( for { durableLog <- ZIO.service[DurableLog] kvStore <- ZIO.service[KeyValueStore] clock <- ZIO.service[Clock] ref <- Ref.make[Map[String, Ref[PersistentExecutor.State[_, _]]]](Map.empty) } yield PersistentExecutor(clock, durableLog, kvStore, opEx, ref) ).toLayer final case class State[E, A]( workflowId: String, current: ZFlow[_, _, _], tstate: TState, stack: List[Instruction], variables: Map[String, SchemaAndValue[ _ ]], //TODO : change the _ to SchemaAndValue[_]. may not get compile error from this change. result: DurablePromise[E, A], envStack: List[SchemaAndValue[_]], tempVarCounter: Int, promiseIdCounter: Int, retry: List[FlowDurablePromise[_, _]], compileStatus: PersistentCompileStatus ) { def currentEnvironment: SchemaAndValue[_] = envStack.headOption.getOrElse(SchemaAndValue[Unit](Schema[Unit], ())) def pushEnv(schemaAndValue: SchemaAndValue[_]): State[E, A] = copy(envStack = schemaAndValue :: envStack) def pushInstruction(instruction: Instruction): State[E, A] = copy(stack = instruction :: stack) def addCompensation(newCompensation: ZFlow[Any, ActivityError, Any]): State[E, A] = copy(tstate = tstate.addCompensation(newCompensation)) def addReadVar(name: String): State[E, A] = copy(tstate = tstate.addReadVar(name)) def addVariable(name: String, value: SchemaAndValue[Any]): State[E, A] = copy(variables = variables + (name -> value)) def enterTransaction(flow: ZFlow[Any, _, _]): State[E, A] = copy(tstate = tstate.enterTransaction(flow)) def getTransactionFlow: Option[ZFlow[Any, _, _]] = tstate match { case TState.Empty => None case TState.Transaction(flow, _, _, _) => Some(flow) } def addRetry(flowDurablePromise: FlowDurablePromise[_, _]): State[E, A] = copy(retry = flowDurablePromise :: retry) def setSuspended(): State[E, A] = copy(compileStatus = PersistentCompileStatus.Suspended) def getVariable(name: String): Option[SchemaAndValue[_]] = variables.get(name) //TODO scala map function // private lazy val lookupName: Map[Any, String] = // variables.map((t: (String, _)) => t._2 -> t._1) } } sealed trait TState { self => def addCompensation(newCompensation: ZFlow[Any, ActivityError, Any]): TState = self match { case TState.Empty => TState.Empty case TState.Transaction(flow, readVars, compensation, fallBacks) => TState.Transaction(flow, readVars, newCompensation *> compensation, fallBacks) //TODO : Compensation Failure semantics } def addReadVar(name: String): TState = self match { case TState.Empty => TState.Empty case TState.Transaction(flow, readVars, compensation, fallbacks) => TState.Transaction(flow, readVars + name, compensation, fallbacks) } def allVariables: Set[String] = self match { case TState.Empty => Set() case TState.Transaction(_, readVars, _, _) => readVars } def enterTransaction(flow: ZFlow[Any, _, _]): TState = self match { case TState.Empty => TState.Transaction(flow, Set(), ZFlow.unit, Nil) case _ => self } def addFallback(zflow: ZFlow[Any, _, _]): Option[TState] = self match { case TState.Empty => None case tstate @ TState.Transaction(_, _, _, fallbacks) => Some(tstate.copy(fallbacks = zflow :: fallbacks)) } def popFallback: Option[TState] = self match { case TState.Empty => None case tstate @ TState.Transaction(_, _, _, fallbacks) => Some(tstate.copy(fallbacks = fallbacks.drop(1))) } } object TState { case object Empty extends TState final case class Transaction( flow: ZFlow[Any, _, _], readVars: Set[String], compensation: ZFlow[Any, ActivityError, Any], fallbacks: List[ZFlow[Any, _, _]] ) extends TState } final case class FlowDurablePromise[E, A](flow: ZFlow[Any, E, A], promise: DurablePromise[E, A]) sealed trait PersistentCompileStatus object PersistentCompileStatus { case object Running extends PersistentCompileStatus case object Done extends PersistentCompileStatus case object Suspended extends PersistentCompileStatus }
vigoo/zio-flow
zio-flow/shared/src/main/scala/zio/flow/internal/DurablePromise.scala
/* * Copyright 2021-2022 <NAME> and the ZIO Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package zio.flow.internal import java.io._ import zio._ import zio.schema._ final case class DurablePromise[E, A](promiseId: String) { def awaitEither(implicit schemaE: Schema[E], schemaA: Schema[A]): ZIO[DurableLog, IOException, Either[E, A]] = DurableLog.subscribe(topic(promiseId), 0L).runHead.map(value => deserialize[E, A](value.get)) def fail(error: E)(implicit schemaE: Schema[E]): ZIO[DurableLog, IOException, Boolean] = DurableLog.append(topic(promiseId), serialize(Left(error))).map(_ == 0L) def succeed(value: A)(implicit schemaA: Schema[A]): ZIO[DurableLog, IOException, Boolean] = DurableLog.append(topic(promiseId), serialize(Right(value))).map(_ == 0L) private def deserialize[E, A](value: Chunk[Byte])(implicit schemaE: Schema[E], schemaA: Schema[A]): Either[E, A] = { val ios = new ObjectInputStream(new ByteArrayInputStream(value.toArray)) ios.readObject().asInstanceOf[Either[E, A]] } private def serialize[A](a: A)(implicit schema: Schema[A]): Chunk[Byte] = { val bf = new ByteArrayOutputStream() val oos = new ObjectOutputStream(bf) oos.writeObject(a) oos.close() Chunk.fromArray(bf.toByteArray) } private def topic(promiseId: String): String = s"_zflow_durable_promise_$promiseId" } object DurablePromise { def make[E, A](promiseId: String): DurablePromise[E, A] = DurablePromise(promiseId) }
whisklabs/chimney
project/plugins.sbt
import scala.util.Properties._ val scalaJSVersion = envOrElse("SCALAJS_VERSION", "1.1.1") addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1") addSbtPlugin("org.scala-js" % "sbt-scalajs" % scalaJSVersion) addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.3.9") addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0") addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.0.0") addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.0") addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "1.4.0") addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3")
whisklabs/chimney
chimney/src/main/scala/io/scalaland/chimney/dsl/TransformerFInto.scala
package io.scalaland.chimney.dsl import io.scalaland.chimney.TransformerFSupport import io.scalaland.chimney.internal.TransformerCfg import io.scalaland.chimney.internal.macros.{ChimneyBlackboxMacros, TransformerFIntoWhiteboxMacros} import scala.language.experimental.macros final class TransformerFInto[F[+_], From, To, C <: TransformerCfg]( val source: From, val td: TransformerFDefinition[F, From, To, C] ) extends ConfigDsl[Lambda[`C1 <: TransformerCfg` => TransformerFInto[F, From, To, C1]], C] { /** Use `value` provided here for field picked using `selector`. * * By default if `From` is missing field picked by `selector` compilation fails. * * @see [[https://scalalandio.github.io/chimney/transformers/customizing-transformers.html#providing-missing-values]] for more details * @param selector target field in `To`, defined like `_.name` * @param value constant value to use for the target field * @return [[io.scalaland.chimney.dsl.TransformerFInto]] */ def withFieldConst[T, U](selector: To => T, value: U): TransformerFInto[F, From, To, _ <: TransformerCfg] = macro TransformerFIntoWhiteboxMacros.withFieldConstImpl /** Use wrapped `value` provided here for field picked using `selector`. * * By default if `From` is missing field picked by `selector` compilation fails. * * @see [[https://scalalandio.github.io/chimney/transformers/customizing-transformers.html#providing-missing-values]] for more details * @param selector target field in `To`, defined like `_.name` * @param value constant value to use for the target field * @return [[io.scalaland.chimney.dsl.TransformerFInto]] */ def withFieldConstF[T, U](selector: To => T, value: F[U]): TransformerFInto[F, From, To, _ <: TransformerCfg] = macro TransformerFIntoWhiteboxMacros.withFieldConstFImpl /** Use `map` provided here to compute value of field picked using `selector`. * * By default if `From` is missing field picked by `selector` compilation fails. * * @see [[https://scalalandio.github.io/chimney/transformers/customizing-transformers.html#providing-missing-values]] for more details * @param selector target field in `To`, defined like `_.name` * @param map function used to compute value of the target field * @return [[io.scalaland.chimney.dsl.TransformerFInto]] */ def withFieldComputed[T, U]( selector: To => T, map: From => U ): TransformerFInto[F, From, To, _ <: TransformerCfg] = macro TransformerFIntoWhiteboxMacros.withFieldComputedImpl /** Use `map` provided here to compute wrapped value of field picked using `selector`. * * By default if `From` is missing field picked by `selector` compilation fails. * * @see [[https://scalalandio.github.io/chimney/transformers/customizing-transformers.html#providing-missing-values]] for more details * @param selector target field in `To`, defined like `_.name` * @param map function used to compute value of the target field * @return [[io.scalaland.chimney.dsl.TransformerFInto]] */ def withFieldComputedF[T, U]( selector: To => T, map: From => F[U] ): TransformerFInto[F, From, To, _ <: TransformerCfg] = macro TransformerFIntoWhiteboxMacros.withFieldComputedFImpl /** Use `selectorFrom` field in `From` to obtain the value of `selectorTo` field in `To` * * By default if `From` is missing field picked by `selectorTo` compilation fails. * * @see [[https://scalalandio.github.io/chimney/transformers/customizing-transformers.html#fields-renaming]] for more details * @param selectorFrom source field in `From`, defined like `_.originalName` * @param selectorTo target field in `To`, defined like `_.newName` * @return [[io.scalaland.chimney.dsl.TransformerFInto]] */ def withFieldRenamed[T, U]( selectorFrom: From => T, selectorTo: To => U ): TransformerFInto[F, From, To, _ <: TransformerCfg] = macro TransformerFIntoWhiteboxMacros.withFieldRenamedImpl /** Use `f` to calculate the (missing) coproduct instance when mapping one coproduct into another. * * By default if mapping one coproduct in `From` into another coproduct in `To` derivation * expects that coproducts to have matching names of its components, and for every component * in `To` field's type there is matching component in `From` type. If some component is missing * it fails compilation unless provided replacement with this operation. * * @see [[https://scalalandio.github.io/chimney/transformers/customizing-transformers.html#transforming-coproducts]] for more details * @param f function to calculate values of components that cannot be mapped automatically * @return [[io.scalaland.chimney.dsl.TransformerFInto]] */ def withCoproductInstance[Inst](f: Inst => To): TransformerInto[From, To, _ <: TransformerCfg] = macro TransformerFIntoWhiteboxMacros.withCoproductInstanceImpl /** Use `f` to calculate the (missing) wrapped coproduct instance when mapping one coproduct into another * * By default if mapping one coproduct in `From` into another coproduct in `To` derivation * expects that coproducts to have matching names of its components, and for every component * in `To` field's type there is matching component in `From` type. If some component is missing * it fails compilation unless provided replacement with this operation. * * @see [[https://scalalandio.github.io/chimney/transformers/customizing-transformers.html#transforming-coproducts]] for more details * @param f function to calculate values of components that cannot be mapped automatically * @return [[io.scalaland.chimney.dsl.TransformerFInto]] */ def withCoproductInstanceF[Inst](f: Inst => F[To]): TransformerFInto[F, From, To, _ <: TransformerCfg] = macro TransformerFIntoWhiteboxMacros.withCoproductInstanceFImpl /** Apply configured wrapped transformation in-place. * * It runs macro that tries to derive instance of `TransformerF[F, From, To]` * and immediately apply it to captured `source` value. * * It requires [[io.scalaland.chimney.TransformerFSupport]] instance for `F` to be * available in implicit scope of invocation of this method. * * When transformation can't be derived, it results with compilation error. * * @return transformed value of type `F[To]` */ def transform(implicit tfs: TransformerFSupport[F]): F[To] = macro ChimneyBlackboxMacros.transformFImpl[F, From, To, C] /** Used internally by macro. Please don't use in your code. */ def __refineTransformerDefinition[C1 <: TransformerCfg]( f: TransformerFDefinition[F, From, To, C] => TransformerFDefinition[F, From, To, C1] ): TransformerFInto[F, From, To, C1] = new TransformerFInto[F, From, To, C1](source, f(td)) }
othree-oss/butler
butler-client/src/main/scala/io/othree/butler/client/actors/CacheClientActor.scala
<reponame>othree-oss/butler package io.othree.butler.client.actors import akka.actor.Actor import akka.cluster.pubsub.DistributedPubSub import akka.cluster.pubsub.DistributedPubSubMediator.{Send, Subscribe, SubscribeAck} import akka.pattern.ask import akka.util.Timeout import com.typesafe.scalalogging.LazyLogging import io.othree.butler.client.configuration.CacheClientConfiguration import io.othree.butler.models.{EmptyCache, Gimme} import io.othree.butler.{Cache, CacheContainer} import scala.concurrent.ExecutionContext import scala.concurrent.duration._ import scala.reflect.ClassTag private[butler] class CacheClientActor[A <: Cache](cacheContainer: CacheContainer[A], cacheClientConfiguration: CacheClientConfiguration) (implicit ec: ExecutionContext, ct: ClassTag[A]) extends Actor with LazyLogging { private val system = context.system private final val TOPIC = ct.runtimeClass.getSimpleName private val mediator = DistributedPubSub(context.system).mediator mediator ! Subscribe(TOPIC, self) override def receive: Receive = { case SubscribeAck(Subscribe(`TOPIC`, None, `self`)) => askForCache(TOPIC) case Gimme => askForCache(TOPIC) case cache: A => setCache(cache) } private def askForCache(cacheTopic: String): Unit = { logger.info(s"Asking for latest cache to topic: $cacheTopic") implicit val timeout = Timeout(1 second) val future = mediator ? Send(s"/user/cache-service-$TOPIC", Gimme, localAffinity = true) future.foreach { case cache: A => setCache(cache) case EmptyCache => logger.info(s"No cache provided, waiting for ${cacheClientConfiguration.recoveryWaitTime.toSeconds} seconds to try again") system.scheduler.scheduleOnce(cacheClientConfiguration.recoveryWaitTime, self, Gimme) } future.failed.foreach { case exception: Exception => logger.error(s"Failed to get response from mediator, waiting for ${cacheClientConfiguration.recoveryWaitTime.toSeconds} seconds to try again", exception) system.scheduler.scheduleOnce(cacheClientConfiguration.recoveryWaitTime, self, Gimme) } } private def setCache(cache: A): Unit = { logger.info(s"Updating cache from topic: $TOPIC") cacheContainer.setCache(cache) } }
othree-oss/butler
butler-service/src/test/scala/io/othree/butler/ButlerServiceTest.scala
package io.othree.butler.actors import akka.actor.{ActorRef, ActorSystem} import akka.cluster.pubsub.DistributedPubSub import akka.cluster.pubsub.DistributedPubSubMediator.{Send, Subscribe, SubscribeAck} import akka.testkit.{ImplicitSender, TestKit} import io.othree.akkaok.BaseAkkaTest import io.othree.butler.configuration.CacheServiceConfiguration import io.othree.butler.models.{EmptyCache, Gimme} import io.othree.butler.{ButlerService, Cache, CacheProvider} import org.junit.runner.RunWith import org.mockito.Mockito._ import org.scalatest.junit.JUnitRunner import scala.concurrent.Future import scala.concurrent.duration._ @RunWith(classOf[JUnitRunner]) class ButlerServiceTest extends BaseAkkaTest(ActorSystem("ActorCacheTest")) with ImplicitSender { import scala.concurrent.ExecutionContext.Implicits.global case class CacheTest() extends Cache var mediator : ActorRef = _ var cacheServiceConfiguration : CacheServiceConfiguration = _ override def beforeAll(): Unit = { mediator = DistributedPubSub(system).mediator mediator ! Subscribe("CacheTest", self) expectMsgClass(classOf[SubscribeAck]) cacheServiceConfiguration = mock[CacheServiceConfiguration] when(cacheServiceConfiguration.refreshTime("CacheTest")).thenReturn(5 seconds) when(cacheServiceConfiguration.recoveryWaitTime).thenReturn(5 seconds) } override def afterAll { TestKit.shutdownActorSystem(system) } "ButlerService" when { "receiving a RefreshCache message" must { "verify that refreshCache was invoked" in { val cacheProvider = mock[CacheProvider[CacheTest]] when(cacheProvider.refreshCache()).thenReturn(Future { CacheTest() }) val butlerService = ButlerService(cacheProvider, cacheServiceConfiguration) expectMsg(CacheTest()) butlerService.refreshCache() expectMsg(CacheTest()) verify(cacheProvider, times(2)).refreshCache() butlerService.terminate() expectNoMessage(100 milliseconds) } } "the cache provider crashes" must { "not publish the current cache" in { val cacheProvider = mock[CacheProvider[CacheTest]] when(cacheProvider.refreshCache()).thenReturn(Future { throw new Exception("kapow!") }) val butlerService = ButlerService(cacheProvider, cacheServiceConfiguration) expectNoMessage() butlerService.terminate() expectNoMessage(100 milliseconds) } } "receiving a Gimme" must { "reply the cache" in { val cacheProvider = mock[CacheProvider[CacheTest]] when(cacheProvider.refreshCache()).thenReturn(Future { CacheTest() }) val butlerService = ButlerService(cacheProvider, cacheServiceConfiguration) expectMsg(CacheTest()) mediator ! Send("/user/CacheTest", Gimme, localAffinity = true) val message = receiveOne(100 milliseconds) message shouldBe CacheTest() verify(cacheProvider, times(1)).refreshCache() butlerService.terminate() expectNoMessage(100 milliseconds) } } "receiving a Gimme and the cache is not set" must { "reply with an EmptyCache" in { val cacheProvider = mock[CacheProvider[CacheTest]] when(cacheProvider.refreshCache()).thenReturn(Future { Thread.sleep(1000) throw new Exception("kapow!") }) val cacheService = ButlerService(cacheProvider, cacheServiceConfiguration) expectNoMessage() mediator ! Send("/user/CacheTest", Gimme, localAffinity = true) val message = receiveOne(100 milliseconds) message shouldBe EmptyCache verify(cacheProvider, times(1)).refreshCache() cacheService.terminate() expectNoMessage(100 milliseconds) } } } }
othree-oss/butler
butler-client/src/test/scala/io/othree/butler/client/ButlerClientTest.scala
package io.othree.butler.client import akka.actor.{Actor, ActorSystem, PoisonPill, Props} import akka.cluster.pubsub.DistributedPubSub import akka.cluster.pubsub.DistributedPubSubMediator.{Publish, Put} import akka.testkit.{ImplicitSender, TestKit, TestProbe} import io.othree.akkaok.BaseAkkaTest import io.othree.butler.Cache import io.othree.butler.client.configuration.CacheClientConfiguration import io.othree.butler.models.{EmptyCache, Gimme} import org.junit.runner.RunWith import org.mockito.Mockito._ import org.scalatest.junit.JUnitRunner import scala.concurrent.duration._ @RunWith(classOf[JUnitRunner]) class ButlerClientTest extends BaseAkkaTest(ActorSystem("ActorCacheTest")) with ImplicitSender { import scala.concurrent.ExecutionContext.Implicits.global case class CacheTest() extends Cache class WrappedTestProbe(testProbe: TestProbe) extends Actor { override def receive: Receive = { case msg: Any => testProbe.ref.forward(msg) } } override def afterAll: Unit = { TestKit.shutdownActorSystem(system) } "ButlerClient" when { "asking for the newest cache and no response is given from the mediator" must { "schedule another try" in { val testActor = TestProbe() val serviceMock = system.actorOf(Props(new WrappedTestProbe(testActor)), "cache-service-CacheTest") val mediator = DistributedPubSub(system).mediator mediator ! Put(serviceMock) val cacheClientConfiguration = mock[CacheClientConfiguration] when(cacheClientConfiguration.recoveryWaitTime).thenReturn(20 milliseconds) val client = CacheClient[CacheTest](cacheClientConfiguration) testActor.expectMsg(Gimme) //No response will be sent back, waiting for another Gimme in the retry testActor.expectMsg(Gimme) client.terminate() serviceMock ! PoisonPill } } "receiving a cached object" must { "verify that object got cached" in { val testActor = TestProbe() val serviceMock = system.actorOf(Props(new WrappedTestProbe(testActor)), "cache-service-CacheTest") val mediator = DistributedPubSub(system).mediator mediator ! Put(serviceMock) val cacheClientConfiguration = mock[CacheClientConfiguration] when(cacheClientConfiguration.recoveryWaitTime).thenReturn(20 milliseconds) val client = CacheClient[CacheTest](cacheClientConfiguration) testActor.expectMsg(Gimme) testActor.reply(CacheTest()) expectNoMessage(100 milliseconds) client.getCache() shouldBe defined client.getCache().get shouldEqual CacheTest() client.terminate() serviceMock ! PoisonPill } } "asking for cache and receiving an empty cached object" must { "schedule another try" in { val testActor = TestProbe() val serviceMock = system.actorOf(Props(new WrappedTestProbe(testActor)), "cache-service-CacheTest") val mediator = DistributedPubSub(system).mediator mediator ! Put(serviceMock) val cacheClientConfiguration = mock[CacheClientConfiguration] when(cacheClientConfiguration.recoveryWaitTime).thenReturn(100 milliseconds) val client = CacheClient[CacheTest](cacheClientConfiguration) testActor.expectMsg(Gimme) mediator ! Publish("test", None) testActor.expectMsg(Gimme) client.terminate() serviceMock ! PoisonPill } } "receiving an empty cached object" must { "schedule another try" in { val testActor = TestProbe() val serviceMock = system.actorOf(Props(new WrappedTestProbe(testActor)), "cache-service-CacheTest") val mediator = DistributedPubSub(system).mediator mediator ! Put(serviceMock) val cacheClientConfiguration = mock[CacheClientConfiguration] when(cacheClientConfiguration.recoveryWaitTime).thenReturn(20 milliseconds) val client = CacheClient[CacheTest](cacheClientConfiguration) testActor.expectMsg(Gimme) testActor.reply(EmptyCache) testActor.expectMsg(Gimme) client.terminate() serviceMock ! PoisonPill } } "confirming the topic subscription" must { "verify that a Gimme message got sent" in { val testActor = TestProbe() val serviceMock = system.actorOf(Props(new WrappedTestProbe(testActor)), "cache-service-CacheTest") val mediator = DistributedPubSub(system).mediator mediator ! Put(serviceMock) val cacheClientConfiguration = mock[CacheClientConfiguration] when(cacheClientConfiguration.recoveryWaitTime).thenReturn(20 milliseconds) val client = CacheClient[CacheTest](cacheClientConfiguration) testActor.expectMsg(Gimme) client.terminate() serviceMock ! PoisonPill } } } }
othree-oss/butler
butler-service/src/main/scala/io/othree/butler/actors/CacheActor.scala
<reponame>othree-oss/butler package io.othree.butler.actors import akka.actor.Actor import akka.cluster.pubsub.DistributedPubSub import akka.cluster.pubsub.DistributedPubSubMediator._ import com.typesafe.scalalogging.LazyLogging import io.othree.butler.configuration.CacheServiceConfiguration import io.othree.butler.models.{EmptyCache, Gimme, RefreshCache} import io.othree.butler.{Cache, CacheContainer, CacheProvider} import scala.concurrent.ExecutionContext import scala.concurrent.duration._ import scala.reflect.ClassTag private[butler] class CacheActor[A <: Cache](cacheProvider: CacheProvider[A], cacheServiceConfiguration: CacheServiceConfiguration) (implicit ec: ExecutionContext, ct: ClassTag[A]) extends Actor with LazyLogging { private val system = context.system private val cacheContainer = new CacheContainer[A] private final val TOPIC = ct.runtimeClass.getSimpleName private val mediator = DistributedPubSub(context.system).mediator logger.info(s"Adding self: ${self.path.toStringWithoutAddress} to mediator") mediator ! Put(self) system.scheduler.schedule( 0 milliseconds, cacheServiceConfiguration.refreshTime(TOPIC), self, RefreshCache) override def receive: Receive = { case RefreshCache => refreshCache() case Gimme => val latestCache = cacheContainer.getCache() if (latestCache.isDefined) { logger.info(s"Sending cache to ${sender().path.toStringWithoutAddress}") sender() ! latestCache.get } else { logger.info(s"No cache set for topic: $TOPIC") sender() ! EmptyCache } case message: Any => logger.info(s"Message $message ignored") } private def refreshCache() = { logger.info(s"Refreshing cache. Topic: $TOPIC") val futureCache = cacheProvider.refreshCache() futureCache.foreach { updatedCache => cacheContainer.setCache(updatedCache) logger.info(s"Publishing cache to topic: $TOPIC") mediator ! Publish(TOPIC, updatedCache) } futureCache.failed.foreach { case ex: Exception => logger.error(s"Failed to update cache for topic: $TOPIC", ex) system.scheduler.scheduleOnce(cacheServiceConfiguration.recoveryWaitTime, self, RefreshCache) } } }
othree-oss/butler
butler-core/src/main/scala/io/othree/butler/models/Gimme.scala
<reponame>othree-oss/butler<filename>butler-core/src/main/scala/io/othree/butler/models/Gimme.scala package io.othree.butler.models case object Gimme
othree-oss/butler
butler-client/src/test/scala/io/othree/butler/client/configuration/TSCacheClientConfigurationTest.scala
<filename>butler-client/src/test/scala/io/othree/butler/client/configuration/TSCacheClientConfigurationTest.scala<gh_stars>1-10 package io.othree.butler.client.configuration import com.typesafe.config.ConfigFactory import io.othree.aok.BaseTest import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner import scala.concurrent.duration._ @RunWith(classOf[JUnitRunner]) class TSCacheClientConfigurationTest extends BaseTest { var config: TSCacheClientConfiguration = _ override def beforeAll(): Unit = { config = new TSCacheClientConfiguration(ConfigFactory.load()) } "TSCacheClientConfiguration" when { "getting the recovery wait time" must { "returned the configured value" in { config.recoveryWaitTime shouldBe 20.seconds } } } }
othree-oss/butler
butler-client/src/main/scala/io/othree/butler/client/configuration/TSCacheClientConfiguration.scala
package io.othree.butler.client.configuration import com.typesafe.config.Config import io.othree.dna.TSConfigurationProvider import scala.concurrent.duration.{Duration, FiniteDuration} class TSCacheClientConfiguration(config: Config) extends TSConfigurationProvider(config) with CacheClientConfiguration { override def recoveryWaitTime: FiniteDuration = { val duration = Duration(getProperty("butler.cache.client.recovery-wait-time")) Some(duration).collect { case finiteDuration: FiniteDuration => finiteDuration }.get } }
othree-oss/butler
butler-core/src/main/scala/io/othree/butler/Cache.scala
<filename>butler-core/src/main/scala/io/othree/butler/Cache.scala package io.othree.butler trait Cache
othree-oss/butler
butler-core/src/main/scala/io/othree/butler/models/RefreshCache.scala
<filename>butler-core/src/main/scala/io/othree/butler/models/RefreshCache.scala<gh_stars>1-10 package io.othree.butler.models case object RefreshCache
othree-oss/butler
butler-core/src/main/scala/io/othree/butler/models/EmptyCache.scala
<filename>butler-core/src/main/scala/io/othree/butler/models/EmptyCache.scala package io.othree.butler.models case object EmptyCache
othree-oss/butler
butler-client/src/main/scala/io/othree/butler/client/ButlerClient.scala
package io.othree.butler.client import akka.actor.{ActorSystem, PoisonPill, Props} import io.othree.butler.client.actors.CacheClientActor import io.othree.butler.{Cache, CacheContainer} import io.othree.butler.client.configuration.CacheClientConfiguration import scala.concurrent.ExecutionContext import scala.reflect.ClassTag object CacheClient { def apply[A <: Cache](cacheClientConfiguration: CacheClientConfiguration) (implicit system: ActorSystem, ec: ExecutionContext, ct: ClassTag[A]): CacheClient[A] = { new CacheClient(system, cacheClientConfiguration) } } class CacheClient[A <: Cache] private(system: ActorSystem, cacheClientConfiguration: CacheClientConfiguration) (implicit ec: ExecutionContext, ct: ClassTag[A]) extends CacheContainer[A] { private final val TOPIC = ct.runtimeClass.getSimpleName private final val cacheClientActor = system.actorOf(Props(new CacheClientActor[A](this, cacheClientConfiguration)), s"cache-client-$TOPIC") def terminate(): Unit = { cacheClientActor ! PoisonPill } }
othree-oss/butler
butler-service/src/main/scala/io/othree/butler/configuration/CacheServiceConfiguration.scala
<reponame>othree-oss/butler package io.othree.butler.configuration import scala.concurrent.duration.FiniteDuration trait CacheServiceConfiguration { def refreshTime(topic: String): FiniteDuration def recoveryWaitTime: FiniteDuration }
othree-oss/butler
butler-core/src/main/scala/io/othree/butler/CacheProvider.scala
package io.othree.butler import scala.concurrent.Future trait CacheProvider[A] { def refreshCache(): Future[A] }
othree-oss/butler
butler-service/src/test/scala/io/othree/butler/configuration/TSCacheServiceConfigurationTest.scala
<reponame>othree-oss/butler package io.othree.butler.configuration import com.typesafe.config.ConfigFactory import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner import io.othree.aok.BaseTest import scala.concurrent.duration._ @RunWith(classOf[JUnitRunner]) class TSCacheServiceConfigurationTest extends BaseTest { var config: TSCacheServiceConfiguration = _ override def beforeAll(): Unit = { config = new TSCacheServiceConfiguration(ConfigFactory.load()) } "TSCacheServiceConfiguration" when { "getting the refresh time" must { "returned the configured value" in { config.refreshTime("topic") shouldBe 30.seconds } } "getting the recovery wait time" must { "returned the configured value" in { config.recoveryWaitTime shouldBe 10.seconds } } } }
othree-oss/butler
butler-core/src/main/scala/io/othree/butler/CacheContainer.scala
package io.othree.butler class CacheContainer[A <: Cache] { private var cache: Option[A] = None def getCache(): Option[A] = { cache } private[butler] def setCache(updatedCache: A) = { cache.synchronized { cache = Some(updatedCache) } } }
othree-oss/butler
butler-core/src/test/scala/io/othree/butler/CacheContainerTest.scala
<gh_stars>1-10 package io.othree.butler import io.othree.aok.BaseTest import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class CacheContainerTest extends BaseTest { case class CacheTest() extends Cache "CacheContainer" when { "getting the cache" must { "return None if it hasn't been initialized" in { val container = new CacheContainer[CacheTest] val cache = container.getCache() cache shouldBe empty } } "setting the cache" must { "set the cache to the provided value" in { val container = new CacheContainer[CacheTest] container.setCache(CacheTest()) val cache = container.getCache() cache shouldBe defined cache.get shouldEqual CacheTest() } } } }
othree-oss/butler
butler-service/src/main/scala/io/othree/butler/ButlerService.scala
<reponame>othree-oss/butler package io.othree.butler import akka.actor.{ActorRef, ActorSystem, PoisonPill, Props} import io.othree.butler.configuration.CacheServiceConfiguration import io.othree.butler.models.RefreshCache import io.othree.butler.actors.CacheActor import scala.concurrent.ExecutionContext import scala.reflect.ClassTag object ButlerService { def apply[A <: Cache](cacheProvider: CacheProvider[A], cacheServiceConfiguration: CacheServiceConfiguration) (implicit system: ActorSystem, ec: ExecutionContext, ct: ClassTag[A]): ButlerService = { val actorRef = system.actorOf(Props(new CacheActor[A](cacheProvider, cacheServiceConfiguration)), ct.runtimeClass.getSimpleName) new ButlerService(actorRef) } } class ButlerService(private val serviceActor: ActorRef) { def terminate(): Unit = { serviceActor ! PoisonPill } def refreshCache(): Unit = { serviceActor ! RefreshCache } }
othree-oss/butler
butler-service/src/main/scala/io/othree/butler/configuration/TSCacheServiceConfiguration.scala
<filename>butler-service/src/main/scala/io/othree/butler/configuration/TSCacheServiceConfiguration.scala package io.othree.butler.configuration import com.typesafe.config.Config import io.othree.dna.TSConfigurationProvider import scala.concurrent.duration.{Duration, FiniteDuration} class TSCacheServiceConfiguration(config: Config) extends TSConfigurationProvider(config) with CacheServiceConfiguration { override def refreshTime(topic: String): FiniteDuration = { val duration = Duration(getProperty(s"butler.cache.service.$topic.refresh-time")) Some(duration).collect { case finiteDuration: FiniteDuration => finiteDuration }.get } override def recoveryWaitTime: FiniteDuration = { val duration = Duration(getProperty("butler.cache.service.recovery-wait-time")) Some(duration).collect { case finiteDuration: FiniteDuration => finiteDuration }.get } }
othree-oss/butler
butler-client/src/main/scala/io/othree/butler/client/configuration/CacheClientConfiguration.scala
package io.othree.butler.client.configuration import scala.concurrent.duration.FiniteDuration trait CacheClientConfiguration { def recoveryWaitTime: FiniteDuration }
meier-christoph/scala-steward
project/Dependencies.scala
<gh_stars>0 import sbt._ import sbt.Keys._ import sbt.librarymanagement.syntax.ExclusionRule object Dependencies { val attoCore = "org.tpolecat" %% "atto-core" % "0.9.0" val bcprovJdk15to18 = "org.bouncycastle" % "bcprov-jdk15to18" % "1.68" val betterFiles = "com.github.pathikrit" %% "better-files" % "3.9.1" val betterMonadicFor = "com.olegpy" %% "better-monadic-for" % "0.3.1" val caseApp = "com.github.alexarchambault" %% "case-app" % "2.0.4" val catsEffect = "org.typelevel" %% "cats-effect" % "2.3.1" val catsCore = "org.typelevel" %% "cats-core" % "2.3.1" val catsLaws = "org.typelevel" %% "cats-laws" % catsCore.revision val circeConfig = "io.circe" %% "circe-config" % "0.8.0" val circeGeneric = "io.circe" %% "circe-generic" % "0.13.0" val circeGenericExtras = "io.circe" %% "circe-generic-extras" % "0.13.0" val circeLiteral = "io.circe" %% "circe-literal" % circeGeneric.revision val circeParser = "io.circe" %% "circe-parser" % circeGeneric.revision val circeRefined = "io.circe" %% "circe-refined" % circeGeneric.revision val commonsIo = "commons-io" % "commons-io" % "2.8.0" val coursierCore = "io.get-coursier" %% "coursier" % "2.0.9" val coursierCatsInterop = "io.get-coursier" %% "coursier-cats-interop" % coursierCore.revision val cron4sCore = "com.github.alonsodomin.cron4s" %% "cron4s-core" % "0.6.1" val disciplineMunit = "org.typelevel" %% "discipline-munit" % "1.0.4" val fs2Core = "co.fs2" %% "fs2-core" % "2.5.0" val fs2Io = "co.fs2" %% "fs2-io" % fs2Core.revision val http4sCore = "org.http4s" %% "http4s-core" % "0.21.15" val http4sCirce = "org.http4s" %% "http4s-circe" % http4sCore.revision val http4sClient = "org.http4s" %% "http4s-client" % http4sCore.revision val http4sDsl = "org.http4s" %% "http4s-dsl" % http4sCore.revision val http4sOkhttpClient = "org.http4s" %% "http4s-okhttp-client" % http4sCore.revision val kindProjector = "org.typelevel" % "kind-projector" % "0.11.3" val log4catsSlf4j = "io.chrisdavenport" %% "log4cats-slf4j" % "1.1.1" val logbackClassic = "ch.qos.logback" % "logback-classic" % "1.2.3" val jjwtApi = "io.jsonwebtoken" % "jjwt-api" % "0.11.2" val jjwtImpl = "io.jsonwebtoken" % "jjwt-impl" % jjwtApi.revision val jjwtJackson = "io.jsonwebtoken" % "jjwt-jackson" % jjwtApi.revision val millVersion = Def.setting(if (scalaBinaryVersion.value == "2.12") "0.6.3" else "0.9.4") val millScalalib = Def.setting("com.lihaoyi" %% "mill-scalalib" % millVersion.value) val monocleCore = "com.github.julien-truffaut" %% "monocle-core" % "2.1.0" val munit = "org.scalameta" %% "munit" % "0.7.20" val munitScalacheck = "org.scalameta" %% "munit-scalacheck" % munit.revision val refined = "eu.timepit" %% "refined" % "0.9.20" val refinedCats = "eu.timepit" %% "refined-cats" % refined.revision val refinedScalacheck = "eu.timepit" %% "refined-scalacheck" % refined.revision val scalacacheCaffeine = "com.github.cb372" %% "scalacache-caffeine" % "0.28.0" val scalacacheCatsEffect = "com.github.cb372" %% "scalacache-cats-effect" % scalacacheCaffeine.revision val scalacheck = "org.scalacheck" %% "scalacheck" % "1.15.2" }
tommay/spudoku-android
scala/external/src/main/scala/net/tommay/sudoku/CreaterForJava.scala
package net.tommay.sudoku import scala.util.Random // Provide a "create" function intended to be called from Java that // does all the heavy lifting like Random creation and Layout lookup // in Scala. // It's not enough to create puzzles with the right Hruristics. We // also need to ensure the puzzles can't be solved without using the // heuristics tht give them their difficulty level. object CreaterForJava { // EasyPeasy puzzles can be solved using only Heuristic.EasyPeasy. // 0m38.704s @throws(classOf[InterruptedException]) def createEasyPeasy(randomSeed: Int, layoutName: String) : (String, String) = { val createOptions = new SolverOptions( List(Heuristic.EasyPeasy), false, false) createFiltered(randomSeed, layoutName, createOptions) } // EasyPeasy and MissingOne are both subsets of Needed, but they // are the easiest subsets of Needed to find visually. The same // puzzles will be created no matter what the order is, but put // MissingOne first because it's faster. // 0m31.961s @throws(classOf[InterruptedException]) def createEasy(randomSeed: Int, layoutName: String) : (String, String) = { val createOptions = new SolverOptions( List(Heuristic.MissingOne, Heuristic.EasyPeasy), false, false) createFiltered(randomSeed, layoutName, createOptions) } // Medium puzzles require Heuristic.Needed. // 0m20.618s @throws(classOf[InterruptedException]) def createMedium(randomSeed: Int, layoutName: String) : (String, String) = { val createOptions = new SolverOptions( List(Heuristic.Needed, Heuristic.MissingOne, Heuristic.EasyPeasy), false, false) val solveOptions = new SolverOptions( List(Heuristic.MissingOne, Heuristic.EasyPeasy), false, false) createFiltered(randomSeed, layoutName, createOptions, (puzzle, solution) => // Checking for Heuristic.Needed here is a tiny win. solution.steps.exists(_.tjpe == Heuristic.Needed) && !solvableWith(puzzle, solveOptions)) } // Tricky puzzles are Easy except they require using a TrickySet. @throws(classOf[InterruptedException]) def createTricky(randomSeed: Int, layoutName: String) : (String, String) = { val createOptions = new SolverOptions( List(Heuristic.Needed, Heuristic.Forced, Heuristic.Tricky), false, false) val solveOptions = new SolverOptions( List(Heuristic.Needed, Heuristic.Forced), false, false) createFiltered(randomSeed, layoutName, createOptions, (puzzle, solution) => !solvableWith(puzzle, solveOptions)) } // Vicious puzzles have Forced cells but no Guessing. // 2m11.172s @throws(classOf[InterruptedException]) def createVicious(randomSeed: Int, layoutName: String) : (String, String) = { val createOptions = new SolverOptions( List(Heuristic.Forced, Heuristic.Needed, Heuristic.Tricky), false, false) val solveOptions = new SolverOptions( List(Heuristic.Needed, Heuristic.Tricky), false, false) createFiltered(randomSeed, layoutName, createOptions, (puzzle, solution) => // Checking for Heuristic.Forced here is a small win. solution.steps.exists(_.tjpe == Heuristic.Forced) && !solvableWith(puzzle, solveOptions)) } // Wicked puzzles require Guessing, even with all our heuristics. // 1m6.223s @throws(classOf[InterruptedException]) def createWicked(randomSeed: Int, layoutName: String) : (String, String) = { val createOptions = new SolverOptions( List(), false, true) val solveOptions = new SolverOptions( List(Heuristic.Forced, Heuristic.Needed, Heuristic.Tricky), false, false) createFiltered(randomSeed, layoutName, createOptions, (puzzle, solution) => !solvableWith(puzzle, solveOptions)) } @throws(classOf[InterruptedException]) def createFiltered( randomSeed: Int, layoutName: String, options: SolverOptions, pred: (Puzzle, Solution) => Boolean = (_, _) => true) : (String, String) = { val rnd = new Random(randomSeed) val solveFunc = Solver.solutions(options)(_) Layout.getLayout(layoutName) match { case None => ("", "") case Some(layout) => val puzzles = Creater.createStreamWithSolution(rnd, layout, solveFunc) val filteredPuzzles = puzzles.filter{case (puzzle, solution) => { println("Spudoku: Running pred") pred(puzzle, solution) } } //.drop(1000) // For testing. XXX!!! val (puzzle, solution) = filteredPuzzles.head (puzzle.toString, solution.puzzle.toString) } } def solvableWith(puzzle: Puzzle, options: SolverOptions) : Boolean = { Solver.solutions(options)(puzzle).nonEmpty } // CreaterForJava can be run independently for testing. def main(args: Array[String]) { val seed = 1 // System.currentTimeMillis.toInt val (puzzle, solved) = createWicked(seed, args(0)) println(s"$puzzle $solved") } }
tommay/spudoku-android
scala/external/src/main/scala/net/tommay/sudoku/Layout.scala
package net.tommay.sudoku /* The functions in this list take a position from 0 to 81 and return a Set of all positions that should have their colors removed together when creating a puzzle. */ object Layout { val layoutList : List[(String, Int => Set[Int])] = List( "classic (half turn)" -> classic, "quarter turn" -> quarterTurn, "mirror" -> leftRight, "double mirror" -> leftRightUpDown, "diagonal" -> diagonal, "other diagonal" -> otherDiagonal, "double diagonal" -> doubleDiagonal, "kaleidoscope" -> kaleidoscope, "identical squares" -> identicalSquares, "tumbler" -> tumbler, "barcode" -> barcode, "random" -> random ) def classic(n: Int) : Set[Int] = { Set(n, 80 - n) } def reflectLeftRight(n: Int) : Int = { val (_, col) = rowcol(n) n - col + 8 - col } def leftRight(n: Int) : Set[Int] = { Set(n, reflectLeftRight(n)) } def reflectUpDown(n: Int) : Int = { val (row, _) = rowcol(n) val rowish = row * 9 n - rowish + 72 - rowish } def leftRightUpDown(n: Int) : Set[Int] = { val leftRightSets = leftRight(n) leftRightSets ++ leftRightSets.map(reflectUpDown) } def identicalSquares(n: Int) : Set[Int] = { val col = n % 3 val row = (n / 9) % 3 val base = row*9 + col Set(0, 3, 6, 27, 30, 33, 54, 57, 60).map(base + _) } def quarterTurn(n: Int) : Set[Int] = { spinny(Set.empty, n) } def spinny(result: Set[Int], n: Int) : Set[Int] = { // Rotate n 90 degrees, add it, and recurse until we've come back // to where we started. if (result.contains(n)) { result } else { val (row, col) = rowcol(n) val rowPrime = col val colPrime = 8 - row spinny(result + n, rowPrime * 9 + colPrime) } } def random(n: Int) : Set[Int] = { Set(n) } def reflectDiagonally(n: Int) : Int = { val (row, col) = rowcol(n) val rowPrime = col val colPrime = row rowPrime * 9 + colPrime } def diagonal(n: Int) : Set[Int] = { Set(n, reflectDiagonally(n)) } def reflectOtherDiagonally(n: Int) : Int = { val (row, col) = rowcol(n) val rowPrime = 8 - col val colPrime = 8 - row rowPrime * 9 + colPrime } def otherDiagonal(n: Int) : Set[Int] = { Set(n, reflectOtherDiagonally(n)) } def doubleDiagonal(n: Int) : Set[Int] = { val diagonalSets = diagonal(n) diagonalSets ++ diagonalSets.map(reflectOtherDiagonally) } def kaleidoscope(n: Int) : Set[Int] = { quarterTurn(n) ++ quarterTurn(reflectLeftRight(n)) } def tumbler(n: Int) : Set[Int] = { val tumbled = List( Set(0, 5, 26, 51, 60, 59, 74, 45), Set(1, 14, 25, 42, 61, 68, 73, 36), Set(2, 23, 24, 33, 62, 77, 72, 27), Set(9, 4, 17, 52, 69, 58, 65, 46), Set(10, 13, 16, 43, 70, 67, 64, 37), Set(11, 22, 15, 34, 71, 76, 63, 28), Set(18, 3, 8, 53, 78, 57, 56, 47), Set(19, 12, 7, 44, 79, 66, 55, 38), Set(20, 21, 6, 35, 80, 75, 54, 29), Set(30, 32, 50, 48), Set(31, 41, 49, 39), Set(40) ) tumbled.find(_.contains(n)).getOrElse(Set.empty) } def barcode(n: Int) : Set[Int] = { val (row, col) = rowcol(n); val row0 = row - (row % 3) Set(0, 1, 2).map{n => (row0 + n) * 9 + col} } def getLayout(name: String) : Option[Iterable[Set[Int]]] = { val nameLower = name.toLowerCase layoutList.find(_._1.toLowerCase == name) match { case None => None case Some((_, func)) => val sets = (0 to 80).map(func(_)) Some(uniqBy(sets, {x:Set[Int] => x.min})) } } def getLayoutNames : Iterable[String] = { layoutList.map(_._1) } def rowcol(n: Int) : (Int, Int) = { (n / 9, n % 9) } def uniqBy[T,K](list: Iterable[T], func: T => K) : Iterable[T] = { list.groupBy(func) .values .map(_.head) } }
tommay/spudoku-android
scala/external/src/main/scala/net/tommay/sudoku/Placement.scala
package net.tommay.sudoku case class Placement( cellNumber: Int, digit: Int)
tommay/spudoku-android
scala/external/src/main/scala/net/tommay/sudoku/ExclusionSet.scala
<reponame>tommay/spudoku-android package net.tommay.sudoku // An ExclusionSet is a named List of all the cell numbers in a row, // column, or square. They're used as part of the heuristic methods // in Solver. // XXX Everything ends up being Vectors. Compare speed to List. case class ExclusionSet( name: String, cells: Set[Int]) object ExclusionSet { // An ExclusionSet for each row. val rows : Iterable[ExclusionSet] = (0 to 8).map(row) def row(n: Int) : ExclusionSet = { ExclusionSet(s"row $n", (0 to 8).map(col => n*9 + col).toSet) } // An ExclusionSet for each column. val columns : Iterable[ExclusionSet] = (0 to 8).map(column) def column(n: Int) : ExclusionSet = { ExclusionSet(s"column $n", (0 to 8).map(row => row*9 + n).toSet) } // An ExclusionSet for each square. val squares : Iterable[ExclusionSet] = (0 to 8).map(square) def square(n: Int) : ExclusionSet = { // row and col of upper left corner of square val row = n / 3 * 3 val col = n % 3 * 3 val cellNumbers = (0 to 8).map(n => (row + n / 3)*9 + (col + n % 3)).toSet ExclusionSet(s"square $n", cellNumbers) } // All ExclusionSets. val exclusionSets : Stream[ExclusionSet] = (rows ++ columns ++ squares).toStream }
tommay/spudoku-android
scala/external/src/main/scala/net/tommay/sudoku/Unknown.scala
<reponame>tommay/spudoku-android package net.tommay.sudoku case class Unknown( cellNumber: Int, row: Int, col: Int, square: Int, possible: Int) { def place(cellNumber: Int, digit: Int) : Unknown = { // Before bothering to test isExcludedBy, check whether the digit // has already been removed. This is just an optimization but // makes a big difference in Frege. if (isDigitPossible(digit)) { val other = Unknown(cellNumber) if (isExcludedBy(other)) { removeDigitFromPossible(digit) } else { this } } else { this } } def isDigitPossible(digit: Int) : Boolean = { (possible & (1 << (digit - 1))) != 0 } def removeDigitFromPossible(digit: Int) : Unknown = { this.copy(possible = possible & ~(1 << (digit - 1))) } def numPossible : Int = { Integer.bitCount(possible) } // This was replaced with lookups from a pre-computed Vector and then // an Array, but even the array was slower than the recursive List // creation, wtf. def getPossible : List[Int] = { Unknown.getPossibleList(possible) } // Returns true if this and Other are in the same row, column, or // square, else false. // An Unknown does not exclude itself. I'm not sure we actually // have to check for this in practice, but better safe than sorry. def isExcludedBy(other: Unknown) : Boolean = { (this.cellNumber != other.cellNumber) && (this.row == other.row || this.col == other.col || this.square == other.square) } // Check for equality by testing cellNumber and possible. The other fields // are functions of cellNumber. // /* instance Eq Unknown where this == that = (Unknown.cellNumber this == Unknown.cellNumber that) && (Unknown.possible this == Unknown.possible that) hashCode this = (this.cellNumber * 23) + this.possible.hashCode */ } object Unknown { // Returns a new Unknown at position cellNumber. Determine the // Unknown's row, column, and square, set all digits possible. def apply(cellNumber: Int) : Unknown = { val row = cellNumber / 9 val col = cellNumber % 9 val square = (row / 3)*3 + (col / 3) new Unknown( cellNumber = cellNumber, row = row, col = col, square = square, possible = 0x1FF) } def getPossibleList(p: Int, digit: Int = 1) : List[Int] = { if (p == 0) { List() } else { val rest = getPossibleList(p >> 1, digit + 1) if ((p & 1) != 0) { digit :: rest } else { rest } } } }
tommay/spudoku-android
scala/external/src/main/scala/net/tommay/sudoku/Creater.scala
package net.tommay.sudoku import scala.util.Random object Creater { @throws(classOf[InterruptedException]) def create( rnd: Random, layout: Iterable[Iterable[Int]], solveFunc: Puzzle => Stream[Solution]) : Puzzle = { createWithSolution(rnd, layout, solveFunc)._1 } @throws(classOf[InterruptedException]) def createWithSolution( rnd: Random, layout: Iterable[Iterable[Int]], solveFunc: Puzzle => Stream[Solution]) : (Puzzle, Solution) = { createStreamWithSolution(rnd, layout, solveFunc).head } @throws(classOf[InterruptedException]) def createStreamWithSolution( rnd: Random, layout: Iterable[Iterable[Int]], solveFunc: Puzzle => Stream[Solution]) : Stream[(Puzzle, Solution)] = { val (rndThis, rndNext) = Util.split(rnd) val (rnd1, rnd2) = Util.split(rndThis) val solvedPuzzle = randomSolvedPuzzle(rnd1) val shuffledLayout = Util.shuffle(layout, rnd2) createFromSolved(solvedPuzzle, shuffledLayout, solveFunc) #:: createStreamWithSolution(rndNext, layout, solveFunc) } // Start with a solved Puzzle and remove sets of cells (that will // result in a specific type of layout) which leave a Puzzle which // is uniquely solvable by the given solver function. @throws(classOf[InterruptedException]) def createFromSolved( puzzle: Puzzle, cellNumberLists: Iterable[Iterable[Int]], solveFunc: Puzzle => Stream[Solution]) : (Puzzle, Solution) = { val initAccum = (puzzle, Solution(puzzle, Iterable.empty)) cellNumberLists.foldLeft(initAccum) {case (accum, cellNumbers) => if (Thread.interrupted) { println("Spudoku Interrupted in createFromSolved") throw new InterruptedException } // We know accum's puzzle has only one solution. Remove // cellNumbers and check whether that's still true. val oldPuzzle = accum._1 val newPuzzle = oldPuzzle.remove(cellNumbers) solveFunc(newPuzzle) match { case Stream(solution) => // newPuzzle has only one solution, go with it. (newPuzzle, solution) case _ => // Ooops, removed too much, stick with the original. accum } } } def randomSolvedPuzzle(rnd: Random) : Puzzle = { val emptyPuzzle = Puzzle.empty val randomSolution = Solver.allRandomSolutions(rnd)(emptyPuzzle).head randomSolution.puzzle } }
tommay/spudoku-android
scala/external/src/main/scala/net/tommay/sudoku/Solve.scala
package net.tommay.sudoku import scala.util.Random object Solve { // Initializes Puzzle from the given Filename and prints out solutions // if any. def main(args: Array[String]) { val filename = args(0) val setup = getSetup(filename) val puzzle = Puzzle.fromString(setup) val rnd = new Random(2) // It is critical not to put the result of randomSolutions in a // val here because that holds onto the head even though it would // just be passed to processAndCount and the val would become dead // and collectable. Scala/JVM doesn't see it that way. // We get away with passing it to processAndCount which is recursive // so the top-level call has the head, except that Scala properly // optimizes the recursive tail call so we're ok. val count = processAndCount( Solver.randomSolutions(options, rnd)(puzzle), printSolution) println(s"There are $count solutions.") } // The heuristics, if any, to use. If useGuessing is true in // options then heuristics, if non-empty, should usually include // Forced otherwise guesses with only one possibility won't be used. val heuristics = List(Heuristic.Tricky, Heuristic.Forced) val options = new SolverOptions( heuristics = heuristics, usePermanentTrickySets = false, useGuessing = true) def processAndCount[T](list: Iterable[T], func: T => Unit, count: Int = 0) : Int = { list.headOption match { case Some(head) => func(head) processAndCount(list.tail, func, count + 1) case _ => count } } def printSolution(solution: Solution) { if (false) { solution.steps.foreach {step => println(showStep(step)) } println(solution.puzzle.toPuzzleString) } } def showStep(step: Step) : String = { step.tjpe.toString + (step.placementOption match { case Some(placement) => val (row, col) = rowcol(placement.cellNumber) s": ($row, $col) ${placement.digit}" case None => "" }) } def rowcol(n: Int) = { (n / 9, n % 9) } // Returns the contents of filename as a string with "#" comments // and whitespace deleted. The result should be a string of 81 // digits or dashes, where the digits are given by the puzzle and // the dash cells are to be solved for. def getSetup(filename: String) = { val raw = scala.io.Source.fromFile(filename).mkString val noComments = "#.*".r.replaceAllIn(raw, "") val setup = """\s+""".r.replaceAllIn(noComments, "") setup } }
tommay/spudoku-android
scala/external/src/main/scala/net/tommay/sudoku/Create.scala
package net.tommay.sudoku import scala.util.Random object Create { val doThis = doOne(_) // val solveFunc = Solver.solutions SolverOptions.noGuessing val solveFunc = Solver.solutions(SolverOptions.all)(_) def main(args: Array[String]) { args match { case Array(layoutName) => Layout.getLayout(layoutName) match { case Some(layout) => doThis(layout) case _ => showLayouts } case _ => showLayouts } } def showLayouts : Unit = { println("Valid layouts:") println(Layout.getLayoutNames.mkString(" ")) } def doOne(layout: Iterable[Iterable[Int]]) = { val rnd = Random val puzzle = Creater.create(rnd, layout, solveFunc) println(puzzle.toPuzzleString) } }