repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/Types.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.{ KeyedList, ParseContext, RamlParseException }
import play.api.libs.json.{ JsArray, JsObject, JsValue }
import scala.language.postfixOps
import scala.util.{ Failure, Success, Try }
/**
* Created by peter on 10/02/16.
*/
case class Types(typeReferences: Map[NativeId, ParsedType] = Map.empty) {
def apply(nativeId: NativeId): ParsedType = typeReferences(nativeId)
def get(nativeId: NativeId): Option[ParsedType] = typeReferences.get(nativeId)
def ++(otherTypes: Types): Types = {
Types(typeReferences ++ otherTypes.typeReferences)
}
def +(typeReference: (NativeId, ParsedType)): Types = copy(typeReferences = typeReferences + typeReference)
}
object Types {
def apply(typesJson: JsValue)(implicit parseContext: ParseContext): Try[Types] = {
def doApply(tpsJson: JsValue): Try[Types] = {
tpsJson match {
case typesJsObj: JsObject => typesJsObjToTypes(typesJsObj)
case typesJsArr: JsArray => typesJsObjToTypes(KeyedList.toJsObject(typesJsArr))
case x =>
Failure(RamlParseException(s"The types (or schemas) definition in ${parseContext.head} is malformed."))
}
}
def typesJsObjToTypes(typesJsObj: JsObject): Try[Types] = {
val tryTypes =
typesJsObj.fields.collect {
case (key: String, incl: JsValue) => parseContext.withSourceAndUrlSegments(incl)(typeObjectToType(key, incl))
}
foldTryTypes(tryTypes.toSeq)
}
def foldTryTypes(tryTypes: Seq[Try[Types]])(implicit parseContext: ParseContext): Try[Types] = {
tryTypes.foldLeft[Try[Types]](Success(Types())) {
case (Success(aggr), Success(types)) => Success(aggr ++ types)
case (Failure(eAggr), Failure(eTypes)) => Failure(RamlParseException(s"${eAggr.getMessage}\n${eTypes.getMessage}"))
case (fail @ Failure(e), _) => fail
case (_, fail @ Failure(e)) => fail
}
}
def typeObjectToType(name: String, typeDefinition: JsValue)(implicit parseContext: ParseContext): Try[Types] = {
typeDefinition match {
case ParsedType(sometype) =>
sometype.map { tp =>
val nativeId = NativeId(name)
val typeWithProperId =
(tp.id, tp.model) match {
case (ImplicitId, RamlModel) => tp.updated(nativeId)
case _ => tp
}
Types(typeReferences = Map(nativeId -> typeWithProperId))
}
case x => Failure(RamlParseException(s"Unknown type $x in ${parseContext.head}."))
}
}
parseContext.withSourceAndUrlSegments(typesJson)(doApply(typesJson))
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/BodyPart.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
import _root_.java.io.File
import _root_.java.nio.charset.Charset
/**
* Created by peter on 1/07/15.
*/
sealed trait BodyPart
/**
*
* @param name The name of the part.
* @param bytes The content of the part.
* @param contentType The optional content type.
* @param charset The optional character encoding (defaults to UTF-8).
* @param contentId The optional content id.
* @param transferEncoding The optional transfer encoding.
*/
case class ByteArrayPart(name: String,
bytes: Array[Byte],
contentType: Option[String] = None,
charset: Option[Charset] = Some(Charset.forName("UTF8")),
contentId: Option[String] = None,
transferEncoding: Option[String] = None)
extends BodyPart
/**
*
* @param name The name of the part.
* @param file The file.
* @param fileName The optional name of the file, if no name is given the name in 'file' is used.
* @param contentType The optional content type.
* @param charset The optional character encoding (defaults to UTF-8).
* @param contentId The optional content id.
* @param transferEncoding The optional transfer encoding.
*/
case class FilePart(name: String,
file: File,
fileName: Option[String] = None,
contentType: Option[String] = None,
charset: Option[Charset] = Some(Charset.forName("UTF8")),
contentId: Option[String] = None,
transferEncoding: Option[String] = None)
extends BodyPart
/**
*
* @param name The name of the part.
* @param value The content of the part.
* @param contentType The optional content type.
* @param charset The optional character encoding (defaults to UTF-8).
* @param contentId The optional content id.
* @param transferEncoding The optional transfer encoding.
*/
case class StringPart(name: String,
value: String,
contentType: Option[String] = None,
charset: Option[Charset] = Some(Charset.forName("UTF8")),
contentId: Option[String] = None,
transferEncoding: Option[String] = None)
extends BodyPart
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/InlineObjectTest.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.{ NativeId, Raml }
import io.atomicbits.scraml.ramlparser.model.canonicaltypes._
import io.atomicbits.scraml.ramlparser.model.parsedtypes.ParsedObject
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 12/03/17.
*/
class InlineObjectTest 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", "model")
val parser = RamlParser("/inlineobject/test-api.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 parsedAttributes = raml.types.typeReferences(NativeId("attributes")).asInstanceOf[ParsedObject]
val parsedAttributeMap = parsedAttributes.properties.values.head.propertyType.parsed.asInstanceOf[ParsedObject]
val attributeRequireValues = parsedAttributeMap.properties.valueMap.values.map(_.required).toList
attributeRequireValues shouldBe List(false, false, false, false)
val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml)
val attributesMapName = CanonicalName.create("AttributesMap", List("io", "atomicbits", "raml10"))
val attributesMapObj = canonicalLookup.apply(attributesMapName)
val attributesMap = attributesMapObj.asInstanceOf[ObjectType]
attributesMap.properties.values.map(_.required).toList shouldBe List(false, false, false, false)
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/transformers/ParsedTypeContext.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.transformers
import io.atomicbits.scraml.ramlparser.lookup.CanonicalLookupHelper
import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName
import io.atomicbits.scraml.ramlparser.model.parsedtypes.ParsedType
/**
* Created by peter on 23/12/16.
*/
/**
* Helper class that contains information for transforming a specific parsed type into its canonical counterpart.
*
* @param parsedType The parsed type which is the subject for this context.
* @param canonicalLookupHelper The canonical lookup helper containing all collected type information.
* @param canonicalNameOpt The optional canonical name for the given parsedType.
* @param parentNameOpt The optional canonical name for the parent of the parsedType. This variable is only present in some cases
* for json-schema type definitions.
* @param imposedTypeDiscriminator The optional type discriminator property name that was specified by a parent class
*/
case class ParsedTypeContext(parsedType: ParsedType,
canonicalLookupHelper: CanonicalLookupHelper,
canonicalNameOpt: Option[CanonicalName] = None,
parentNameOpt: Option[CanonicalName] = None,
imposedTypeDiscriminator: Option[String] = None)
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Action.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.ParsedType
import io.atomicbits.scraml.ramlparser.parser.ParseContext
import play.api.libs.json.{ JsObject, JsValue, Json }
import scala.util.{ Success, Try }
/**
* Created by peter on 10/02/16.
*/
case class Action(actionType: Method,
headers: Parameters,
queryParameters: Parameters,
body: Body,
responses: Responses,
queryString: Option[QueryString] = None,
description: Option[String] = None) // ToDo: add action description from parsed data
object Action {
def apply(actionDef: (Method, JsObject))(implicit parseContext: ParseContext): Try[Action] = {
val (method, jsObj) = actionDef
createAction(method, jsObj)
}
private def createAction(actionType: Method, jsObject: JsObject)(implicit parseContext: ParseContext): Try[Action] = {
parseContext.traits.applyToAction(jsObject) { json =>
val tryQueryParameters = Parameters(jsValueOpt = (json \ "queryParameters").toOption)
val tryQueryString =
(json \ "queryString").toOption.collect {
case ParsedType(bType) => bType.map(Option(_))
} getOrElse Success(None)
val tryHeaders = Parameters((json \ "headers").toOption)
val tryBody = Body(json)
val tryResponses = Responses(json)
for {
queryParameters <- tryQueryParameters
headers <- tryHeaders
body <- tryBody
responses <- tryResponses
queryStringOpt <- tryQueryString
} yield
Action(
actionType = actionType,
headers = headers,
queryParameters = queryParameters,
body = body,
responses = responses,
queryString = queryStringOpt.map(qs => QueryString(queryStringType = TypeRepresentation(qs)))
)
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/restmodel/ResponseType.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.restmodel
import io.atomicbits.scraml.generator.codegen.GenerationAggr
import io.atomicbits.scraml.generator.platform.Platform
import io.atomicbits.scraml.generator.typemodel.ClassPointer
import io.atomicbits.scraml.ramlparser.model.{ MediaType, Response }
import Platform._
/**
* Created by peter on 26/08/15.
*/
sealed trait ResponseType {
def acceptHeader: MediaType
def acceptHeaderOpt: Option[MediaType] = Some(acceptHeader)
}
case class StringResponseType(acceptHeader: MediaType) extends ResponseType
case class JsonResponseType(acceptHeader: MediaType) extends ResponseType
case class TypedResponseType(acceptHeader: MediaType, classPointer: ClassPointer) extends ResponseType
case class BinaryResponseType(acceptHeader: MediaType) extends ResponseType
case object NoResponseType extends ResponseType {
val acceptHeader = MediaType("")
override val acceptHeaderOpt = None
}
object ResponseType {
def apply(response: Response)(implicit platform: Platform): Set[ResponseType] = {
response.body.contentMap.map {
case (mediaType, bodyContent) =>
val classPointerOpt = bodyContent.bodyType.flatMap(_.canonical).map(Platform.typeReferenceToClassPointer)
val formParams = bodyContent.formParameters
ResponseType(acceptHeader = mediaType, classPointer = classPointerOpt)
}.toSet
}
def apply(acceptHeader: MediaType, classPointer: Option[ClassPointer])(implicit platform: Platform): ResponseType = {
val mediaTypeValue = acceptHeader.value.toLowerCase
if (classPointer.isDefined) {
TypedResponseType(acceptHeader, classPointer.get)
} else if (mediaTypeValue.contains("json")) {
JsonResponseType(acceptHeader)
} else if (mediaTypeValue.contains("text")) {
StringResponseType(acceptHeader)
} else if (mediaTypeValue.contains("octet-stream")) {
BinaryResponseType(acceptHeader)
} else {
BinaryResponseType(acceptHeader)
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedObject.scala | <filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedObject.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, RamlParseException }
import io.atomicbits.scraml.util.TryUtils
import play.api.libs.json._
import scala.util.{ Failure, Success, Try }
/**
* Created by peter on 25/03/16.
*/
case class ParsedObject(id: Id,
properties: ParsedProperties,
required: Option[Boolean] = None,
requiredProperties: List[String] = List.empty,
selection: Option[Selection] = None,
fragments: Fragments = Fragments(),
parents: Set[ParsedTypeReference] = Set.empty,
typeParameters: List[String] = List.empty,
typeDiscriminator: Option[String] = None,
typeDiscriminatorValue: Option[String] = None,
model: TypeModel = RamlModel)
extends Fragmented
with AllowedAsObjectField
with NonPrimitiveType {
override def updated(updatedId: Id): ParsedObject = copy(id = updatedId)
override def asTypeModel(typeModel: TypeModel): ParsedType = {
val updatedProperties =
properties.map { property =>
property.copy(propertyType = TypeRepresentation(property.propertyType.parsed.asTypeModel(typeModel)))
}
val updatedSelection =
selection.map { effectiveSelection =>
effectiveSelection.map { ptype =>
ptype.asTypeModel(typeModel)
}
}
copy(model = typeModel, properties = updatedProperties, selection = updatedSelection)
}
def isEmpty: Boolean = {
properties.valueMap.isEmpty && selection.isEmpty && fragments.fragmentMap.isEmpty &&
typeParameters.isEmpty && typeDiscriminator.isEmpty && typeDiscriminatorValue.isEmpty
}
}
object ParsedObject {
val value = "object"
def apply(json: JsValue)(implicit parseContext: ParseContext): Try[ParsedObject] = {
val model: TypeModel = TypeModel(json)
// Process the id
val id: Id = JsonSchemaIdExtractor(json)
// Process the properties
val properties: Try[ParsedProperties] = ParsedProperties((json \ "properties").toOption, model)
val fragments = json match {
case Fragments(fragment) => fragment
}
// Process the required field
val (required, requiredFields) =
(json \ "required").toOption match {
case Some(req: JsArray) =>
val reqFields =
req.value.toList collect {
case JsString(fieldName) => fieldName
}
(None, Some(reqFields))
case Some(JsBoolean(b)) => (Some(b), None)
case _ => (None, None)
}
// Process the typeVariables field
val typeVariables: List[String] =
(json \ "typeVariables").toOption match {
case Some(typeVars: JsArray) => typeVars.value.toList.collect { case JsString(value) => value }
case _ => List.empty[String]
}
// Process the discriminator field
val discriminator: Option[String] =
List((json \ "discriminator").toOption, (json \ "typeDiscriminator").toOption).flatten.headOption match {
case Some(JsString(value)) => Some(value)
case _ => None
}
// Process the discriminatorValue field
val discriminatorValue: Option[String] =
(json \ "discriminatorValue").toOption match {
case Some(JsString(value)) => Some(value)
case _ => None
}
val oneOf =
(json \ "oneOf").toOption collect {
case selections: JsArray =>
val selectionSchemas = selections.value collect {
case jsObj: JsObject => jsObj
} map (tryToInterpretOneOfSelectionAsObjectType(_, id, discriminator.getOrElse("type")))
TryUtils.accumulate(selectionSchemas.toSeq).map(_.toList).map(selections => OneOf(selections.map(_.asTypeModel(JsonSchemaModel))))
}
val anyOf =
(json \ "anyOf").toOption collect {
case selections: JsArray =>
val selectionSchemas = selections.value collect {
case ParsedType(theType) => theType
}
TryUtils.accumulate(selectionSchemas.toList).map(_.toList).map(selections => AnyOf(selections.map(_.asTypeModel(JsonSchemaModel))))
}
val allOf =
(json \ "allOf").toOption collect {
case selections: JsArray =>
val selectionSchemas = selections.value collect {
case ParsedType(theType) => theType
}
TryUtils.accumulate(selectionSchemas.toList).map(_.toList).map(selections => AllOf(selections.map(_.asTypeModel(JsonSchemaModel))))
}
val selection = List(oneOf, anyOf, allOf).flatten.headOption
TryUtils.withSuccess(
Success(id),
properties,
Success(required),
Success(requiredFields.getOrElse(List.empty[String])),
TryUtils.accumulate(selection),
fragments,
Success(Set.empty[ParsedTypeReference]),
Success(typeVariables),
Success(discriminator),
Success(discriminatorValue),
Success(model)
)(new ParsedObject(_, _, _, _, _, _, _, _, _, _, _))
}
def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[ParsedObject]] = {
def isParentRef(theOtherType: String): Option[Try[ParsedTypeReference]] = {
ParsedType(theOtherType) match {
case Success(typeRef: ParsedTypeReference) => Some(Try(typeRef)) // It is not a primitive type and not an array, so it is a type reference.
case _ => None
}
}
(ParsedType.typeDeclaration(json), (json \ "properties").toOption, (json \ "genericType").toOption) match {
case (Some(JsString(ParsedObject.value)), _, None) => Some(ParsedObject(json))
case (Some(JsString(otherType)), Some(jsObj), None) =>
isParentRef(otherType).map { triedParent =>
triedParent.flatMap { parent =>
ParsedObject(json).flatMap { objectType =>
parent.refersTo match {
case nativeId: NativeId => Success(objectType.copy(parents = Set(parent)))
case _ => Failure(RamlParseException(s"Expected a parent reference in RAML1.0 to have a valid native id."))
}
}
}
}
case (None, Some(jsObj), None) => Some(ParsedObject(json))
case _ => None
}
}
def schemaToDiscriminatorValue(schema: Identifiable): Option[String] = {
Some(schema) collect {
case enumType: ParsedEnum if enumType.choices.length == 1 => enumType.choices.head
}
}
private def tryToInterpretOneOfSelectionAsObjectType(schema: JsObject, parentId: Id, typeDiscriminator: String)(
implicit parseContext: ParseContext): Try[ParsedType] = {
def typeDiscriminatorFromProperties(oneOfFragment: Fragments): Option[String] = {
oneOfFragment.fragmentMap.get("properties").collect {
case propFrag: Fragments => propFrag.fragmentMap.get(typeDiscriminator) flatMap schemaToDiscriminatorValue
}.flatten
}
def fixId(id: Id, parentId: Id, discriminatorValue: String): Option[RelativeId] = {
id match {
case ImplicitId => // fix id based on the parentId if there isn't one
if (discriminatorValue.exists(_.isLower)) Some(RelativeId(id = discriminatorValue))
else Some(RelativeId(id = discriminatorValue.toLowerCase))
case _ => None
}
}
schema match {
case ParsedType(x) => x
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/BodyContent.scala | <filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/BodyContent.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.ParsedType
import io.atomicbits.scraml.ramlparser.parser.ParseContext
import play.api.libs.json.{ JsObject, JsValue }
import scala.util.{ Failure, Success, Try }
import io.atomicbits.scraml.util.TryUtils._
/**
* Created by peter on 10/02/16.
*/
case class BodyContent(mediaType: MediaType, bodyType: Option[TypeRepresentation] = None, formParameters: Parameters = new Parameters())
object BodyContentAsMediaTypeMap {
/**
* Tries to represent a body from a mediatype map
*
* @param json Everything under the 'body' field of a resource spec.
*/
def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[List[BodyContent]]] = {
def fromJsObjectValues(mediaTypeAndJsValue: (String, JsValue))(implicit parseContext: ParseContext): Option[Try[BodyContent]] = {
val (medType, json) = mediaTypeAndJsValue
medType match {
case mediaType @ MediaType(mt) =>
val tryFormParameters = Parameters((json \ "formParameters").toOption)
val bodyType =
json match {
case ParsedType(bType) => Some(bType)
case _ => None
}
val triedBodyContent =
for {
bType <- accumulate(bodyType)
formParameters <- tryFormParameters
} yield BodyContent(MediaType(medType), bType.map(TypeRepresentation(_)), formParameters)
Some(triedBodyContent)
case _ => None
}
}
json match {
case jsObj: JsObject =>
val bodyContentList = jsObj.value.toList.map(fromJsObjectValues).flatten
accumulate(bodyContentList).map(_.toList) match {
case Success(Nil) => None
case Success(someContent) => Some(Success(someContent))
case failure @ Failure(exc) => Some(failure)
}
case _ => None
}
}
}
object BodyContentAsDefaultMediaType {
/**
* Tries to represent a body from a mediatype map
*
* @param json Everything under the 'body' field of a resource spec.
*/
def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[BodyContent]] = {
parseContext.defaultMediaType.map { defaultMediaType =>
val bodyType =
json match {
case ParsedType(bType) => Some(bType)
case _ => None
}
accumulate(bodyType).map(bType => BodyContent(defaultMediaType, bType.map(TypeRepresentation(_))))
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/SimpleRamlConstructor.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 org.yaml.snakeyaml.constructor.{ Construct, AbstractConstruct, SafeConstructor }
import org.yaml.snakeyaml.nodes.{ ScalarNode, Node, Tag }
/**
* Created by peter on 6/02/16.
*/
class SimpleRamlConstructor extends SafeConstructor {
def addYamlConstructor(tag: Tag, construct: Construct): Unit = {
this.yamlConstructors.put(tag, construct)
}
}
class ConstructInclude extends AbstractConstruct {
@SuppressWarnings(Array("unchecked"))
def construct(node: Node): Object = {
val snode: ScalarNode = node.asInstanceOf[ScalarNode]
Include(snode.getValue)
}
}
object SimpleRamlConstructor {
def apply(): SimpleRamlConstructor = {
val constructor = new SimpleRamlConstructor
constructor.addYamlConstructor(new Tag("!include"), new ConstructInclude())
constructor
}
}
|
atomicbits/scramlgen | modules/scraml-gen-simulation/src/test/java/io/atomicbits/scraml/client/java/JavaScramlGeneratorTest.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.client.java
import java.util
import java.util.concurrent.{ Future, TimeUnit }
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.javajackson.client.ClientConfig
import io.atomicbits.scraml.dsl.javajackson.Response
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen }
import org.scalatest.featurespec.AnyFeatureSpec
/**
* Created by peter on 19/08/15.
*/
class JavaScramlGeneratorTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll with ScalaFutures {
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/foo?queryparX=30.0&queryparZ=6&queryparY=5"))
.withHeader("Accept", equalTo("application/json"))
.withHeader("Cookie", equalTo("mjam"))
.willReturn(aResponse()
.withBody("""{"firstName":"John", "lastName": "Doe", "age": 21}""")
.withStatus(200)))
stubFor(
get(urlEqualTo(s"/rest/some/webservice/bar?queryparX=21.5&queryparZ=66&queryparY=55"))
.withHeader("Accept", equalTo("application/json"))
.withHeader("Cookie", equalTo("bar"))
.willReturn(aResponse()
.withBody("""{"firstName":"Ziva", "lastName": "Zoef", "age": 2}""")
.withStatus(200)))
When("we execute some restful requests using the DSL")
val client: JXoClient = new JXoClient(host, port, "http", null, new ClientConfig(), new util.HashMap[String, String](), null)
val resource = client.rest.some.webservice
val request1 = resource.pathparam("foo").addHeader("Cookie", "mjam")
val request2 = resource.pathparam("bar").addHeader("Cookie", "bar")
val result1: Future[Response[Person]] = request1.get(30.0, 5, 6).call()
val response1 = result1.get(10, TimeUnit.SECONDS)
val persoon1 = new Person()
persoon1.setFirstName("John")
persoon1.setLastName("Doe")
persoon1.setAge(21L)
assertResult(persoon1)(response1.getBody)
val result2: Future[Response[Person]] = request2.get(21.5, 55, 66).call()
val response2 = result2.get(10, TimeUnit.SECONDS)
val persoon2 = new Person()
persoon2.setFirstName("Ziva")
persoon2.setLastName("Zoef")
persoon2.setAge(2L)
assertResult(persoon2)(response2.getBody)
client._close()
}
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/client/ning/Ning2Client.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.client.ning
import java.nio.charset.Charset
import java.util.{List => JList, Map => JMap}
import java.util.concurrent.CompletionStage
import java.util.function.{BiConsumer, Function => JFunction}
import org.asynchttpclient.AsyncCompletionHandlerBase
import org.asynchttpclient.DefaultAsyncHttpClientConfig
import org.asynchttpclient.Request
import org.asynchttpclient.request.body.generator.InputStreamBodyGenerator
import org.asynchttpclient.Dsl._
import scala.concurrent.ExecutionContext.Implicits.global
import io.atomicbits.scraml.dsl.scalaplay.client.ClientConfig
import io.atomicbits.scraml.dsl.scalaplay._
import io.netty.handler.codec.http.HttpHeaders
import org.slf4j.{Logger, LoggerFactory}
import play.api.libs.json._
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success, Try}
import scala.collection.JavaConverters._
/**
* Created by peter on 28/10/15.
*/
case class Ning2Client(protocol: String,
host: String,
port: Int,
prefix: Option[String],
config: ClientConfig,
defaultHeaders: Map[String, String])
extends Client {
val LOGGER: Logger = LoggerFactory.getLogger(classOf[Ning2Client])
private val cleanPrefix = prefix.map { pref =>
val strippedPref = pref.stripPrefix("/").stripSuffix("/")
s"/$strippedPref"
} getOrElse ""
private lazy val client = {
val configBuilder: DefaultAsyncHttpClientConfig.Builder = new DefaultAsyncHttpClientConfig.Builder
asyncHttpClient(applyConfiguration(configBuilder).build)
}
def callToJsonResponse(requestBuilder: RequestBuilder, body: Option[String]): Future[Response[JsValue]] = {
callToStringResponse(requestBuilder, body).map { response =>
if (response.status >= 200 && response.status < 300) {
// Where we assume that any response in the 200 range will map to the unique typed response. This doesn't hold true if
// there are many responses in the 200 range with different typed responses.
// if (response.status == 200) {
val respJson = response.flatMap { responseString =>
if (responseString != null && responseString.nonEmpty) Some(Json.parse(responseString))
else None
}
respJson.copy(jsonBody = respJson.body)
} else {
response.copy(jsonBody = None, body = None)
}
}
}
def callToTypeResponse[R](requestBuilder: RequestBuilder, body: Option[String])(
implicit responseFormat: Format[R]): Future[Response[R]] = {
// In case of a non-200 or non-204 response, we set the typed body to None and keep the future successful and return the
// Response object. When the JSON body on a 200-response cannot be parsed into the expected type, we DO fail the future because
// in that case we violate the RAML specs.
callToJsonResponse(requestBuilder, body) map { response =>
if (response.status >= 200 && response.status < 300) {
// Where we assume that any response in the 200 range will map to the unique typed response. This doesn't hold true if
// there are many responses in the 200 range with different typed responses.
response.map(responseFormat.reads)
} else {
// We hijack the 'JsError(Nil)' type here to mark the non-200 case that has to result in a successful future with empty body.
// Mind that the empty body only means that the requested type is None, the stringBody and jsonBody fields are present as well.
response.map(_ => JsError(Nil))
}
} flatMap {
case response @ Response(_, _, _, Some(JsSuccess(t, path)), _) => Future.successful(response.copy(body = Some(t)))
case response @ Response(_, _, _, Some(JsError(Nil)), _) => Future.successful(response.copy(body = None))
case response @ Response(_, _, _, None, _) => Future.successful(response.copy(body = None))
case Response(_, _, _, Some(JsError(e)), _) =>
val validationMessages = {
e flatMap { errorsByPath =>
val (path, errors) = errorsByPath
errors map (error => s"$path -> ${error.message}")
}
}
Future.failed(
new IllegalArgumentException(
s"JSON validation error in the response from ${requestBuilder.summary}: ${validationMessages mkString ", "}"))
}
}
def callToStringResponse(requestBuilder: RequestBuilder, body: Option[String]): Future[Response[String]] = {
val transformer: org.asynchttpclient.Response => Response[String] = { response =>
val headers: Map[String, List[String]] = headersToMap(response.getHeaders)
val responseCharset: String = getResponseCharsetFromHeaders(headers).getOrElse(config.responseCharset.displayName)
val stringResponseBody: Option[String] = Option(response.getResponseBody(Charset.forName(responseCharset)))
Response[String](response.getStatusCode, stringResponseBody, None, stringResponseBody, headers)
}
callToResponse(requestBuilder, body, transformer)
}
def callToBinaryResponse(requestBuilder: RequestBuilder, body: Option[String]): Future[Response[BinaryData]] = {
val transformer: org.asynchttpclient.Response => Response[BinaryData] = { response =>
val binaryData: BinaryData = new Ning2BinaryData(response)
val headers: Map[String, List[String]] = headersToMap(response.getHeaders)
Response[BinaryData](response.getStatusCode, None, None, Some(binaryData), headers)
}
callToResponse(requestBuilder, body, transformer)
}
private def callToResponse[T](requestBuilder: RequestBuilder,
body: Option[String],
transformer: org.asynchttpclient.Response => Response[T]): Future[Response[T]] = {
val ningBuilder = {
// Create builder
val ningRb: org.asynchttpclient.RequestBuilder = new org.asynchttpclient.RequestBuilder
val baseUrl: String = protocol + "://" + host + ":" + port + cleanPrefix
ningRb.setUrl(baseUrl + "/" + requestBuilder.relativePath.stripPrefix("/"))
ningRb.setMethod(requestBuilder.method.toString)
ningRb
}
requestBuilder.allHeaders.foreach {
case (key, values) =>
values.foreach { value =>
ningBuilder.addHeader(key, value)
}
}
requestBuilder.queryParameters.foreach {
case (key, value) =>
value match {
case SimpleHttpParam(parameter) => ningBuilder.addQueryParam(key, parameter)
case ComplexHttpParam(parameter) => ningBuilder.addQueryParam(key, parameter)
case RepeatedHttpParam(parameters) =>
parameters.foreach(parameter => ningBuilder.addQueryParam(key, parameter))
}
}
body.foreach { body =>
ningBuilder.setBody(body)
}
requestBuilder.binaryBody.foreach {
case FileBinaryRequest(file) => ningBuilder.setBody(file)
case InputStreamBinaryRequest(inputStream) => ningBuilder.setBody(new InputStreamBodyGenerator(inputStream))
case ByteArrayBinaryRequest(byteArray) => ningBuilder.setBody(byteArray)
case StringBinaryRequest(text) => ningBuilder.setBody(text)
}
requestBuilder.formParameters.foreach {
case (key, value) =>
value match {
case SimpleHttpParam(parameter) => ningBuilder.addFormParam(key, parameter)
case ComplexHttpParam(parameter) => ningBuilder.addFormParam(key, parameter)
case RepeatedHttpParam(parameters) =>
parameters.foreach(parameter => ningBuilder.addFormParam(key, parameter))
}
}
requestBuilder.multipartParams.foreach {
case part: ByteArrayPart =>
ningBuilder.addBodyPart(
new org.asynchttpclient.request.body.multipart.ByteArrayPart(
part.name,
part.bytes,
part.contentType.orNull,
part.charset.orNull,
part.contentId.orNull,
part.transferEncoding.orNull
)
)
case part: FilePart =>
ningBuilder.addBodyPart(
new org.asynchttpclient.request.body.multipart.FilePart(
part.name,
part.file,
part.contentType.orNull,
part.charset.orNull,
part.fileName.orNull,
part.contentId.orNull,
part.transferEncoding.orNull
)
)
case part: StringPart =>
ningBuilder.addBodyPart(
new org.asynchttpclient.request.body.multipart.StringPart(
part.name,
part.value,
part.contentType.orNull,
part.charset.orNull,
part.contentId.orNull,
part.transferEncoding.orNull
)
)
}
val ningRequest: Request = ningBuilder.build()
LOGGER.debug(s"Executing request: $ningRequest")
LOGGER.trace(s"Request body: $body")
val promise = Promise[Response[T]]()
client.executeRequest(
ningRequest,
new AsyncCompletionHandlerBase() {
@throws(classOf[Exception])
override def onCompleted(response: org.asynchttpclient.Response): org.asynchttpclient.Response = {
val resp: Try[Response[T]] = Try(transformer(response))
promise.complete(resp)
null
}
override def onThrowable(t: Throwable) {
super.onThrowable(t)
promise.failure(t)
// explicitely return Unit to avoid compilation errors on systems with strict compilation rules switched on,
// such as "-Ywarn-value-discard"
()
}
}
)
promise.future
}
def close(): Unit = client.close()
private def applyConfiguration(builder: DefaultAsyncHttpClientConfig.Builder): DefaultAsyncHttpClientConfig.Builder = {
builder.setReadTimeout(config.readTimeout)
builder.setMaxConnections(config.maxConnections)
builder.setRequestTimeout(config.requestTimeout)
builder.setMaxRequestRetry(config.maxRequestRetry)
builder.setConnectTimeout(config.connectTimeout)
builder.setConnectionTtl(config.connectionTTL)
builder.setMaxConnectionsPerHost(config.maxConnectionsPerHost)
builder.setPooledConnectionIdleTimeout(config.pooledConnectionIdleTimeout)
builder.setUseInsecureTrustManager(config.useInsecureTrustManager)
builder.setFollowRedirect(config.followRedirect)
builder.setMaxRedirects(config.maxRedirects)
builder.setStrict302Handling(config.strict302Handling)
}
private[ning] def getResponseCharsetFromHeaders(headers: Map[String, List[String]]): Option[String] = {
val contentTypeValuesOpt =
headers.map { keyValues =>
val (key, values) = keyValues
key.toLowerCase() -> values
} get "content-type"
for {
contentTypeValues <- contentTypeValuesOpt
contentTypeValueWithCharset <- contentTypeValues.find(_.toLowerCase().contains("charset"))
charsetPart <- contentTypeValueWithCharset.toLowerCase().split(";").toList.find(_.contains("charset"))
splitOnCharset = charsetPart.split("charset").toList
charsetString <- {
splitOnCharset match {
case _ :: value :: other =>
val cleanValue = value.trim.stripPrefix("=").trim
Try(Charset.forName(cleanValue)).toOption.map(_.name())
case _ => None
}
}
} yield charsetString
}
private def headersToMap(httpHeaders: HttpHeaders) = {
httpHeaders.names.asScala.foldLeft(Map.empty[String,List[String]]) { (map, name) =>
map + (name -> httpHeaders.getAll(name).asScala.toList)
}
}
private def toJavaFunction[A, B](f: A => B) = new JFunction[A, B] {
override def apply(a: A): B = f(a)
}
private def fromJavaFuture[B](jfuture: CompletionStage[B]): Future[B] = {
val p = Promise[B]()
val consumer = new BiConsumer[B, Throwable] {
override def accept(v: B, t: Throwable): Unit =
if (t == null) {
p.complete(Success(v))
// explicitely return Unit to avoid compilation errors on systems with strict compilation rules switched on,
// such as "-Ywarn-value-discard"
()
} else {
p.complete(Failure(t))
// explicitely return Unit to avoid compilation errors on systems with strict compilation rules switched on,
// such as "-Ywarn-value-discard"
()
}
}
jfuture.whenComplete(consumer)
p.future
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/javajackson/PojoGenerator.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.javajackson
import io.atomicbits.scraml.generator.codegen.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 1/03/17.
*/
case class PojoGenerator(javaJackson: CommonJavaJacksonPlatform) extends SourceGenerator with PojoGeneratorSupport {
implicit val platform: Platform = javaJackson
val defaultDiscriminator = "type"
def generate(generationAggr: GenerationAggr, toClassDefinition: TransferObjectClassDefinition): GenerationAggr = {
/**
* TOs are represented as POJOs in Java, which can without trouble extend from each other as long as only single-inheritance
* is used. As soon as we deal with multiple-inheritance, we need to replace all POJOs that function as one of the parents in
* a multiple-inheritance relation by their interface. The actual implementing class of that interface case gets the 'Impl' suffix.
*/
val originalToCanonicalName = toClassDefinition.reference.canonicalName
val toHasOwnInterface = hasOwnInterface(originalToCanonicalName, generationAggr)
val actualToCanonicalClassReference: ClassReference =
if (toHasOwnInterface) toClassDefinition.implementingInterfaceReference
else toClassDefinition.reference
val initialTosWithInterface: Seq[TransferObjectClassDefinition] =
if (toHasOwnInterface) Seq(toClassDefinition)
else Seq.empty
val ownFields: Seq[Field] = toClassDefinition.fields
val parentNames: List[CanonicalName] = generationAggr.allParents(originalToCanonicalName)
val interfacesAndFieldsAggr = (initialTosWithInterface, ownFields)
val (recursiveExtendedParents, allFields) =
parentNames.foldLeft(interfacesAndFieldsAggr) { (aggr, parentName) =>
val (interfaces, fields) = aggr
val parentDefinition: TransferObjectClassDefinition =
generationAggr.toMap.getOrElse(parentName, sys.error(s"Expected to find $parentName in the generation aggregate."))
val withParentFields = fields ++ parentDefinition.fields
val withParentInterface = interfaces :+ parentDefinition
(withParentInterface, withParentFields)
}
val discriminator: String =
(toClassDefinition.typeDiscriminator +: recursiveExtendedParents.map(_.typeDiscriminator)).flatten.headOption
.getOrElse(defaultDiscriminator)
val jsonTypeInfo: Option[JsonTypeInfo] =
if (generationAggr.isInHierarchy(originalToCanonicalName)) {
Some(JsonTypeInfo(discriminator = discriminator, discriminatorValue = toClassDefinition.actualTypeDiscriminatorValue))
} else {
None
}
val hasMultipleDirectParents = generationAggr.directParents(originalToCanonicalName).size > 1
val (interfacesToImplement, fieldsToGenerate, classToExtend) =
(toHasOwnInterface, hasMultipleDirectParents) match {
case (true, _) =>
val interfaceToImpl = List(TransferObjectInterfaceDefinition(toClassDefinition, discriminator))
val fieldsToGen = allFields
val classToExt = None
(interfaceToImpl, fieldsToGen, classToExt)
case (false, false) =>
val interfaceToImpl = List.empty[TransferObjectInterfaceDefinition]
val fieldsToGen = ownFields
val classToExt =
generationAggr
.directParents(originalToCanonicalName)
.headOption // There should be at most one direct parent.
.map(parent => generationAggr.toMap.getOrElse(parent, sys.error(s"Expected to find $parent in the generation aggregate.")))
(interfaceToImpl, fieldsToGen, classToExt)
case (false, true) =>
val interfaceToImpl =
generationAggr
.directParents(originalToCanonicalName)
.map(parent => generationAggr.toMap.getOrElse(parent, sys.error(s"Expected to find $parent in the generation aggregate.")))
.map(TransferObjectInterfaceDefinition(_, discriminator))
val fieldsToGen = allFields
val classToExt = None
(interfaceToImpl.toList, fieldsToGen, classToExt)
}
val skipFieldName = jsonTypeInfo.map(_.discriminator)
val childrenToSerialize =
if (!toHasOwnInterface) compileChildrenToSerialize(originalToCanonicalName, toClassDefinition, generationAggr)
else Set.empty[ChildToSerialize]
val importPointers: Seq[ClassPointer] = {
val fieldTypesToImport = allFields.map(_.classPointer)
val children = childrenToSerialize.map(_.classReference)
val interfaces = interfacesToImplement.map(_.origin.reference.classPointer)
val parentClass = Seq(classToExtend.map(_.reference.classPointer)).flatten
fieldTypesToImport ++ children ++ interfaces ++ parentClass
}
val imports: Set[String] = platform.importStatements(actualToCanonicalClassReference, importPointers.toSet)
val jsonTypeAnnotations = generateJsonTypeAnnotations(childrenToSerialize, jsonTypeInfo)
val source =
s"""
package ${actualToCanonicalClassReference.packageName};
import com.fasterxml.jackson.annotation.*;
${imports.mkString("\n")}
$jsonTypeAnnotations
${generatePojoSource(actualToCanonicalClassReference,
interfacesToImplement,
classToExtend,
fieldsToGenerate,
allFields,
skipFieldName)}
"""
val generationAggrWithAddedInterfaces = interfacesToImplement.foldLeft(generationAggr) { (aggr, interf) =>
generationAggr.addInterfaceSourceDefinition(interf)
}
val sourceFile =
SourceFile(
filePath = actualToCanonicalClassReference.toFilePath,
content = source
)
generationAggrWithAddedInterfaces.addSourceFile(sourceFile)
}
private def generatePojoSource(toClassReference: ClassReference,
interfacesToImplement: List[TransferObjectInterfaceDefinition],
classToExtend: Option[TransferObjectClassDefinition],
fieldsToGenerate: Seq[Field],
allFields: Seq[Field],
skipFieldName: Option[String] = None): String = {
def fieldsWithoutSkipField(fields: Seq[Field]): Seq[Field] = {
skipFieldName map { skipField =>
fields.filterNot(_.fieldName == skipField)
} getOrElse fields
}
val selectedFields = fieldsWithoutSkipField(fieldsToGenerate)
val sortedFields = selectedFields.sortBy(_.safeFieldName) // In Java Pojo's, we sort by field name!
val selectedFieldsWithParentFields = fieldsWithoutSkipField(allFields)
val sortedFieldsWithParentFields = selectedFieldsWithParentFields.sortBy(_.safeFieldName)
val privateFieldExpressions = sortedFields.map { field =>
s"""
@JsonProperty(value = "${field.fieldName}")
private ${field.fieldDeclaration};
"""
}
val getterAndSetters = sortedFields map {
case fieldRep @ Field(fieldName, classPointer, required) =>
val fieldNameCap = fieldRep.safeFieldName.capitalize
s"""
public ${classPointer.classDefinition} get$fieldNameCap() {
return ${fieldRep.safeFieldName};
}
public void set$fieldNameCap(${classPointer.classDefinition} ${fieldRep.safeFieldName}) {
this.${fieldRep.safeFieldName} = ${fieldRep.safeFieldName};
}
"""
}
val extendsClass = classToExtend.map(classToExt => s"extends ${classToExt.reference.classDefinition}").getOrElse("")
val implementsClass =
if (interfacesToImplement.nonEmpty)
interfacesToImplement.map(classToImpl => classToImpl.origin.reference.classDefinition).mkString("implements ", ", ", "")
else ""
val constructorInitialization = sortedFieldsWithParentFields map { sf =>
val fieldNameCap = sf.safeFieldName.capitalize
s"this.set$fieldNameCap(${sf.safeFieldName});"
}
val constructorFieldDeclarations = sortedFieldsWithParentFields.map(_.fieldDeclaration)
val fieldConstructor =
if (constructorFieldDeclarations.nonEmpty)
s"""
public ${toClassReference.name}(${constructorFieldDeclarations.mkString(", ")}) {
${constructorInitialization.mkString("\n")}
}
"""
else ""
s"""
public class ${toClassReference.classDefinition} $extendsClass $implementsClass {
${privateFieldExpressions.mkString("\n")}
public ${toClassReference.name}() {
}
$fieldConstructor
${getterAndSetters.mkString("\n")}
}
"""
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/util/TestUtils.scala | <filename>modules/scraml-raml-parser/src/test/scala/io/atomicbits/util/TestUtils.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.util
/**
* Created by peter on 31/08/16.
*/
object TestUtils {
/**
* Pretty prints a textual representation of case classes.
*/
def prettyPrint(obj: Object): String = {
val text = Text(obj.toString)
text.print()
}
def prettyPrint(text: String): String = Text(text).print()
trait Text {
val indentIncrement = 4
def print(): String = print(0)
def print(indent: Int): String
}
object Text {
def apply(text: String): Text = {
val cleanText = text.replaceAll(" ", "")
def splitListElements(elements: String, splitChar: Char): List[String] = {
val aggregate = (0, "", List.empty[String])
val (level, last, elem) =
elements.foldLeft(aggregate) {
case ((0, current, elems), `splitChar`) => (0, "", elems :+ current)
case ((x, current, elems), '(') => (x + 1, s"${current}(", elems)
case ((x, current, elems), ')') => (x - 1, s"${current})", elems)
case ((x, current, elems), char) => (x, s"${current}$char", elems)
}
elem :+ last
}
val beginIndex = text.indexOf('(')
val endIndex = text.lastIndexOf(')')
(beginIndex, endIndex) match {
case (-1, -1) => SimpleText(cleanText)
case (-1, _) => sys.error(s"Invalid case class representation: $text")
case (_, -1) => sys.error(s"Invalid case class representation: $text")
case (begin, end) =>
val prefix = text.take(begin)
val contentString = text.drop(begin + 1).dropRight(text.length - end)
if ("Map" == prefix || "HashMap" == prefix) {
val contentStrings = splitListElements(contentString, ',')
val content = contentStrings.filter(_.nonEmpty).map { contentString =>
val replaced = contentString.replaceFirst("->", "@")
val index = replaced.indexOf('@')
val key = replaced.take(index)
val text = replaced.drop(index + 1)
key -> Text(text)
}
MapBlock(content.toMap)
} else {
val contentStrings = splitListElements(contentString, ',')
val content = contentStrings.map(Text(_))
Block(prefix, content)
}
}
}
}
case class SimpleText(content: String) extends Text {
def print(indent: Int): String = {
val indentString = " " * indent
s"$indentString$content"
}
}
case class Block(prefix: String, content: List[Text]) extends Text {
def print(indent: Int): String = {
val indentString = " " * indent
if (content.isEmpty) {
s"$indentString$prefix()"
} else {
s"""$indentString$prefix(
|${content.map(_.print(indent + indentIncrement)).mkString(",\n")}
|$indentString)""".stripMargin
}
}
}
case class MapBlock(content: Map[String, Text]) extends Text {
def print(indent: Int): String = {
val indentString = " " * indent
val contentIndentString = " " * (indent + 1)
val contentString = content.map {
case (key, text) =>
s"""$contentIndentString$key ->
|${text.print(indent + 1 + indentIncrement)}""".stripMargin
}.mkString(",\n")
if (content.isEmpty) {
s"${indentString}Map()"
} else {
s"""${indentString}Map(
|$contentString
|$indentString)""".stripMargin
}
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/RamltoJsonParser.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.parser
import java.net.URI
import org.yaml.snakeyaml.Yaml
import play.api.libs.json._
import scala.collection.JavaConverters._
import scala.util.{ Failure, Success, Try }
/**
* Created by peter on 10/02/16.
*/
object RamlToJsonParser {
def parseToJson(source: String): JsonFile = {
parseToJson(source, "UTF-8")
}
def parseToJson(source: String, charsetName: String): JsonFile = {
Try {
val SourceFile(path, ramlContent) = SourceReader.read(source, charsetName)
val ramlContentNoTabs = ramlContent.replace("\t", " ") // apparently, the yaml parser does not handle tabs well
val yaml = new Yaml(SimpleRamlConstructor())
val ramlMap: Any = yaml.load(ramlContentNoTabs)
(path, anyToJson(ramlMap))
} match {
case Success((path, jsvalue)) => JsonFile(path, jsvalue)
case Failure(ex) =>
ex.printStackTrace()
sys.error(s"Parsing $source resulted in the following error:\n${ex.getMessage}")
}
}
private def printReadStatus(resourceType: String, resourceOpt: Option[URI]): Any = {
resourceOpt.map { resource =>
println(s"Resource found $resourceType: $resource")
} getOrElse {
println(s"Resource NOT found $resourceType")
}
}
private def anyToJson(value: Any): JsValue = {
value match {
case s: String => unwrapJsonString(Json.toJson(s))
case b: Boolean => Json.toJson(b)
case i: java.lang.Integer => Json.toJson(i.doubleValue())
case l: java.lang.Long => Json.toJson(l.doubleValue())
case d: Double => Json.toJson(d)
case list: java.util.ArrayList[_] => JsArray(list.asScala.map(anyToJson))
case map: java.util.Map[_, _] =>
val mapped =
mapAsScalaMap(map).map {
case (field, theValue) => field.toString -> anyToJson(theValue)
}
JsObject(mapped.toSeq)
case include: Include =>
Json.toJson(include) // the included body is attached in a json object as the string value of the !include field of that JSON object
case null => JsNull
case x => sys.error(s"Cannot parse unknown type $x (${x.getClass.getCanonicalName})")
}
}
/**
* One time 'unwrap' of a JSON value that is wrapped as a string value.
*/
private def unwrapJsonString(json: JsValue): JsValue = {
json match {
case JsString(stringVal) =>
Try(Json.parse(stringVal)) match {
case Success(jsObject: JsObject) =>
if (jsObject.\("$schema").toOption.isEmpty) {
jsObject + ("$schema" -> JsString("http://json-schema.org/draft-03/schema"))
} else {
jsObject
}
case Success(nonStringJsValue) => nonStringJsValue
case _ => json
}
case _ => json
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/Platform.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
import java.nio.file.Path
import io.atomicbits.scraml.generator.codegen.GenerationAggr
import io.atomicbits.scraml.ramlparser.model.canonicaltypes.{ TypeParameter => ParserTypeParameter }
import io.atomicbits.scraml.ramlparser.model.canonicaltypes.{
ArrayTypeReference,
BooleanType,
CanonicalName,
DateOnlyType,
DateTimeDefaultType,
DateTimeOnlyType,
DateTimeRFC2616Type,
DateType,
FileType,
GenericReferrable,
IntegerType,
JsonType,
NonPrimitiveTypeReference,
NullType,
NumberType,
ObjectType,
StringType,
TimeOnlyType,
TypeReference,
TypeParameter => CanonicalTypeParameter
}
import io.atomicbits.scraml.generator.typemodel._
import io.atomicbits.scraml.ramlparser.parser.SourceFile
/**
* Created by peter on 10/01/17.
*/
trait Platform {
def name: String
def apiBasePackageParts: List[String]
def apiBasePackage: String = apiBasePackageParts.mkString(".")
def apiBaseDir: String = apiBasePackageParts.mkString("/", "/", "")
def dslBasePackageParts: List[String]
def dslBasePackage: String = dslBasePackageParts.mkString(".")
def dslBaseDir: String = dslBasePackageParts.mkString("/", "/", "")
def rewrittenDslBasePackage: List[String]
def classPointerToNativeClassReference(classPointer: ClassPointer): ClassReference
/**
* The implementing interface reference is the reference to the class (transfer object class) that implements the
* interface that replaces it in a multiple inheritance relation (and in Scala also in a regular inheritance relation).
* E.g. AnimalImpl implements Animal --> Here, 'Animal' is the interface where resources and cross referencing inside TO's point to.
*/
def implementingInterfaceReference(classReference: ClassReference): ClassReference
/**
* The definition of a class.
* E.g. List[String] or List<String> or Element or PagedList<T> or PagedList[Element]
* or their fully qualified verions
* E.g. List[String] or java.util.List<String> or io.atomicbits.Element or io.atomicbits.PagedList<T> or io.atomicbits.PagedList[Element]
*/
def classDefinition(classPointer: ClassPointer, fullyQualified: Boolean = false): String
def className(classPointer: ClassPointer): String
def packageName(classPointer: ClassPointer): String
def fullyQualifiedName(classPointer: ClassPointer): String
def safePackageParts(classPointer: ClassPointer): List[String]
def safeFieldName(field: Field): String = safeFieldName(field.fieldName)
def safeFieldName(fieldName: String): String
def safeDeconstructionName(fieldName: String): String = safeFieldName(fieldName)
def fieldDeclarationWithDefaultValue(field: Field): String
def fieldDeclaration(field: Field): String
def importStatements(targetClassReference: ClassPointer, dependencies: Set[ClassPointer] = Set.empty): Set[String]
def toSourceFile(generationAggr: GenerationAggr, toClassDefinition: TransferObjectClassDefinition): GenerationAggr
def toSourceFile(generationAggr: GenerationAggr, toInterfaceDefinition: TransferObjectInterfaceDefinition): GenerationAggr
def toSourceFile(generationAggr: GenerationAggr, enumDefinition: EnumDefinition): GenerationAggr
def toSourceFile(generationAggr: GenerationAggr, clientClassDefinition: ClientClassDefinition): GenerationAggr
def toSourceFile(generationAggr: GenerationAggr, resourceClassDefinition: ResourceClassDefinition): GenerationAggr
def toSourceFile(generationAggr: GenerationAggr, headerSegmentClassDefinition: HeaderSegmentClassDefinition): GenerationAggr
def toSourceFile(generationAggr: GenerationAggr, unionClassDefinition: UnionClassDefinition): GenerationAggr
def classFileExtension: String
/**
* Transforms a given class reference to a file path. The given class reference already has clean package and class names.
*
* @param classPointer The class reference for which a file path is generated.
* @return The relative file name for the given class.
*/
def toFilePath(classPointer: ClassPointer): Path
/**
* Platform specific mapping from the generated sourcefiles. Mostly the original sources will be kept, hence the
* default implementation. Other platforms will map the sources into a single file (e.g. typescript).
*/
def mapSourceFiles(sources: Set[SourceFile], combinedSourcesFileName: Option[String] = None): Set[SourceFile] = sources
def reservedKeywords: Set[String]
}
object Platform {
def typeReferenceToClassPointer(typeReference: TypeReference): ClassPointer = {
def customClassReference(canonicalName: CanonicalName,
genericTypes: List[GenericReferrable],
genericTypeParameters: List[ParserTypeParameter]): ClassReference = {
val generics: List[ClassPointer] =
genericTypes.map {
case typeRef: TypeReference => typeReferenceToClassPointer(typeRef)
case CanonicalTypeParameter(paramName) =>
sys.error(s"Didn't expect a type parameter when constructing a custom class reference at this stage.")
}
val typeParameters = genericTypeParameters.map(tp => TypeParameter(tp.name))
ClassReference(
name = canonicalName.name,
packageParts = canonicalName.packagePath,
typeParameters = typeParameters,
typeParamValues = generics
)
}
typeReference match {
case BooleanType => BooleanClassPointer(false)
case StringType => StringClassPointer
case JsonType => JsObjectClassPointer
case IntegerType => LongClassPointer(false)
case NumberType => DoubleClassPointer(false)
case NullType => StringClassPointer // not sure what we have to do in this case
case FileType => FileClassPointer
case DateTimeDefaultType => DateTimeRFC3339ClassPointer
case DateTimeRFC2616Type => DateTimeRFC2616ClassPointer
case DateTimeOnlyType => DateTimeOnlyClassPointer
case TimeOnlyType => TimeOnlyClassPointer
case DateOnlyType => DateOnlyClassPointer
case ArrayTypeReference(genericType) =>
genericType match {
case typeReference: TypeReference =>
val classPointer = typeReferenceToClassPointer(typeReference)
ListClassPointer(classPointer)
case CanonicalTypeParameter(paramName) =>
val typeParameter = TypeParameter(paramName)
ListClassPointer(typeParameter)
}
case NonPrimitiveTypeReference(refers, genericTypes, genericTypeParameters) =>
customClassReference(refers, genericTypes, genericTypeParameters)
case unexpected => sys.error(s"Didn't expect type reference in generator: $unexpected")
}
}
def typeReferenceToNonPrimitiveCanonicalName(typeReference: TypeReference): Option[CanonicalName] = {
Some(typeReference).collect {
case NonPrimitiveTypeReference(refers, genericTypes, genericTypeParameters) => refers
}
}
def typeReferenceToClassReference(typeReference: TypeReference): Option[ClassReference] = {
Some(typeReferenceToClassPointer(typeReference)).collect {
case classReference: ClassReference => classReference
}
}
implicit class PlatformClassPointerOps(val classPointer: ClassPointer) {
def classDefinition(implicit platform: Platform): String = platform.classDefinition(classPointer)
def packageName(implicit platform: Platform): String = platform.packageName(classPointer)
def fullyQualifiedName(implicit platform: Platform): String = platform.fullyQualifiedName(classPointer)
def safePackageParts(implicit platform: Platform): List[String] = platform.safePackageParts(classPointer)
def fullyQualifiedClassDefinition(implicit platform: Platform): String = platform.classDefinition(classPointer, fullyQualified = true)
def native(implicit platform: Platform): ClassReference = platform.classPointerToNativeClassReference(classPointer)
def toFilePath(implicit platform: Platform): Path = platform.toFilePath(classPointer)
def implementingInterfaceReference(implicit platform: Platform): ClassReference =
platform.implementingInterfaceReference(classPointer.native)
def importStatements(implicit platform: Platform): Set[String] = platform.importStatements(classPointer)
}
implicit class PlatformFieldOps(val field: Field) {
def safeFieldName(implicit platform: Platform): String = platform.safeFieldName(field)
def safeDeconstructionName(implicit platform: Platform): String = platform.safeDeconstructionName(field.fieldName)
def fieldDeclarationWithDefaultValue(implicit platform: Platform): String = platform.fieldDeclarationWithDefaultValue(field)
def fieldDeclaration(implicit platform: Platform): String = platform.fieldDeclaration(field)
}
implicit class PlatformToClassDefinitionOps(val toClassDefinition: TransferObjectClassDefinition) {
def toSourceFile(generationAggr: GenerationAggr)(implicit platform: Platform): GenerationAggr =
platform.toSourceFile(generationAggr, toClassDefinition)
}
implicit class PlatformToInterfaceDefinitionOps(val toInterfaceDefinition: TransferObjectInterfaceDefinition) {
def toSourceFile(generationAggr: GenerationAggr)(implicit platform: Platform): GenerationAggr =
platform.toSourceFile(generationAggr, toInterfaceDefinition)
}
implicit class PlatformEnumDefinitionOps(val enumDefinition: EnumDefinition) {
def toSourceFile(generationAggr: GenerationAggr)(implicit platform: Platform): GenerationAggr =
platform.toSourceFile(generationAggr, enumDefinition)
}
implicit class PlatformClientClassDefinitionOps(val clientClassDefinition: ClientClassDefinition) {
def toSourceFile(generationAggr: GenerationAggr)(implicit platform: Platform): GenerationAggr =
platform.toSourceFile(generationAggr, clientClassDefinition)
}
implicit class PlatformResourceClassDefinitionOps(val resourceClassDefinition: ResourceClassDefinition) {
def toSourceFile(generationAggr: GenerationAggr)(implicit platform: Platform): GenerationAggr =
platform.toSourceFile(generationAggr, resourceClassDefinition)
}
implicit class PlatformHeaderSegmentClassDefinitionOps(val headerSegmentClassDefinition: HeaderSegmentClassDefinition) {
def toSourceFile(generationAggr: GenerationAggr)(implicit platform: Platform): GenerationAggr =
platform.toSourceFile(generationAggr, headerSegmentClassDefinition)
}
implicit class PlatformUnionClassDefinitionOps(val unionClassDefinition: UnionClassDefinition) {
def toSourceFile(generationAggr: GenerationAggr)(implicit platform: Platform): GenerationAggr =
platform.toSourceFile(generationAggr, unionClassDefinition)
}
implicit class PlatformSourceCodeOps(val sourceCode: SourceDefinition) {
def toSourceFile(generationAggr: GenerationAggr)(implicit platform: Platform): GenerationAggr =
sourceCode match {
case clientClassDefinition: ClientClassDefinition =>
new PlatformClientClassDefinitionOps(clientClassDefinition).toSourceFile(generationAggr)
case resourceClassDefinition: ResourceClassDefinition =>
new PlatformResourceClassDefinitionOps(resourceClassDefinition).toSourceFile(generationAggr)
case headerSegmentDefinition: HeaderSegmentClassDefinition =>
new PlatformHeaderSegmentClassDefinitionOps(headerSegmentDefinition).toSourceFile(generationAggr)
case toClassDefinition: TransferObjectClassDefinition =>
new PlatformToClassDefinitionOps(toClassDefinition).toSourceFile(generationAggr)
case toInterfaceDefinition: TransferObjectInterfaceDefinition =>
new PlatformToInterfaceDefinitionOps(toInterfaceDefinition).toSourceFile(generationAggr)
case enumDefinition: EnumDefinition =>
new PlatformEnumDefinitionOps(enumDefinition).toSourceFile(generationAggr)
case unionClassDefinition: UnionClassDefinition =>
new PlatformUnionClassDefinitionOps(unionClassDefinition).toSourceFile(generationAggr)
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/ActionsParseTest.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.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 ActionsParseTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll {
Feature("actions parsing") {
Scenario("test parsing actions 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 all four actions in the userid resource")
val raml = parsedModel.get
val restResource: Resource = raml.resources.filter(_.urlSegment == "rest").head
val userResource: Resource = restResource.resources.filter(_.urlSegment == "user").head
val userIdResource: Resource = userResource.resources.filter(_.urlSegment == "userid").head
val actionTypes = userIdResource.actions.map(_.actionType)
actionTypes should contain(Get)
actionTypes should contain(Put)
actionTypes should contain(Post)
actionTypes should contain(Delete)
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/TraitsParseTest.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._
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/11/16.
*/
class TraitsParseTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll {
Scenario("test the application of traits in a complex RAML 1.0 model") {
Given("a RAML 1.0 specification with a traits definition")
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 restResource: Resource = raml.resourceMap("rest")
val userResource: Resource = restResource.resourceMap("user")
val uploadResource: Resource = userResource.resourceMap("upload")
val uploadPostAction: Action = uploadResource.actionMap(Post)
val response401Opt = uploadPostAction.responses.responseMap.get(StatusCode("401"))
response401Opt should not be None
val bodyContentOpt = response401Opt.get.body.contentMap.get(MediaType("application/json"))
bodyContentOpt should not be None
val resourcetraitResource: Resource = userResource.resourceMap("resourcetrait")
val getAction: Action = resourcetraitResource.actionMap(Get)
val getResponse401Opt = getAction.responses.responseMap.get(StatusCode("401"))
getResponse401Opt should not be None
val getBodyContentOpt = getResponse401Opt.get.body.contentMap.get(MediaType("application/json"))
getBodyContentOpt should not be None
val putAction: Action = resourcetraitResource.actionMap(Put)
val putResponse401Opt = putAction.responses.responseMap.get(StatusCode("401"))
putResponse401Opt should not be None
val putBodyContentOpt = putResponse401Opt.get.body.contentMap.get(MediaType("application/json"))
putBodyContentOpt should not be None
val postAction: Action = resourcetraitResource.actionMap(Post)
val postResponse401Opt = postAction.responses.responseMap.get(StatusCode("401"))
postResponse401Opt should not be None
val postBodyContentOpt = postResponse401Opt.get.body.contentMap.get(MediaType("application/existing+json"))
postBodyContentOpt should not be None
val deleteAction: Action = resourcetraitResource.actionMap(Delete)
val deleteResponse401Opt = deleteAction.responses.responseMap.get(StatusCode("401"))
deleteResponse401Opt should not be None
val deleteBodyContentOpt = deleteResponse401Opt.get.body.contentMap.get(MediaType("application/alternative+json"))
deleteBodyContentOpt should not be None
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Body.scala | <reponame>atomicbits/scramlgen<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Body.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.JsValue
import scala.language.postfixOps
import scala.util.{ Success, Try }
/**
* Created by peter on 26/08/16.
*/
case class Body(contentMap: Map[MediaType, BodyContent] = Map.empty) {
def forHeader(mimeType: MediaType): Option[BodyContent] = contentMap.get(mimeType)
// val values = contentMap.values.toList
}
object Body {
def apply(json: JsValue)(implicit parseContext: ParseContext): Try[Body] = {
json \ "body" toOption match {
case Some(BodyContentAsMediaTypeMap(triedBodyContents)) =>
triedBodyContents.map { bodyContentList =>
val contentMap =
bodyContentList.map { bodyContent =>
bodyContent.mediaType -> bodyContent
}
Body(contentMap.toMap)
}
case Some(BodyContentAsDefaultMediaType(triedBodyContent)) =>
triedBodyContent.map { bodyContent =>
Body(Map(bodyContent.mediaType -> bodyContent))
}
case _ => Success(Body())
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/MediaType.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
/**
* Created by peter on 26/08/16.
*/
trait MediaType {
def value: String
}
case class ActualMediaType(value: String) extends MediaType
case object NoMediaType extends MediaType {
val value: String = ""
}
object MediaType {
def apply(mimeType: String): MediaType = unapply(mimeType).getOrElse(NoMediaType)
def unapply(mimeType: String): Option[MediaType] = {
val (typeAndSubT, params) =
mimeType.split(';').toList match {
case typeAndSubType :: Nil => (Some(typeAndSubType.trim), None)
case typeAndSubType :: parameters :: unexpected => (Some(typeAndSubType.trim), Some(parameters.trim))
case Nil => (None, None)
}
typeAndSubT.flatMap { typeSub =>
typeSub.split('/').toList match {
case ttype :: subtype :: anything => Some(ActualMediaType(typeSub))
case _ => None
}
}
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/json/JsonOps.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.dsl.scalaplay.json
import play.api.libs.json._
import scala.language.postfixOps
/**
* Created by peter on 7/04/17.
*/
object JsonOps {
def toString(json: JsValue): String = {
json match {
case JsString(jsString) => jsString // JsString(jsString).toString would have put quotes around the jsString.
case other => other.toString()
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedArray.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, RamlParseException }
import play.api.libs.json.{ JsObject, JsString, JsValue }
import io.atomicbits.scraml.ramlparser.parser.JsUtils._
import io.atomicbits.scraml.util.TryUtils
import scala.util.{ Failure, Success, Try }
/**
* Created by peter on 25/03/16.
*/
case class ParsedArray(items: ParsedType,
id: Id = ImplicitId,
required: Option[Boolean] = None,
minItems: Option[Int] = None,
maxItems: Option[Int] = None,
uniqueItems: Boolean = false,
fragments: Fragments = Fragments(),
model: TypeModel = RamlModel)
extends NonPrimitiveType
with AllowedAsObjectField
with Fragmented {
override def updated(updatedId: Id): ParsedArray = copy(id = updatedId)
override def asTypeModel(typeModel: TypeModel): ParsedType = copy(model = typeModel, items = items.asTypeModel(typeModel))
def asRequired = copy(required = Some(true))
}
object ParsedArray {
val value = "array"
def apply(triedPrimitiveType: Try[PrimitiveType])(implicit parseContext: ParseContext): Try[ParsedArray] = {
val id = triedPrimitiveType.map(_.id)
val primitiveWithErasedId =
triedPrimitiveType.map { prim =>
prim.updated(ImplicitId)
}
val required = triedPrimitiveType.map(_.required)
TryUtils.withSuccess(
primitiveWithErasedId,
id,
required,
Success(None),
Success(None),
Success(false),
Success(new Fragments())
)(ParsedArray(_, _, _, _, _, _, _))
}
def apply(arrayExpression: String)(implicit parseContext: ParseContext): Try[ParsedArray] = {
if (arrayExpression.endsWith("[]")) {
val typeName = arrayExpression.stripSuffix("[]")
ParsedType(typeName).map(ParsedArray(_))
} else {
Failure(
RamlParseException(
s"Expression $arrayExpression in ${parseContext.head} is not an array expression, it should end with '[]'."
)
)
}
}
def apply(json: JsValue)(implicit parseContext: ParseContext): Try[ParsedArray] = {
val model: TypeModel = TypeModel(json)
// Process the id
val id = JsonSchemaIdExtractor(json)
// Process the items type
val items =
(json \ "items").toOption.collect {
case ParsedType(someType) => someType
} getOrElse
Failure(
RamlParseException(
s"An array definition in ${parseContext.head} has either no 'items' field or an 'items' field with an invalid type declaration."
)
)
// Process the required field
val required = json.fieldBooleanValue("required")
val fragments = json match {
case Fragments(fragment) => fragment
}
TryUtils.withSuccess(
items,
Success(id),
Success(required),
Success(None),
Success(None),
Success(false),
fragments,
Success(model)
)(ParsedArray(_, _, _, _, _, _, _, _))
}
def unapply(arrayTypeExpression: String)(implicit parseContext: ParseContext): Option[Try[ParsedArray]] = {
if (arrayTypeExpression.endsWith("[]")) Some(ParsedArray(arrayTypeExpression))
else None
}
def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[ParsedArray]] = {
// The repeated field is no longer present in RAML 1.0, but for backward compatibility reasons, we still parse it and
// interpret these values as array types.
val repeatedValue = (json \ "repeat").asOpt[Boolean]
(ParsedType.typeDeclaration(json), json, repeatedValue) match {
case (Some(JsString(ParsedArray.value)), _, _) => Some(ParsedArray(json))
case (_, JsString(arrayTypeExpression), _) if arrayTypeExpression.endsWith("[]") => Some(ParsedArray(arrayTypeExpression))
case (_, PrimitiveType(tryType), Some(true)) => Some(ParsedArray(tryType))
case _ => None
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/typemodel/ClassPointer.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
import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName
/**
* Created by peter on 10/01/17.
*/
sealed trait ClassPointer
trait PrimitiveClassPointer extends ClassPointer
case class ClassReference(name: String,
packageParts: List[String] = List.empty,
typeParameters: List[TypeParameter] = List.empty,
typeParamValues: List[ClassPointer] = List.empty,
arrayType: Option[ClassReference] = None,
predef: Boolean = false,
library: Boolean = false,
isTypeParameter: Boolean = false)
extends ClassPointer {
lazy val canonicalName: CanonicalName = CanonicalName.create(name, packageParts)
/**
* The base form for this class reference. The base form refers to the class in its most unique way,
* without type parameter values.
* e.g. List[T] and not List[Dog]
*/
lazy val base: ClassReference = if (typeParamValues.isEmpty) this else copy(typeParamValues = List.empty)
val isArray: Boolean = arrayType.isDefined
}
case object StringClassPointer extends PrimitiveClassPointer
case object ByteClassPointer extends PrimitiveClassPointer
case class LongClassPointer(primitive: Boolean = true) extends PrimitiveClassPointer
case class DoubleClassPointer(primitive: Boolean = true) extends PrimitiveClassPointer
case class BooleanClassPointer(primitive: Boolean = true) extends PrimitiveClassPointer
case class TypeParameter(name: String) extends ClassPointer
case class ArrayClassPointer(arrayType: ClassPointer) extends ClassPointer
case object BinaryDataClassPointer extends ClassPointer
case object InputStreamClassPointer extends ClassPointer
case object FileClassPointer extends ClassPointer
case object JsObjectClassPointer extends ClassPointer
case object JsValueClassPointer extends ClassPointer
case class ListClassPointer(typeParamValue: ClassPointer) extends ClassPointer
case object BodyPartClassPointer extends ClassPointer
case object DateTimeRFC3339ClassPointer extends ClassPointer
case object DateTimeRFC2616ClassPointer extends ClassPointer
case object DateTimeOnlyClassPointer extends ClassPointer
case object TimeOnlyClassPointer extends ClassPointer
case object DateOnlyClassPointer extends ClassPointer
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/TypeParametersTest.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.canonicaltypes._
import io.atomicbits.scraml.ramlparser.model.Raml
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 20/03/17.
*/
class TypeParametersTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll {
Feature("Test cases using type parameters") {
Scenario("a json-schema definition with a reference to a paged-list in an object field") {
Given("a RAML specification containing a json-schema definition with type parameters")
val defaultBasePath = List("io", "atomicbits", "raml10")
val parser = RamlParser("/typeparameters08/zoo-api.raml", "UTF-8")
When("we parse the specification")
val raml: Raml = parser.parse.get
val canonicalNameGenerator = CanonicalNameGenerator(defaultBasePath)
val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator)
val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml)
Then("we find the type parameters in the parsed and the canonical types")
val pagedListNonPrimitive: NonPrimitiveType =
canonicalLookup.map(CanonicalName.create(name = "PagedList", packagePath = List("io", "atomicbits", "raml10")))
val pagedListObject = pagedListNonPrimitive.asInstanceOf[ObjectType]
pagedListObject.typeParameters shouldBe List(TypeParameter("T"), TypeParameter("U"))
val zooNonPrimitive: NonPrimitiveType =
canonicalLookup.map(CanonicalName.create(name = "Zoo", packagePath = List("io", "atomicbits", "raml10")))
val zooObject = zooNonPrimitive.asInstanceOf[ObjectType]
val pagedListTypeReference: Property[NonPrimitiveTypeReference] =
zooObject.properties("animals").asInstanceOf[Property[NonPrimitiveTypeReference]]
val animalTypeRef: NonPrimitiveTypeReference =
pagedListTypeReference.ttype.genericTypes.head.asInstanceOf[NonPrimitiveTypeReference]
animalTypeRef.refers shouldBe CanonicalName.create(name = "Animal", packagePath = List("io", "atomicbits", "raml10"))
val intTypeRef: GenericReferrable = pagedListTypeReference.ttype.genericTypes.tail.head
intTypeRef shouldBe IntegerType
}
Scenario("a RAML 1.0 definition with a reference to a paged-list in an object field") {
Given("a RAML specification containing a RAML 1.0 definition with type parameters")
val defaultBasePath = List("io", "atomicbits", "raml10")
val parser = RamlParser("/typeparameters10/zoo-api.raml", "UTF-8")
When("we parse the specification")
val raml: Raml = parser.parse.get
val canonicalNameGenerator = CanonicalNameGenerator(defaultBasePath)
val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator)
val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml)
Then("we find the type parameters in the parsed and the canonical types")
val pagedListNonPrimitive: NonPrimitiveType =
canonicalLookup.map(CanonicalName.create(name = "PagedList", packagePath = List("io", "atomicbits", "raml10")))
val pagedListObject = pagedListNonPrimitive.asInstanceOf[ObjectType]
pagedListObject.typeParameters shouldBe List(TypeParameter("T"), TypeParameter("U"))
val zooNonPrimitive: NonPrimitiveType =
canonicalLookup.map(CanonicalName.create(name = "Zoo", packagePath = List("io", "atomicbits", "raml10")))
val zooObject = zooNonPrimitive.asInstanceOf[ObjectType]
val pagedListTypeReference: Property[NonPrimitiveTypeReference] =
zooObject.properties("animals").asInstanceOf[Property[NonPrimitiveTypeReference]]
val animalTypeRef: NonPrimitiveTypeReference =
pagedListTypeReference.ttype.genericTypes.head.asInstanceOf[NonPrimitiveTypeReference]
animalTypeRef.refers shouldBe CanonicalName.create(name = "Animal", packagePath = List("io", "atomicbits", "raml10"))
val intTypeRef: GenericReferrable = pagedListTypeReference.ttype.genericTypes.tail.head
intTypeRef shouldBe IntegerType
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/typescript/TypeScript.scala | <filename>modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/typescript/TypeScript.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.typescript
import java.nio.file.{ Path, Paths }
import io.atomicbits.scraml.generator.codegen.GenerationAggr
import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform }
import io.atomicbits.scraml.generator.typemodel._
import Platform._
import io.atomicbits.scraml.ramlparser.parser.SourceFile
/**
* Created by peter on 15/12/17.
*/
case class TypeScript() extends Platform with CleanNameTools {
val apiBasePackageParts: List[String] = List.empty
val name: String = "TypeScript"
implicit val platform: TypeScript = this
override def dslBasePackageParts = List.empty
override def rewrittenDslBasePackage = List.empty
override def classPointerToNativeClassReference(classPointer: ClassPointer): ClassReference = {
classPointer match {
case classReference: ClassReference => classReference
case ArrayClassPointer(arrayType) =>
val typeParameter = TypeParameter("T")
val typeParamValues = List(arrayType)
ClassReference(name = "Array", typeParameters = List(typeParameter), typeParamValues = typeParamValues, predef = true)
case StringClassPointer =>
ClassReference(name = "string", packageParts = List(), predef = true)
case ByteClassPointer =>
ClassReference(name = "Byte", packageParts = List(), predef = true)
??? // not implemented
case BinaryDataClassPointer =>
ClassReference(name = "BinaryData", packageParts = List(), library = true) // Uint8Array ?
??? // not implemented
case FileClassPointer =>
ClassReference(name = "File", packageParts = List(), library = true)
??? // not implemented
case InputStreamClassPointer =>
ClassReference(name = "InputStream", packageParts = List(), library = true)
??? // not implemented
case JsObjectClassPointer =>
ClassReference(name = "any", packageParts = List(), library = true)
case JsValueClassPointer =>
ClassReference(name = "JsValue", packageParts = List(), library = true)
??? // not implemented
case BodyPartClassPointer =>
ClassReference(name = "BodyPart", packageParts = List(), library = true)
??? // not implemented
case LongClassPointer(primitive) =>
ClassReference(name = "number", packageParts = List(), predef = true)
case DoubleClassPointer(primitive) =>
ClassReference(name = "number", packageParts = List(), predef = true)
case BooleanClassPointer(primitive) =>
ClassReference(name = "boolean", packageParts = List(), predef = true)
case DateTimeRFC3339ClassPointer => // See: http://blog.stevenlevithan.com/archives/date-time-format
// ClassReference(name = "DateTimeRFC3339", packageParts = List(), library = true)
ClassReference(name = "string", packageParts = List(), predef = true)
case DateTimeRFC2616ClassPointer =>
// ClassReference(name = "DateTimeRFC2616", packageParts = List(), library = true)
ClassReference(name = "string", packageParts = List(), predef = true)
case DateTimeOnlyClassPointer =>
// ClassReference(name = "DateTimeOnly", packageParts = List(), library = true)
ClassReference(name = "string", packageParts = List(), predef = true)
case TimeOnlyClassPointer =>
// ClassReference(name = "TimeOnly", packageParts = List(), library = true)
ClassReference(name = "string", packageParts = List(), predef = true)
case DateOnlyClassPointer =>
// ClassReference(name = "DateOnly", packageParts = List(), library = true)
ClassReference(name = "string", packageParts = List(), predef = true)
case ListClassPointer(typeParamValue) =>
val typeParameter = TypeParameter("T")
val typeParamValues = List(typeParamValue)
ClassReference(name = "Array", 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 => ???
}
}
/**
* The implementing interface reference is the reference to the class (transfer object class) that implements the
* interface that replaces it in a multiple inheritance relation (and in Scala also in a regular inheritance relation).
* E.g. AnimalImpl implements Animal --> Here, 'Animal' is the interface where resources and cross referencing inside TO's point to.
*/
override def implementingInterfaceReference(classReference: ClassReference) = ??? // not implemented
/**
* The definition of a class.
* E.g. List[String] or List<String> or Element or PagedList<T> or PagedList[Element]
* or their fully qualified verions
* E.g. List[String] or java.util.List<String> or io.atomicbits.Element or io.atomicbits.PagedList<T> or io.atomicbits.PagedList[Element]
*/
override def classDefinition(classPointer: ClassPointer, fullyQualified: Boolean) = {
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 = ""
override def fullyQualifiedName(classPointer: ClassPointer) = className(classPointer)
override def safePackageParts(classPointer: ClassPointer): List[String] = List()
override def safeFieldName(fieldName: String): String = {
// In typescript, all field names are allowed, even reserved words.
// If the field name contains special characters such as spaces, '-', '~', ..., then we need to quote it.
// Just to be sure to handle all special characters, we quote all fields.
quoteString(fieldName)
}
override def fieldDeclarationWithDefaultValue(field: Field) = fieldDeclaration(field)
override def fieldDeclaration(field: Field) =
if (field.required) s"${safeFieldName(field)}: ${classDefinition(field.classPointer)}"
else s"${safeFieldName(field)}?: ${classDefinition(field.classPointer)}"
override def importStatements(targetClassReference: ClassPointer, dependencies: Set[ClassPointer]): Set[String] = Set()
override def toSourceFile(generationAggr: GenerationAggr, toClassDefinition: TransferObjectClassDefinition) =
ToClassGenerator(this).generate(generationAggr, toClassDefinition)
override def toSourceFile(generationAggr: GenerationAggr, toInterfaceDefinition: TransferObjectInterfaceDefinition) =
InterfaceGenerator(this).generate(generationAggr, toInterfaceDefinition)
override def toSourceFile(generationAggr: GenerationAggr, enumDefinition: EnumDefinition) =
EnumGenerator(this).generate(generationAggr, enumDefinition)
override def toSourceFile(generationAggr: GenerationAggr, clientClassDefinition: ClientClassDefinition) = generationAggr
override def toSourceFile(generationAggr: GenerationAggr, resourceClassDefinition: ResourceClassDefinition) = generationAggr
override def toSourceFile(generationAggr: GenerationAggr, headerSegmentClassDefinition: HeaderSegmentClassDefinition) = generationAggr
override def toSourceFile(generationAggr: GenerationAggr, unionClassDefinition: UnionClassDefinition) =
UnionClassGenerator(this).generate(generationAggr, unionClassDefinition)
override def classFileExtension = "d.ts"
/**
* Transforms a given class reference to a file path. The given class reference already has clean package and class names.
*
* @param classPointer The class reference for which a file path is generated.
* @return The relative file name for the given class.
*/
override def toFilePath(classPointer: ClassPointer): Path = {
classPointer match {
case classReference: ClassReference =>
Paths.get("", s"${classReference.name}.$classFileExtension") // 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!")
}
}
override def mapSourceFiles(sources: Set[SourceFile], combinedSourcesFileName: Option[String] = None): Set[SourceFile] = {
combinedSourcesFileName.map { combinedName =>
val allContent = sources.toList.sortBy(_.filePath).map(_.content)
Set(
SourceFile(
filePath = Paths.get(combinedName), // We will fill in the actual filePath later.
content = allContent.mkString("\n")
)
)
} getOrElse (sources)
}
val reservedKeywords =
Set(
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"enum",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"import",
"in",
"instanceof",
"new",
"null",
"return",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"var",
"void",
"while",
"with",
"as",
"implements",
"interface",
"let",
"package",
"private",
"protected",
"public",
"static",
"yield",
"any",
"boolean",
"constructor",
"declare",
"get",
"module",
"require",
"number",
"set",
"string",
"symbol",
"type",
"from",
"of"
) ++
Set(
"otherFields"
) // These are the fields we have reserved by scraml.
def escapeTypeScriptKeyword(someName: String, escape: String = "$"): String =
reservedKeywords.foldLeft(someName) { (name, resWord) =>
if (name == resWord) s"$name$escape"
else name
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/BinaryData.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.dsl.scalaplay
import _root_.java.io.{ File, InputStream }
import _root_.java.nio.file._
import scala.util.{ Success, Try }
/**
* Created by peter on 20/01/16.
*/
/**
* The BinaryData object is the Response result type when binary data is received from the server.
*/
trait BinaryData {
def asBytes: Array[Byte]
/**
* Request the binary data as a stream. This is convenient when there is a large amount of data to receive.
* You can only request the input stream once because the data is not stored along the way!
* Do not close the stream after use.
*
* @return An inputstream for reading the binary data.
*/
def asStream: InputStream
def asString: String
def asString(charset: String): String
/**
* Write the binary data as a stream to the given file. This call can only be executed once!
*
* @param path The path (file) to write the binary data to.
* @param options The copy options.
* @return A Success if the copying was successful, a Failure otherwise.
*/
def writeToFile(path: Path, options: CopyOption*): Try[_] = {
val directoriesCreated =
Option(path.getParent) collect {
case parent => Try(Files.createDirectories(parent))
} getOrElse Success(())
directoriesCreated flatMap { _ =>
Try(Files.copy(asStream, path, options: _*))
}
}
/**
* Write the binary data as a stream to the given file. This call can only be executed once!
*
* @param file The file to write the binary data to.
* @return A Success if the copying was successful, a Failure otherwise.
*/
def writeToFile(file: File): Try[_] = writeToFile(file.toPath)
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/restmodel/ContentType.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.restmodel
import io.atomicbits.scraml.generator.platform.Platform
import io.atomicbits.scraml.generator.typemodel.ClassPointer
import io.atomicbits.scraml.ramlparser.model.{ Body, MediaType, Parameters }
/**
* Created by peter on 26/08/15.
*/
sealed trait ContentType {
def contentTypeHeader: MediaType
def contentTypeHeaderOpt: Option[MediaType] = Some(contentTypeHeader)
}
case class StringContentType(contentTypeHeader: MediaType) extends ContentType
case class JsonContentType(contentTypeHeader: MediaType) extends ContentType
case class TypedContentType(contentTypeHeader: MediaType, classPointer: ClassPointer) extends ContentType
case class FormPostContentType(contentTypeHeader: MediaType, formParameters: Parameters) extends ContentType
case class MultipartFormContentType(contentTypeHeader: MediaType) extends ContentType
case class BinaryContentType(contentTypeHeader: MediaType) extends ContentType
case class AnyContentType(contentTypeHeader: MediaType) extends ContentType
case object NoContentType extends ContentType {
val contentTypeHeader = MediaType("")
override val contentTypeHeaderOpt = None
}
object ContentType {
def apply(body: Body)(implicit platform: Platform): Set[ContentType] =
body.contentMap.map {
case (mediaType, bodyContent) =>
val classPointerOpt = bodyContent.bodyType.flatMap(_.canonical).map(Platform.typeReferenceToClassPointer)
val formParams = bodyContent.formParameters
ContentType(mediaType = mediaType, content = classPointerOpt, formParameters = formParams)
}.toSet
def apply(mediaType: MediaType, content: Option[ClassPointer], formParameters: Parameters)(implicit platform: Platform): ContentType = {
val mediaTypeValue = mediaType.value.toLowerCase
if (mediaTypeValue == "multipart/form-data") {
MultipartFormContentType(mediaType)
} else if (formParameters.nonEmpty) {
FormPostContentType(mediaType, formParameters)
} else if (content.isDefined) {
TypedContentType(mediaType, content.get)
} else if (mediaTypeValue.contains("json")) {
JsonContentType(mediaType)
} else if (mediaTypeValue.contains("text")) {
StringContentType(mediaType)
} else if (mediaTypeValue.contains("octet-stream")) {
BinaryContentType(mediaType)
} else {
AnyContentType(mediaType)
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/JsonSchemaWithRelativeIdsTest.scala | <filename>modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/JsonSchemaWithRelativeIdsTest.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.canonicaltypes._
import io.atomicbits.scraml.ramlparser.model.{ Get, MediaType, Raml, StatusCode }
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 15/02/17.
*/
class JsonSchemaWithRelativeIdsTest 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", "model")
val parser = RamlParser("/relativeid/car-api.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 carsResource = ramlUpdated.resources.filter(_.urlSegment == "cars").head
val getBody = carsResource.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 car = canonicalType.asInstanceOf[NonPrimitiveTypeReference]
val carName = CanonicalName.create("Car", List("io", "atomicbits", "model"))
car.refers shouldBe carName
val carType = canonicalLookup.map(carName).asInstanceOf[ObjectType]
carType.properties("drive") shouldBe
Property(
name = "drive",
ttype = NonPrimitiveTypeReference(refers = CanonicalName.create(name = "Engine", packagePath = List("io", "atomicbits", "model")))
)
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/ResourcePathsParseTest.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.canonicaltypes.{StringType, TypeReference}
import io.atomicbits.scraml.ramlparser.model.{Parameter, Raml, Resource}
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 ResourcePathsParseTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll {
Feature("resource paths parsing") {
Scenario("test resource paths in a complex RAML 1.0 model") {
Given("a RAML 1.0 specification")
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
Then("we get a series of resource paths")
val raml = parsedModel.get
// collect resource paths
def collectResources(resources: List[Resource]): List[List[String]] = {
resources.flatMap(collectResourcePaths(_, List.empty))
}
def collectResourcePaths(currentResource: Resource, currentPath: List[String]): List[List[String]] = {
val currentSegment =
currentResource.urlParameter.map(param => s"{${currentResource.urlSegment}}").getOrElse(currentResource.urlSegment)
val nextPath = currentPath :+ currentSegment
currentResource.resources match {
case Nil => List(nextPath)
case rs =>
if (currentResource.actions.isEmpty) rs.flatMap(collectResourcePaths(_, nextPath))
else nextPath :: rs.flatMap(collectResourcePaths(_, nextPath))
}
}
val collectedResources = collectResources(raml.resources)
// println(s"collected resources:\n$collectedResources")
val expectedResources =
Set(
List("rest", "user"),
List("rest", "user", "upload"),
List("rest", "user", "resourcetrait"),
List("rest", "user", "activate"),
List("rest", "user", "{void}", "location"),
List("rest", "user", "{userid}"),
List("rest", "user", "{userid}", "dogs"),
List("rest", "animals"),
List("rest", "animals", "datafile", "upload"),
List("rest", "animals", "datafile", "download"),
List("rest", "books")
)
collectedResources.size shouldEqual expectedResources.size
expectedResources.foreach { expected =>
collectedResources should contain(expected)
}
implicit val canonicalNameGenerator = CanonicalNameGenerator(defaultBasePath)
val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator)
val (ramlUpdated, canonicalLookup) = canonicalTypeCollector.collect(raml)
val userIdUrlParameter: Option[Parameter] =
ramlUpdated.resourceMap("rest").resourceMap("user").resourceMap("userid").urlParameter
userIdUrlParameter.isDefined shouldBe true
val canonicalUrlParamTypeRef: Option[TypeReference] = userIdUrlParameter.flatMap(_.parameterType.canonical)
canonicalUrlParamTypeRef shouldBe Some(StringType)
// val prettyModel = TestUtils.prettyPrint(parsedModel)
// println(s"Parsed raml: $prettyModel")
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/CanonicalName.scala | <reponame>atomicbits/scramlgen<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/CanonicalName.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.
*/
trait CanonicalName {
def name: String
def packagePath: List[String]
}
case class RealCanonicalName private[canonicaltypes] (name: String, packagePath: List[String] = List.empty) extends CanonicalName {
val value: String = s"${packagePath.mkString(".")}.$name"
}
case class NoName private[canonicaltypes] (packagePath: List[String] = List.empty) extends CanonicalName {
override def name: String = "NoName"
}
object CanonicalName {
def create(name: String, packagePath: List[String] = List.empty): CanonicalName =
new RealCanonicalName(cleanClassName(name), cleanPackage(packagePath))
def noName(packagePath: List[String]): CanonicalName = NoName(cleanPackage(packagePath))
def cleanClassName(dirtyName: String): String = {
// capitalize after special characters and drop those characters along the way
// todo: instead of filtering out by listing the 'bad' characters, make a filter that is based on the 'good' characters.
val capitalizedAfterDropChars =
List('-', '_', '+', ' ', '/', '.', '~').foldLeft(dirtyName) { (cleaned, dropChar) =>
cleaned.split(dropChar).filter(_.nonEmpty).map(_.capitalize).mkString("")
}
// capitalize after numbers 0 to 9, but keep the numbers
val capitalized =
(0 to 9).map(_.toString.head).toList.foldLeft(capitalizedAfterDropChars) { (cleaned, numberChar) =>
// Make sure we don't drop the occurrences of numberChar at the end by adding a space and removing it later.
val cleanedWorker = s"$cleaned "
cleanedWorker.split(numberChar).map(_.capitalize).mkString(numberChar.toString).stripSuffix(" ")
}
// final cleanup of all strange characters
prepend$IfStartsWithNumber(dropInvalidCharacters(capitalized))
}
def cleanPackage(pack: List[String]): List[String] = pack.map(cleanClassName).map(_.toLowerCase)
def cleanClassNameFromFileName(fileName: String): String = {
val withOutExtension = fileName.split('.').filter(_.nonEmpty).head
cleanClassName(withOutExtension)
}
private def prepend$IfStartsWithNumber(name: String): String = {
if ((0 to 9).map(number => name.startsWith(number.toString)).reduce(_ || _)) "$" + name
else name
}
private def dropInvalidCharacters(name: String): String = name.replaceAll("[^A-Za-z0-9$_]", "")
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/typemodel/ResourceClassDefinition.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.typemodel
import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform }
import io.atomicbits.scraml.ramlparser.model.Resource
/**
* Created by peter on 13/01/17.
*
* In a resource class definition, we collect all information that is needed to generate a single resource class, independent from
* the target language.
*/
case class ResourceClassDefinition(apiPackage: List[String], precedingUrlSegments: List[String], resource: Resource)
extends SourceDefinition {
val nextPackagePart: String = CleanNameTools.cleanPackageName(resource.urlSegment)
lazy val childResourceDefinitions: List[ResourceClassDefinition] = {
val nextPrecedingUrlSegments = precedingUrlSegments :+ nextPackagePart
resource.resources.map { childResource =>
ResourceClassDefinition(
apiPackage = apiPackage,
precedingUrlSegments = nextPrecedingUrlSegments,
resource = childResource
)
}
}
lazy val resourcePackage: List[String] = apiPackage ++ precedingUrlSegments :+ nextPackagePart
def urlParamClassPointer(): Option[ClassPointer] = {
resource.urlParameter
.map(_.parameterType)
.flatMap(_.canonical)
.map(Platform.typeReferenceToClassPointer)
}
override def classReference(implicit platform: Platform): ClassReference = {
val resourceClassName = s"${CleanNameTools.cleanClassName(resource.urlSegment)}Resource"
ClassReference(name = resourceClassName, packageParts = resourcePackage)
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/ClientClassGenerator.scala | <filename>modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/ClientClassGenerator.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.{ Platform, SourceGenerator }
import io.atomicbits.scraml.generator.typemodel.{ ClassPointer, ClientClassDefinition }
import io.atomicbits.scraml.generator.platform.Platform._
import io.atomicbits.scraml.ramlparser.parser.SourceFile
/**
* Created by peter on 14/01/17.
*/
case class ClientClassGenerator(scalaPlay: ScalaPlay) extends SourceGenerator {
implicit val platform: ScalaPlay = scalaPlay
def generate(generationAggr: GenerationAggr, clientClassDefinition: ClientClassDefinition): GenerationAggr = {
val dslBasePackage = platform.rewrittenDslBasePackage.mkString(".")
val apiPackage = clientClassDefinition.classReference.safePackageParts
val apiClassName = clientClassDefinition.classReference.name
val apiClassReference = clientClassDefinition.classReference
val (importClasses, dslFields, actionFunctions, headerPathSourceDefs) =
clientClassDefinition.topLevelResourceDefinitions match {
case oneRoot :: Nil if oneRoot.resource.urlSegment.isEmpty =>
val dslFields = oneRoot.childResourceDefinitions.map(ResourceClassGenerator(platform).generateResourceDslField)
val SourceCodeFragment(importClasses, actionFunctions, headerPathSourceDefs) =
ActionGenerator(ScalaActionCodeGenerator(platform)).generateActionFunctions(oneRoot)
(importClasses, dslFields, actionFunctions, headerPathSourceDefs)
case manyRoots =>
val importClasses = Set.empty[ClassPointer]
val dslFields = manyRoots.map(ResourceClassGenerator(platform).generateResourceDslField)
val actionFunctions = List.empty[String]
(importClasses, dslFields, actionFunctions, List.empty)
}
val importStatements: Set[String] = platform.importStatements(apiClassReference, importClasses)
val sourcecode =
s"""
package ${apiPackage.mkString(".")}
import $dslBasePackage.client.{ClientFactory, ClientConfig}
import $dslBasePackage.RestException
import $dslBasePackage.RequestBuilder
import $dslBasePackage.client.ning.Ning2ClientFactory
import java.net.URL
import play.api.libs.json._
import java.io._
${importStatements.mkString("\n")}
class $apiClassName(private val _requestBuilder: RequestBuilder) {
import $dslBasePackage._
${dslFields.mkString("\n\n")}
${actionFunctions.mkString("\n\n")}
def close() = _requestBuilder.client.close()
}
object $apiClassName {
import $dslBasePackage.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) : $apiClassName = {
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 $apiClassName(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 $apiClassName(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 RestException(message, resp.status)
}
}
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 RestException(message, resp.status)
}
}
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 RestException(message, resp.status)
}
}
}
}
"""
generationAggr
.addSourceDefinitions(clientClassDefinition.topLevelResourceDefinitions)
.addSourceDefinitions(headerPathSourceDefs)
.addSourceFile(SourceFile(filePath = apiClassReference.toFilePath, content = sourcecode))
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/RamlParser.scala | <filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/RamlParser.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, Paths }
import io.atomicbits.scraml.ramlparser.model.{ JsInclude, Raml }
import play.api.libs.json._
import scala.util.Try
/**
* Created by peter on 6/02/16.
*/
case class RamlParser(ramlSource: String, charsetName: String) {
def parse: Try[Raml] = {
val JsonFile(path, ramlJson) = RamlToJsonParser.parseToJson(ramlSource, charsetName)
val parsed: JsObject =
ramlJson match {
case ramlJsObj: JsObject => parseRamlJsonDocument(path.getParent, ramlJsObj)
case x => sys.error(s"Could not parse $ramlSource, expected a RAML document.")
}
val parseContext = ParseContext(List(ramlSource), List.empty)
Raml(parsed)(parseContext)
}
/**
* Recursively parse all RAML documents by following all include statements and packing everything in one big JSON object.
* The source references will be injected under the "_source" fields so that we can trace the origin of all documents later on.
*
* @param raml
*/
private def parseRamlJsonDocument(basePath: Path, raml: JsObject): JsObject = {
def parseNested(doc: JsValue, currentBasePath: Path): JsValue = {
doc match {
case JsInclude(source) =>
// The check for empty base path below needs to be there for Windows machines, to avoid paths like "/C:/Users/..."
// that don't resolve because of the leading "/".
// ToDo: Refactor to use file system libraries to merge paths (and test on Windows as well).
val nextPath =
if (currentBasePath.normalize().toString.isEmpty) Paths.get(source)
else currentBasePath.resolve(source) // s"$currentBasePath/$source"
val JsonFile(newFilePath, included) = RamlToJsonParser.parseToJson(nextPath.normalize().toString)
included match {
case incl: JsObject => parseNested(incl + (Sourced.sourcefield -> JsString(source)), newFilePath.getParent)
case x => parseNested(x, newFilePath.getParent)
}
case jsObj: JsObject =>
val mappedFields = jsObj.fields.collect {
case (key, value) => key -> parseNested(value, currentBasePath)
}
JsObject(mappedFields)
case jsArr: JsArray => JsArray(jsArr.value.map(parseNested(_, currentBasePath)))
case x => x
}
}
parseNested(raml, basePath).asInstanceOf[JsObject]
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/codegen/CanonicalToSourceDefinitionGenerator.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.Platform
import io.atomicbits.scraml.generator.typemodel._
import io.atomicbits.scraml.ramlparser.model.canonicaltypes.{
CanonicalName,
EnumType,
GenericReferrable,
NonPrimitiveType,
ObjectType,
Property,
TypeReference,
UnionType,
TypeParameter => CanonicalTypeParameter
}
import scala.language.existentials
/**
* Created by peter on 14/01/17.
*
* Transforms a map containing canonical RAML or json-schema types to a sequence of source definitions. The number of
* source definitions isn't always equal to the number of canonical types, because (multiple) inheritance may produce additional
* source definitions.
*/
object CanonicalToSourceDefinitionGenerator {
def transferObjectsToClassDefinitions(generationAggr: GenerationAggr): GenerationAggr = {
// ToDo: see if the following assertion is true for all languages, for now we put this logic in the sourcecode generators.
// We assume here that all our target languages support inheritance, but no multiple inheritance and that
// all languages have a way to express interface definitions in order to 'simulate' the effect, to some extend,
// of multiple inheritance.
// Conclusion so far:
// * SourceDefinitions are generated independent of the target language
// * interface definitions are not generated now, its the target language's responsibility to generate them when necessary while
// generating the source codes (adding those interface definitions to the GenerationAggr for later source code generation).
def objectTypeToTransferObjectClassDefinition(genAggr: GenerationAggr, objectType: ObjectType): GenerationAggr = {
def propertyToField(propertyDef: (String, Property[_ <: GenericReferrable])): Field = {
val (name, property) = propertyDef
val fieldClassPointer =
property.ttype match {
case CanonicalTypeParameter(tParamName) => TypeParameter(tParamName)
case typeReference: TypeReference => Platform.typeReferenceToClassPointer(typeReference)
}
Field(
fieldName = name,
classPointer = fieldClassPointer,
required = property.required
)
}
val canonicalName = objectType.canonicalName
val toClassReference =
ClassReference(
name = canonicalName.name,
packageParts = canonicalName.packagePath,
typeParameters = objectType.typeParameters.map(tp => TypeParameter(tp.name))
)
val transferObjectClassDefinition =
TransferObjectClassDefinition(
reference = toClassReference,
fields = objectType.properties.map(propertyToField).toList,
parents = objectType.parents.flatMap(Platform.typeReferenceToClassReference),
typeDiscriminator = objectType.typeDiscriminator,
typeDiscriminatorValue = objectType.typeDiscriminatorValue
)
genAggr
.addToDefinition(canonicalName, transferObjectClassDefinition)
.addSourceDefinition(transferObjectClassDefinition)
}
def enumTypeToEnumDefinition(genAggr: GenerationAggr, enumType: EnumType): GenerationAggr = {
val enumClassReference =
ClassReference(
name = enumType.canonicalName.name,
packageParts = enumType.canonicalName.packagePath
)
val enumDefinition =
EnumDefinition(
reference = enumClassReference,
values = enumType.choices
)
genAggr.addSourceDefinition(enumDefinition)
}
def unionTypeToUnionClassDefinition(genAggr: GenerationAggr, unionType: UnionType): GenerationAggr = {
val unionClassReference =
ClassReference(
name = unionType.canonicalName.name,
packageParts = unionType.canonicalName.packagePath
)
val unionClassDefinition =
UnionClassDefinition(
reference = unionClassReference,
union = unionType.types.map(Platform.typeReferenceToClassPointer)
)
genAggr.addSourceDefinition(unionClassDefinition)
}
generationAggr.canonicalToMap.values.foldLeft(generationAggr) { (genAggr, nonPrimitiveType) =>
nonPrimitiveType match {
case objectType: ObjectType => objectTypeToTransferObjectClassDefinition(genAggr, objectType)
case enumType: EnumType => enumTypeToEnumDefinition(genAggr, enumType)
case unionType: UnionType => unionTypeToUnionClassDefinition(genAggr, unionType)
case unexpected => sys.error(s"Unexpected type seen during TO definition generation: $unexpected")
}
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/javajackson/JavaJackson.scala | <filename>modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/javajackson/JavaJackson.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.platform.Platform
/**
* Created by peter on 10/01/17.
*/
case class JavaJackson(apiBasePackageParts: List[String]) extends CommonJavaJacksonPlatform {
implicit val platform: Platform = this
val name: String = "Java Jackson"
override val dslBasePackageParts: List[String] = List("io", "atomicbits", "scraml", "dsl", "javajackson")
override val rewrittenDslBasePackage: List[String] = apiBasePackageParts ++ List("dsl", "javajackson")
}
|
atomicbits/scramlgen | modules/scraml-gen-simulation/src/test/scala/io/atomicbits/scraml/client/manual/Animal.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.client.manual
import io.atomicbits.scraml.dsl.scalaplay.json.TypedJson._
import play.api.libs.json.{ Format, Json }
sealed trait Animal {
def gender: String
}
sealed trait Mammal extends Animal {
def name: Option[String]
}
object Mammal {
implicit val mammalFormat: Format[Mammal] =
TypeHintFormat(
"type",
Cat.jsonFormatter.withTypeHint("Cat"),
Dog.jsonFormatter.withTypeHint("Dog")
)
}
case class Cat(gender: String, name: Option[String] = None) extends Mammal
object Cat {
implicit val jsonFormatter: Format[Cat] = Json.format[Cat]
}
case class Dog(gender: String, name: Option[String] = None, canBark: Boolean = true) extends Mammal
object Dog {
implicit val jsonFormatter: Format[Dog] = Json.format[Dog]
}
case class Fish(gender: String) extends Animal
object Fish {
implicit val jsonFormatter: Format[Fish] = Json.format[Fish]
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedDate.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 play.api.libs.json.{ JsString, JsValue }
import io.atomicbits.scraml.ramlparser.model._
import io.atomicbits.scraml.ramlparser.parser.JsUtils._
import scala.util.{ Success, Try }
/**
* Created by peter on 26/08/16.
*/
trait ParsedDate extends NonPrimitiveType with AllowedAsObjectField {
def format: DateFormat
def model: TypeModel = RamlModel
def asTypeModel(typeModel: TypeModel): ParsedType = this
}
/**
* date-only The "full-date" notation of RFC3339, namely yyyy-mm-dd. Does not support time or time zone-offset notation.
*
* example: 2015-05-23
*/
case class ParsedDateOnly(id: Id = ImplicitId, required: Option[Boolean] = None) extends ParsedDate {
val format = RFC3339FullDate
def asRequired = copy(required = Some(true))
override def updated(updatedId: Id): ParsedDateOnly = copy(id = updatedId)
}
case object ParsedDateOnly {
val value = "date-only"
def unapply(json: JsValue): Option[Try[ParsedDateOnly]] = {
ParsedType.typeDeclaration(json).collect {
case JsString(ParsedDateOnly.value) => Success(ParsedDateOnly(required = json.fieldBooleanValue("required")))
}
}
}
/**
* time-only The "partial-time" notation of RFC3339, namely hh:mm:ss[.ff...]. Does not support date or time zone-offset notation.
*
* example: 12:30:00
*/
case class ParsedTimeOnly(id: Id = ImplicitId, required: Option[Boolean] = None) extends ParsedDate {
val format = RFC3339PartialTime
def asRequired = copy(required = Some(true))
override def updated(updatedId: Id): ParsedTimeOnly = copy(id = updatedId)
}
case object ParsedTimeOnly {
val value = "time-only"
def unapply(json: JsValue): Option[Try[ParsedTimeOnly]] = {
ParsedType.typeDeclaration(json).collect {
case JsString(ParsedTimeOnly.value) => Success(ParsedTimeOnly(required = json.fieldBooleanValue("required")))
}
}
}
/**
* datetime-only Combined date-only and time-only with a separator of "T", namely yyyy-mm-ddThh:mm:ss[.ff...]. Does not support
* a time zone offset.
*
* example: 2015-07-04T21:00:00
*/
case class ParsedDateTimeOnly(id: Id = ImplicitId, required: Option[Boolean] = None) extends ParsedDate {
val format = DateOnlyTimeOnly
def asRequired = copy(required = Some(true))
override def updated(updatedId: Id): ParsedDateTimeOnly = copy(id = updatedId)
}
case object ParsedDateTimeOnly {
val value = "datetime-only"
def unapply(json: JsValue): Option[Try[ParsedDateTimeOnly]] = {
ParsedType.typeDeclaration(json).collect {
case JsString(ParsedDateTimeOnly.value) => Success(ParsedDateTimeOnly(required = json.fieldBooleanValue("required")))
}
}
}
/**
* datetime A timestamp in one of the following formats: if the format is omitted or set to rfc3339, uses the "date-time" notation
* of RFC3339; if format is set to rfc2616, uses the format defined in RFC2616.
*
* example: 2016-02-28T16:41:41.090Z
* format: rfc3339 # the default, so no need to specify
*
* example: Sun, 28 Feb 2016 16:41:41 GMT
* format: rfc2616 # this time it's required, otherwise, the example format is invalid
*/
sealed trait ParsedDateTime extends ParsedDate
object ParsedDateTime {
val value = "datetime"
}
case class ParsedDateTimeDefault(id: Id = ImplicitId, required: Option[Boolean] = None) extends ParsedDateTime {
val format = RFC3339DateTime
def asRequired = copy(required = Some(true))
override def updated(updatedId: Id): ParsedDateTimeDefault = copy(id = updatedId)
}
case object ParsedDateTimeDefault {
def unapply(json: JsValue): Option[Try[ParsedDateTimeDefault]] = {
val isValid = json.fieldStringValue("format").forall(_.toLowerCase == "rfc3339")
ParsedType.typeDeclaration(json).collect {
case JsString(ParsedDateTime.value) if isValid =>
Success(ParsedDateTimeDefault(required = json.fieldBooleanValue("required")))
}
}
}
case class ParsedDateTimeRFC2616(id: Id = ImplicitId, required: Option[Boolean] = None) extends ParsedDateTime {
val format = RFC2616
def asRequired = copy(required = Some(true))
override def updated(updatedId: Id): ParsedDateTimeRFC2616 = copy(id = updatedId)
}
case object ParsedDateTimeRFC2616 {
def unapply(json: JsValue): Option[Try[ParsedDateTimeRFC2616]] = {
val isValid = json.fieldStringValue("format").exists(_.toLowerCase == "rfc2616")
ParsedType.typeDeclaration(json).collect {
case JsString(ParsedDateTime.value) if isValid =>
Success(ParsedDateTimeRFC2616(required = json.fieldBooleanValue("required")))
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/htmldoc/HtmlDoc.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.htmldoc
import java.nio.file.{ Path, Paths }
import io.atomicbits.scraml.generator.codegen.GenerationAggr
import io.atomicbits.scraml.generator.platform.Platform
import io.atomicbits.scraml.generator.typemodel._
/**
* Created by peter on 9/05/18.
*/
object HtmlDoc extends Platform {
val name = "HTML Documentation"
override def apiBasePackageParts = List.empty[String]
override def dslBasePackageParts = List.empty[String]
override def rewrittenDslBasePackage = List.empty[String]
override def classPointerToNativeClassReference(classPointer: ClassPointer) = ???
override def implementingInterfaceReference(classReference: ClassReference) = ???
override def classDefinition(classPointer: ClassPointer, fullyQualified: Boolean) = ???
override def className(classPointer: ClassPointer) = ???
override def packageName(classPointer: ClassPointer) = ???
override def fullyQualifiedName(classPointer: ClassPointer) = ???
override def safePackageParts(classPointer: ClassPointer) = ???
override def safeFieldName(fieldName: String) = ???
override def fieldDeclarationWithDefaultValue(field: Field) = ???
override def fieldDeclaration(field: Field) = ???
override def importStatements(targetClassReference: ClassPointer, dependencies: Set[ClassPointer]) = ???
override def toSourceFile(generationAggr: GenerationAggr, toClassDefinition: TransferObjectClassDefinition) = generationAggr
override def toSourceFile(generationAggr: GenerationAggr, toInterfaceDefinition: TransferObjectInterfaceDefinition) = generationAggr
override def toSourceFile(generationAggr: GenerationAggr, enumDefinition: EnumDefinition) = generationAggr
override def toSourceFile(generationAggr: GenerationAggr, clientClassDefinition: ClientClassDefinition) =
IndexDocGenerator.generate(generationAggr, clientClassDefinition)
override def toSourceFile(generationAggr: GenerationAggr, resourceClassDefinition: ResourceClassDefinition) = generationAggr
override def toSourceFile(generationAggr: GenerationAggr, headerSegmentClassDefinition: HeaderSegmentClassDefinition) = generationAggr
override def toSourceFile(generationAggr: GenerationAggr, unionClassDefinition: UnionClassDefinition) = generationAggr
val classFileExtension = "html"
/**
* Transforms a given class reference to a file path. The given class reference already has clean package and class names.
*
* @param classPointer The class reference for which a file path is generated.
* @return The relative file name for the given class.
*/
override def toFilePath(classPointer: ClassPointer): Path = {
classPointer match {
case classReference: ClassReference =>
Paths.get("", s"${classReference.name}.$classFileExtension") // 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!")
}
}
override def reservedKeywords = Set.empty[String]
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/typescript/ToClassGenerator.scala | <filename>modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/typescript/ToClassGenerator.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.SourceGenerator
import io.atomicbits.scraml.generator.typemodel.{ TransferObjectClassDefinition, TransferObjectInterfaceDefinition }
import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName
/**
* Created by peter on 15/12/17.
*/
case class ToClassGenerator(typeScript: TypeScript) extends SourceGenerator {
val defaultDiscriminator = "type"
implicit val platform: TypeScript = typeScript
def generate(generationAggr: GenerationAggr, toClassDefinition: TransferObjectClassDefinition): GenerationAggr = {
val originalToCanonicalName = toClassDefinition.reference.canonicalName
val parentNames: List[CanonicalName] = generationAggr.allParents(originalToCanonicalName)
val recursiveExtendedParents =
parentNames.foldLeft(Seq.empty[TransferObjectClassDefinition]) { (aggr, parentName) =>
val interfaces = aggr
val parentDefinition: TransferObjectClassDefinition =
generationAggr.toMap.getOrElse(parentName, sys.error(s"Expected to find $parentName in the generation aggregate."))
interfaces :+ parentDefinition
}
val discriminator: String =
(toClassDefinition.typeDiscriminator +: recursiveExtendedParents.map(_.typeDiscriminator)).flatten.headOption
.getOrElse(defaultDiscriminator)
// register all parents for interface generation
val parentInterfacesToGenerate =
recursiveExtendedParents.map(TransferObjectInterfaceDefinition(_, discriminator))
val generationAggrWithParentInterfaces =
parentInterfacesToGenerate.foldLeft(generationAggr) { (aggr, parentInt) =>
aggr.addInterfaceSourceDefinition(parentInt)
}
val interfaceDefinition = TransferObjectInterfaceDefinition(toClassDefinition, discriminator)
generationAggrWithParentInterfaces.addInterfaceSourceDefinition(interfaceDefinition) // We only generate interfaces
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedFragmentContainer.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.{ JsObject, JsValue }
import scala.util.{ Try }
/**
* Created by peter on 22/12/16.
*/
object ParsedFragmentContainer {
def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[Fragments]] = {
(ParsedType.typeDeclaration(json), (json \ "properties").toOption, json) match {
case (None, None, jsObj: JsObject) => Some(Fragments(jsObj))
case _ => None
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Traits.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 io.atomicbits.scraml.ramlparser.parser.{ KeyedList, ParseContext, RamlParseException }
import play.api.libs.json._
import scala.util.{ Failure, Success, Try }
/**
* Created by peter on 10/02/16.
*/
case class Traits(traitsMap: Map[String, JsObject]) extends ModelMerge {
/**
* Apply the matching traits in this to the given JsObject by deep-copying the objects and
* giving priority to the given jsObject when collisions should occur.
*/
def applyToAction[T](jsObject: JsObject)(f: JsObject => Try[T])(implicit parseContext: ParseContext): Try[T] = {
mergeInToAction(jsObject).flatMap(f)
}
def mergeInToAction(actionJsObj: JsObject)(implicit parseContext: ParseContext): Try[JsObject] = {
val appliedTraits: MergeApplicationMap = findMergeNames(actionJsObj, Traits.selectionKey)
applyToForMergeNames(actionJsObj, appliedTraits, traitsMap)
}
def mergeInToActionFromResource(actionJsObj: JsObject, resourceJsObj: JsObject)(implicit parseContext: ParseContext): Try[JsObject] = {
val appliedTraits: MergeApplicationMap = findMergeNames(resourceJsObj, Traits.selectionKey)
applyToForMergeNames(actionJsObj, appliedTraits, traitsMap)
}
}
object Traits {
val selectionKey: String = "is"
def apply(): Traits = Traits(Map.empty[String, JsObject])
def apply(json: JsValue)(implicit parseContext: ParseContext): Try[Traits] = {
def doApply(trsJson: JsValue): Try[Traits] = {
trsJson match {
case traitsJsObj: JsObject => Success(Traits(traitsJsObjToTraitMap(traitsJsObj)))
case traitsJsArr: JsArray => Success(Traits(traitsJsObjToTraitMap(KeyedList.toJsObject(traitsJsArr))))
case x =>
Failure(
RamlParseException(s"The traits definition in ${parseContext.head} is malformed.")
)
}
}
def traitsJsObjToTraitMap(traitsJsObj: JsObject): Map[String, JsObject] = {
traitsJsObj.fields.collect {
case (key: String, value: JsObject) => key -> value
}.toMap
}
parseContext.withSourceAndUrlSegments(json)(doApply(json))
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/Method.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.dsl.scalaplay
/**
* Created by peter on 21/05/15, Atomic BITS (http://atomicbits.io).
*/
sealed trait Method
case object Get extends Method {
override def toString = "GET"
}
case object Post extends Method {
override def toString = "POST"
}
case object Put extends Method {
override def toString = "PUT"
}
case object Delete extends Method {
override def toString = "DELETE"
}
case object Head extends Method {
override def toString = "HEAD"
}
case object Opt extends Method {
override def toString = "OPTIONS"
}
case object Patch extends Method {
override def toString = "PATCH"
}
case object Trace extends Method {
override def toString = "TRACE"
}
case object Connect extends Method {
override def toString = "CONNECT"
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/CanonicalLookupHelper.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, NonPrimitiveType }
import io.atomicbits.scraml.ramlparser.model.parsedtypes.{ ParsedNull, ParsedType }
import org.slf4j.{ Logger, LoggerFactory }
/**
* Created by peter on 17/12/16.
*/
/**
*
* @param parsedTypeIndex The types that are explicitely declared the in the Raml model's types declaration and
* those that are implicitely declared inside the resource's parameters (e.g. GET parameters)
* and body content of responses and replies. Each type declaration is keyed on its
* native (RAML) id.
* @param referenceOnlyParsedTypeIndex Like parsedTypeIndex, but the elements in this index will not be used directly to create
* canonical types later on. This index will only contain the Selection elements of a json-schema
* object. We need to be able to look up those elements, but we will generate their canonical
* form through their parent.
* @param lookupTable The canonical lookup map.
* @param jsonSchemaNativeToAbsoluteIdMap Native references may be used in the RAML definition to refer to json-schema types that
* have their own json-schema id internally. This map enables us to translate the canonical
* name that matches the native id to the canonical name that matches the json-schema id.
*/
case class CanonicalLookupHelper(lookupTable: Map[CanonicalName, NonPrimitiveType] = Map.empty,
parsedTypeIndex: Map[UniqueId, ParsedType] = Map.empty,
referenceOnlyParsedTypeIndex: Map[UniqueId, ParsedType] = Map.empty,
jsonSchemaNativeToAbsoluteIdMap: Map[NativeId, AbsoluteId] = Map.empty) {
val logger: Logger = LoggerFactory.getLogger(CanonicalLookupHelper.getClass)
def getParsedTypeWithProperId(id: Id): Option[ParsedType] = {
val parsedTypeOpt =
id match {
case NoId =>
Some(ParsedNull())
case nativeId: NativeId =>
val realIndex = jsonSchemaNativeToAbsoluteIdMap.getOrElse(nativeId, nativeId)
List(parsedTypeIndex.get(realIndex), referenceOnlyParsedTypeIndex.get(realIndex)).flatten.headOption
case uniqueId: UniqueId =>
List(parsedTypeIndex.get(uniqueId), referenceOnlyParsedTypeIndex.get(uniqueId)).flatten.headOption
case other => None
}
parsedTypeOpt.map { parsedType =>
parsedType.id match {
case ImplicitId => parsedType.updated(id)
case other => parsedType
}
}
}
def addCanonicalType(canonicalName: CanonicalName, canonicalType: NonPrimitiveType): CanonicalLookupHelper =
copy(lookupTable = lookupTable + (canonicalName -> canonicalType))
def addParsedTypeIndex(id: Id, parsedType: ParsedType, lookupOnly: Boolean = false): CanonicalLookupHelper = {
def warnDuplicate(uniqueId: UniqueId, parsedT: ParsedType): Unit = {
parsedTypeIndex.get(uniqueId).collect {
case pType if pType != parsedT => logger.debug(s"Duplicate type definition found for id $uniqueId")
}
()
}
id match {
case uniqueId: UniqueId =>
if (lookupOnly) {
copy(referenceOnlyParsedTypeIndex = referenceOnlyParsedTypeIndex + (uniqueId -> parsedType))
} else {
warnDuplicate(uniqueId, parsedType)
copy(parsedTypeIndex = parsedTypeIndex + (uniqueId -> parsedType))
}
case _ => this
}
}
def addJsonSchemaNativeToAbsoluteIdTranslation(jsonSchemaNativeId: NativeId, jsonSchemaAbsoluteId: AbsoluteId): CanonicalLookupHelper =
copy(jsonSchemaNativeToAbsoluteIdMap = jsonSchemaNativeToAbsoluteIdMap + (jsonSchemaNativeId -> jsonSchemaAbsoluteId))
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/parser/ParseContext.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 io.atomicbits.scraml.ramlparser.model.{ MediaType, ResourceTypes, Traits }
import play.api.libs.json.{ JsString, JsValue }
/**
* Created by peter on 10/02/16.
*/
case class ParseContext(var sourceTrail: List[String],
var urlSegments: List[String],
resourceTypes: ResourceTypes = ResourceTypes(),
traits: Traits = Traits(),
defaultMediaType: Option[MediaType] = None) {
def withSourceAndUrlSegments[T](jsValue: JsValue, urlSegs: List[String] = List.empty)(fn: => T): T = {
val sourceTrailOrig = sourceTrail
val urlSegmentsOrig = urlSegments
sourceTrail =
(jsValue \ Sourced.sourcefield).toOption.collect {
case JsString(source) => source :: sourceTrailOrig
} getOrElse {
sourceTrailOrig
}
urlSegments = urlSegmentsOrig ++ urlSegs
val result = fn
sourceTrail = sourceTrailOrig
urlSegments = urlSegmentsOrig
result
}
def head: String = sourceTrail.head
def resourcePath: String = {
val resourcePathOptExt = urlSegments.mkString("/")
if (resourcePathOptExt.endsWith("{ext}")) resourcePathOptExt.dropRight(5)
else resourcePathOptExt
}
def resourcePathName: String = {
def stripParamSegments(reverseUrlSegs: List[String]): String =
reverseUrlSegs match {
case urlSeg :: urlSegs if urlSeg.contains('{') && urlSeg.contains('}') => stripParamSegments(urlSegs)
case urlSeg :: urlSegs => urlSeg
case Nil => ""
}
stripParamSegments(urlSegments.reverse)
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/formatting/ScalaFormatter.scala | <filename>modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/formatting/ScalaFormatter.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.formatting
import scalariform.formatter.preferences._
import scala.util.Try
/**
* Created by peter on 17/07/17.
*/
object ScalaFormatter {
private val formatSettings =
FormattingPreferences()
.setPreference(AlignParameters, true)
.setPreference(AlignSingleLineCaseStatements, true)
.setPreference(DoubleIndentConstructorArguments, true)
.setPreference(IndentSpaces, 2)
def format(code: String): String = Try(scalariform.formatter.ScalaFormatter.format(code, formatSettings)).getOrElse(code)
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/htmldoc/simplifiedmodel/BodyContentRenderer.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.generator.util.CleanNameUtil
import io.atomicbits.scraml.ramlparser.model.canonicaltypes._
/**
* Created by peter on 11/06/18.
*/
case class BodyContentRenderer(generationAggr: GenerationAggr) {
def renderHtmlForType(typeReference: TypeReference,
recursiveCanonicals: Set[CanonicalName] = Set.empty,
typeParameterMap: Map[TypeParameter, TypeReference] = Map.empty,
suffix: String = "",
required: Option[Boolean] = None,
description: Option[String] = None,
expandedLevels: Int = 5): String = {
def getSuffixes(items: List[_]): List[String] = {
items match {
case Nil => List.empty
case it :: Nil => List("")
case it :: its => ", " :: getSuffixes(its)
}
}
val comment =
(required, description) match {
case (Some(true), Some(desc)) => s" // (required) $desc"
case (_, Some(desc)) => s" // $desc"
case (_, None) => ""
}
typeReference match {
case BooleanType => s"""<span class="primitivetype">boolean$suffix$comment</span>"""
case StringType => s"""<span class="primitivetype">string$suffix$comment</span>"""
case JsonType => s"""<span class="primitivetype">json$suffix$comment</span>"""
case IntegerType => s"""<span class="primitivetype">integer$suffix$comment</span>"""
case NumberType => s"""<span class="primitivetype">number$suffix$comment</span>"""
case NullType => s"""<span class="primitivetype">null$suffix$comment</span>"""
case FileType => s"""<span class="primitivetype">file$suffix$comment</span>"""
case DateTimeDefaultType =>
s"""<span class="primitivetype">datetime (rfc3339: yyyy-MM-dd'T'HH:mm:ss[.SSS]XXX)$suffix$comment</span>"""
case DateTimeRFC2616Type =>
s"""<span class="primitivetype">datetime (rfc2616: EEE, dd MMM yyyy HH:mm:ss 'GMT')$suffix$comment</span>"""
case DateTimeOnlyType => s"""<span class="primitivetype">datetime-only (yyyy-MM-dd'T'HH:mm:ss[.SSS])$suffix$comment</span>"""
case TimeOnlyType => s"""<span class="primitivetype">time-only (HH:mm:ss[.SSS])$suffix$comment</span>"""
case DateOnlyType => s"""<span class="primitivetype">date-only (yyyy-MM-dd)$suffix$comment</span>"""
case ArrayTypeReference(genericType) =>
genericType match {
case typeReference: TypeReference =>
s"""
|<span>[</span>${renderHtmlForType(typeReference, recursiveCanonicals)}<span>]$suffix$comment</span>
""".stripMargin
case TypeParameter(paramName) => s"type parameter$suffix$comment"
}
case NonPrimitiveTypeReference(refers, genericTypes, genericTypeParameters) =>
(refers, generationAggr.canonicalToMap.get(refers)) match {
case (ref, _) if recursiveCanonicals.contains(ref) => "" // ToDo: render recursive object type.
case (ref, None) => ""
case (ref, Some(objectType: ObjectType)) =>
val tpMap =
genericTypeParameters
.zip(genericTypes)
.collect {
case (tp, tr: TypeReference) => (tp, tr)
// We don't consider transitive type parameters yet, that's why we ignore the case for
// (tp1, tp2: TypeParameter) for now. (ToDo: https://github.com/atomicbits/scraml/issues/37)
}
.toMap
// objectType.typeDiscriminator // ToDo
// objectType.typeDiscriminatorValue // ToDo
val recCanonicals = recursiveCanonicals + refers
val propertyList = objectType.properties.values.toList
val suffixes = getSuffixes(propertyList)
val propertiesWithSuffixes = propertyList.zip(suffixes)
val renderedProperties =
propertiesWithSuffixes.map {
case (property, suffx) => renderProperty(property, recCanonicals, tpMap, suffx, expandedLevels - 1)
}
s"""
|<span>{</span>
| ${renderedProperties.mkString}
|<span>}$suffix</span>
""".stripMargin
case (ref, Some(enumType: EnumType)) =>
s"""<span class="primitivetype">${enumType.choices.map(CleanNameUtil.quoteString).mkString(" | ")}$suffix$comment</span>"""
case (ref, Some(union: UnionType)) => "ToDo: render union types"
}
case other => s"Unknown type representation for $other$suffix$comment"
}
}
private def renderProperty(property: Property[_],
recCanonicals: Set[CanonicalName],
tpMap: Map[TypeParameter, TypeReference],
propSuffix: String,
expLevels: Int): String = {
val renderedType = {
val typeReferenceOpt: Option[TypeReference] =
property.ttype match {
case tr: TypeReference => Some(tr)
case tp: TypeParameter => tpMap.get(tp)
}
typeReferenceOpt.map { tr =>
renderHtmlForType(
typeReference = tr,
recursiveCanonicals = recCanonicals,
typeParameterMap = tpMap,
suffix = propSuffix,
required = Some(property.required),
description = None, // property.description // Todo: add the description to the parsed properties
expandedLevels = expLevels
)
} getOrElse ""
}
s"""
|<div class='indent'>
| <span>\"${property.name}\":</span>$renderedType
|</div>
""".stripMargin
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Response.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
import io.atomicbits.scraml.ramlparser.parser.ParseContext
import play.api.libs.json.JsValue
import scala.util.Try
/**
* Created by peter on 10/02/16.
*/
case class Response(status: StatusCode, headers: Parameters, body: Body, description: Option[String] = None) // ToDo add description from parsed model
object Response {
val value = "responses"
def unapply(statusAndJsValue: (String, JsValue))(implicit parseContext: ParseContext): Option[Try[Response]] = {
val (statusString, json) = statusAndJsValue
val status = StatusCode(statusString)
val tryHeaders = Parameters((json \ "headers").toOption)
val tryBody = Body(json)
val tryResponse =
for {
headers <- tryHeaders
body <- tryBody
} yield Response(status, headers, body)
Some(tryResponse)
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/transformers/ParsedEnumTransformer.scala | <filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/transformers/ParsedEnumTransformer.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.transformers
import io.atomicbits.scraml.ramlparser.lookup.{ CanonicalLookupHelper, CanonicalNameGenerator }
import io.atomicbits.scraml.ramlparser.model.canonicaltypes._
import io.atomicbits.scraml.ramlparser.model.parsedtypes.{ ParsedEnum, ParsedType }
/**
* Created by peter on 30/12/16.
*/
object ParsedEnumTransformer {
// 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
def registerParsedEnum(parsedEnum: ParsedEnum, canonicalName: CanonicalName): (TypeReference, CanonicalLookupHelper) = {
val enumType =
EnumType(
canonicalName = canonicalName,
choices = parsedEnum.choices
)
val typeReference: TypeReference = NonPrimitiveTypeReference(canonicalName)
(typeReference, canonicalLookupHelper.addCanonicalType(canonicalName, enumType))
}
// Generate the canonical name for this object
val canonicalName = canonicalNameOpt.getOrElse(canonicalNameGenerator.generate(parsed.id))
(parsed, canonicalName) match {
case (parsedEnum: ParsedEnum, NoName(_)) => Some((JsonType, canonicalLookupHelper))
case (parsedEnum: ParsedEnum, _) => Some(registerParsedEnum(parsedEnum, canonicalName))
case _ => None
}
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/client/ning/Ning2BinaryData.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.client.ning
import java.io.InputStream
import java.nio.charset.Charset
import io.atomicbits.scraml.dsl.scalaplay.BinaryData
/**
* Created by peter on 21/01/16.
*/
class Ning2BinaryData(val innerResponse: org.asynchttpclient.Response) extends BinaryData {
override def asBytes: Array[Byte] = innerResponse.getResponseBodyAsBytes
override def asString: String = innerResponse.getResponseBody
override def asString(charset: String): String = innerResponse.getResponseBody(Charset.forName(charset))
/**
* Request the binary data as a stream. This is convenient when there is a large amount of data to receive.
* You can only request the input stream once because the data is not stored along the way!
* Do not close the stream after use.
*
* @return An inputstream for reading the binary data.
*/
override def asStream: InputStream = innerResponse.getResponseBodyAsStream
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/HttpParam.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 io.atomicbits.scraml.dsl.scalaplay.json.JsonOps
import play.api.libs.json._
/**
* Created by peter on 27/07/15.
*/
sealed trait HttpParam
case object HttpParam {
def toFormUrlEncoded(json: JsValue): Map[String, HttpParam] = {
def flatten(jsObj: JsObject): Map[String, HttpParam] = {
jsObj.value.collect {
case (field, JsString(value)) => field -> SimpleHttpParam.create(value)
case (field, JsNumber(value)) => field -> SimpleHttpParam.create(value)
case (field, JsBoolean(value)) => field -> SimpleHttpParam.create(value)
case (field, jsObj: JsObject) => field -> SimpleHttpParam.create(jsObj)
}.toMap
}
json match {
case jsObject: JsObject => flatten(jsObject)
case other => Map.empty
}
}
}
case class SimpleHttpParam(parameter: String) extends HttpParam
object SimpleHttpParam {
def create(value: Any): SimpleHttpParam = SimpleHttpParam(value.toString)
}
case class ComplexHttpParam(json: String) extends HttpParam
object ComplexHttpParam {
def create[P](value: P)(implicit formatter: Format[P]): ComplexHttpParam =
ComplexHttpParam(JsonOps.toString(formatter.writes(value)))
}
case class RepeatedHttpParam(parameters: List[String]) extends HttpParam
object RepeatedHttpParam {
def create(values: List[Any]): RepeatedHttpParam = RepeatedHttpParam(values.map(_.toString))
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/javajackson/ClientClassGenerator.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, GenerationAggr, SourceCodeFragment }
import io.atomicbits.scraml.generator.platform.SourceGenerator
import io.atomicbits.scraml.generator.typemodel.{ ClassPointer, ClientClassDefinition }
import io.atomicbits.scraml.generator.platform.Platform._
import io.atomicbits.scraml.generator.platform.androidjavajackson.AndroidJavaJackson
import io.atomicbits.scraml.ramlparser.parser.SourceFile
/**
* Created by peter on 1/03/17.
*/
case class ClientClassGenerator(javaJackson: CommonJavaJacksonPlatform) extends SourceGenerator {
implicit val platform: CommonJavaJacksonPlatform = javaJackson
def generate(generationAggr: GenerationAggr, clientClassDefinition: ClientClassDefinition): GenerationAggr = {
val apiPackage = clientClassDefinition.classReference.safePackageParts
val apiClassName = clientClassDefinition.classReference.name
val apiClassReference = clientClassDefinition.classReference
val (importClasses, dslFields, actionFunctions, headerPathSourceDefs) =
clientClassDefinition.topLevelResourceDefinitions match {
case oneRoot :: Nil if oneRoot.resource.urlSegment.isEmpty =>
val dslFields = oneRoot.childResourceDefinitions.map(ResourceClassGenerator(platform).generateResourceDslField)
val SourceCodeFragment(importClasses, actionFunctions, headerPathSourceDefs) =
ActionGenerator(new JavaActionCodeGenerator(platform)).generateActionFunctions(oneRoot)
(importClasses, dslFields, actionFunctions, headerPathSourceDefs)
case manyRoots =>
val importClasses = Set.empty[ClassPointer]
val dslFields = manyRoots.map(ResourceClassGenerator(platform).generateResourceDslField)
val actionFunctions = List.empty[String]
(importClasses, dslFields, actionFunctions, List.empty)
}
val importStatements: Set[String] = platform.importStatements(apiClassReference, importClasses)
val dslBasePackage = platform.rewrittenDslBasePackage.mkString(".")
val (defaultClientFactory, defaultClientImportStatement) =
platform match {
case android: AndroidJavaJackson =>
val defaultCF = "OkHttpScramlClientFactory"
val defaultCIS = s"import $dslBasePackage.client.okhttp.$defaultCF;"
(defaultCF, defaultCIS)
case _ =>
val defaultCF = "Ning2ClientFactory"
val defaultCIS = s"import $dslBasePackage.client.ning.$defaultCF;"
(defaultCF, defaultCIS)
}
val sourcecode =
s"""
package ${apiPackage.mkString(".")};
import $dslBasePackage.RequestBuilder;
import $dslBasePackage.client.ClientConfig;
import $dslBasePackage.client.ClientFactory;
import $dslBasePackage.Client;
$defaultClientImportStatement
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.io.*;
${importStatements.mkString("\n")}
public class $apiClassName {
private RequestBuilder _requestBuilder = new RequestBuilder();
public $apiClassName(String host,
int port,
String protocol,
String prefix,
ClientConfig clientConfig,
Map<String, String> defaultHeaders) {
this(host, port, protocol, prefix, clientConfig, defaultHeaders, null);
}
public $apiClassName(String host,
int port,
String protocol,
String prefix,
ClientConfig clientConfig,
Map<String, String> defaultHeaders,
ClientFactory clientFactory) {
ClientFactory cFactory = clientFactory != null ? clientFactory : new $defaultClientFactory();
Client client = cFactory.createClient(host, port, protocol, prefix, clientConfig, defaultHeaders);
this._requestBuilder.setClient(client);
}
${dslFields.mkString("\n\n")}
${actionFunctions.mkString("\n\n")}
public RequestBuilder getRequestBuilder() {
return this._requestBuilder;
}
public void close() throws Exception {
this._requestBuilder.getClient().close();
}
}
"""
generationAggr
.addSourceDefinitions(clientClassDefinition.topLevelResourceDefinitions)
.addSourceDefinitions(headerPathSourceDefs)
.addSourceFile(SourceFile(filePath = apiClassReference.toFilePath, content = sourcecode))
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/codegen/DslSourceExtractor.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.codegen
import io.atomicbits.scraml.generator.platform.Platform
import io.atomicbits.scraml.ramlparser.parser.{ SourceFile, SourceReader }
import org.slf4j.{ Logger, LoggerFactory }
import scala.util.{ Failure, Success, Try }
/**
* Created by peter on 12/04/17.
*/
object DslSourceExtractor {
val logger: Logger = LoggerFactory.getLogger(DslSourceExtractor.getClass)
@volatile
var cache: Map[(String, String), Set[SourceFile]] = Map.empty
/**
* Extract all source files from the DSL jar dependency.
*
* @param platform The platform.
* @return A set of source files wrapped in a Try monad. On read exceptions, the Try will be a Failure.
*/
def extract()(implicit platform: Platform): Set[SourceFile] = {
val baseDir = platform.dslBaseDir
val extension = platform.classFileExtension
cache.getOrElse((baseDir, extension), fetchFiles(baseDir, extension))
}
private def fetchFiles(baseDir: String, extension: String): Set[SourceFile] = {
val files =
DslSourceExtractor.synchronized { // opening the same jar file several times in parallel... it doesn't work well
Try(SourceReader.readResources(baseDir, s".$extension")) match {
case Success(theFiles) => theFiles
case Failure(exception) =>
logger.debug(
s"""
|Could not read the DSL source files from $baseDir with extension $extension
|The exception was:
|${exception.getClass.getName}
|${exception.getMessage}
""".stripMargin
)
Set.empty[SourceFile]
}
}
add(baseDir, extension, files)
files
}
private def add(baseDir: String, extension: String, files: Set[SourceFile]): Unit = {
val baseDirAndExtension = (baseDir, extension)
DslSourceExtractor.synchronized {
cache += baseDirAndExtension -> files
}
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/client/ning/Ning2ClientFactory.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.client.ning
import io.atomicbits.scraml.dsl.scalaplay.Client
import io.atomicbits.scraml.dsl.scalaplay.client.{ ClientConfig, ClientFactory }
import scala.util.{ Failure, Try }
/**
* Created by peter on 8/01/16.
*/
object Ning2ClientFactory extends ClientFactory {
override def createClient(protocol: String,
host: String,
port: Int,
prefix: Option[String],
config: ClientConfig,
defaultHeaders: Map[String, String]): Try[Client] = {
Try {
new Ning2Client(protocol, host, port, prefix, config, defaultHeaders)
} recoverWith {
case cnfe: NoClassDefFoundError =>
Failure(
new NoClassDefFoundError(
s"${cnfe.getMessage}} The Scraml ning client factory cannot find the necessary ning dependencies to instantiate its client. Did you add the necessary ning dependencies to your project?"
)
)
case e => Failure(e)
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/javajackson/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.javajackson
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.util.CleanNameUtil
import io.atomicbits.scraml.generator.platform.Platform._
import io.atomicbits.scraml.ramlparser.parser.SourceFile
/**
* Created by peter on 1/03/17.
*/
case class EnumGenerator(javaJackson: CommonJavaJacksonPlatform) extends SourceGenerator {
implicit val platform: Platform = javaJackson
def generate(generationAggr: GenerationAggr, enumDefinition: EnumDefinition): GenerationAggr = {
// Accompany the enum names with their 'Java-safe' name.
val enumsWithSafeName =
enumDefinition.values map { value =>
val safeName = javaJackson.escapeJavaKeyword(CleanNameUtil.cleanEnumName(value))
s"""$safeName("$value")""" // e.g. space("spa ce")
}
val classNameCamel = CleanNameUtil.camelCased(enumDefinition.reference.name)
val source =
s"""
package ${enumDefinition.reference.packageName};
import com.fasterxml.jackson.annotation.*;
public enum ${enumDefinition.reference.name} {
${enumsWithSafeName.mkString("", ",\n", ";\n")}
private final String value;
private ${enumDefinition.reference.name}(final String value) {
this.value = value;
}
@JsonValue
final String value() {
return this.value;
}
@JsonCreator
public static ${enumDefinition.reference.name} fromValue(String value) {
for (${enumDefinition.reference.name} $classNameCamel : ${enumDefinition.reference.name}.values()) {
if (value.equals($classNameCamel.value())) {
return $classNameCamel;
}
}
throw new IllegalArgumentException("Cannot instantiate a ${enumDefinition.reference.name} enum element from " + value);
}
public String toString() {
return value();
}
}
"""
val sourceFile =
SourceFile(
filePath = enumDefinition.reference.toFilePath,
content = source
)
generationAggr.addSourceFile(sourceFile)
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/codegen/ActionFunctionGenerator.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._
import io.atomicbits.scraml.generator.typemodel._
import io.atomicbits.scraml.ramlparser.model.Parameter
/**
* Created by peter on 20/01/17.
*/
case class ActionFunctionGenerator(actionCode: ActionCode) {
def generate(actionSelection: ActionSelection): SourceCodeFragment = {
actionSelection.selectedContentType match {
case x: FormPostContentType => generateFormAction(actionSelection, x)
case _: MultipartFormContentType => generateMultipartFormPostAction(actionSelection)
case _: BinaryContentType => generateBodyAction(actionSelection, binary = true)
case _: AnyContentType => generateBodyAction(actionSelection, binary = true)
case x => generateBodyAction(actionSelection, binary = false)
}
}
def generateFormAction(actionSelection: ActionSelection, formPostContentType: FormPostContentType): SourceCodeFragment = {
val actualFormParameters: Map[String, Parameter] = formPostContentType.formParameters.valueMap
val formParameterMethodParameterCode: List[SourceCodeFragment] =
actionCode.sortQueryOrFormParameters(actualFormParameters.toList).map { paramPair =>
val (name, param) = paramPair
actionCode.expandQueryOrFormParameterAsMethodParameter((name, param))
}
val formParameterMethodParameterImports = formParameterMethodParameterCode.flatMap(_.imports)
val formParameterMethodParameters = formParameterMethodParameterCode.flatMap(_.sourceDefinition)
val formParameterMapEntries: List[String] =
actualFormParameters.map {
case (name, parameter) => actionCode.expandQueryOrFormParameterAsMapEntry((name, parameter))
}.toList
val queryStringType = actionCode.queryStringType(actionSelection)
val formAction: String =
actionCode.generateAction(
actionSelection = actionSelection,
bodyType = None,
queryStringType = queryStringType,
isBinary = false,
actionParameters = formParameterMethodParameters,
formParameterMapEntries = formParameterMapEntries,
contentType = actionSelection.selectedContentType,
responseType = actionSelection.selectedResponseType
)
val actionFunctionDefinitions = List(formAction)
val actionImports = generateActionImports(actionSelection)
SourceCodeFragment(imports = actionImports ++ formParameterMethodParameterImports, sourceDefinition = actionFunctionDefinitions)
}
def generateMultipartFormPostAction(actionSelection: ActionSelection): SourceCodeFragment = {
val queryStringType = actionCode.queryStringType(actionSelection)
val multipartAction: String =
actionCode.generateAction(
actionSelection = actionSelection,
bodyType = None,
queryStringType = queryStringType,
isBinary = false,
actionParameters = actionCode.expandMethodParameter(List("parts" -> ListClassPointer(BodyPartClassPointer))),
isMultipartParams = true,
contentType = actionSelection.selectedContentType,
responseType = actionSelection.selectedResponseType
)
val actionFunctionDefinitions = List(multipartAction)
val actionImports = generateActionImports(actionSelection)
SourceCodeFragment(imports = actionImports, sourceDefinition = actionFunctionDefinitions)
}
def generateBodyAction(actionSelection: ActionSelection, binary: Boolean): SourceCodeFragment = {
/**
* In scala, we can get compiler issues with default values on overloaded action methods. That's why we don't add
* a default value in such cases. We do this any time when there are overloaded action methods, i.e. when there
* are multiple body types.
*/
val bodyTypes = actionCode.bodyTypes(actionSelection)
// Scala action methods will have trouble with default query parameter values when there are more than one body types.
// Repetition of the action method will cause compiler conflicts in that case, so default values must be omitted then.
val noDefault = bodyTypes.size > 1
val queryParameterMethodParameterCode: List[SourceCodeFragment] =
actionCode
.sortQueryOrFormParameters(actionSelection.action.queryParameters.valueMap.toList)
.map(actionCode.expandQueryOrFormParameterAsMethodParameter(_, noDefault))
val queryParameterMethodParameterImports = queryParameterMethodParameterCode.flatMap(_.imports)
val queryParameterMethodParameters = queryParameterMethodParameterCode.flatMap(_.sourceDefinition)
val queryStringMethodParameterCode: SourceCodeFragment =
actionSelection.action.queryString.map(actionCode.expandQueryStringAsMethodParameter).getOrElse(SourceCodeFragment())
val queryStringMethodParameterImports = queryStringMethodParameterCode.imports
val queryStringMethodParameters = queryStringMethodParameterCode.sourceDefinition
val queryStringType = actionCode.queryStringType(actionSelection)
val actionFunctionDefinitions =
bodyTypes.map { bodyType =>
val actionBodyParameter =
bodyType.map(bdType => actionCode.expandMethodParameter(List("body" -> bdType))).getOrElse(List.empty)
val allActionParameters = actionBodyParameter ++ queryParameterMethodParameters ++ queryStringMethodParameters
val segmentBodyType = if (binary) None else bodyType
actionCode.generateAction(
actionSelection = actionSelection,
bodyType = bodyType,
queryStringType = queryStringType,
isBinary = binary,
actionParameters = allActionParameters,
isTypedBodyParam = actionBodyParameter.nonEmpty && !binary,
isBinaryParam = actionBodyParameter.nonEmpty && binary,
contentType = actionSelection.selectedContentType,
responseType = actionSelection.selectedResponseType
)
}
val actionImports = generateActionImports(actionSelection)
SourceCodeFragment(imports = actionImports ++ queryParameterMethodParameterImports ++ queryStringMethodParameterImports,
sourceDefinition = actionFunctionDefinitions)
}
private def generateActionImports(actionSelection: ActionSelection): Set[ClassPointer] = {
// Todo: add the imports from the Parameters (headers / query parameters)
// actionSelection.action.queryParameters
// actionSelection.action.headers
val bodyTypes = actionCode.bodyTypes(actionSelection).flatten.toSet
val responseTypes = actionCode.responseTypes(actionSelection).flatten.toSet
bodyTypes ++ responseTypes
}
}
case class SourceCodeFragment(imports: Set[ClassPointer] = Set.empty,
sourceDefinition: List[String] = List.empty,
headerPathClassDefinitions: List[SourceDefinition] = List.empty) {
def ++(other: SourceCodeFragment): SourceCodeFragment =
SourceCodeFragment(imports ++ other.imports,
sourceDefinition ++ other.sourceDefinition,
headerPathClassDefinitions ++ other.headerPathClassDefinitions)
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedBoolean.scala | <reponame>atomicbits/scramlgen<filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedBoolean.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 }
import scala.util.{ Success, Try }
import io.atomicbits.scraml.ramlparser.parser.JsUtils._
/**
* Created by peter on 1/04/16.
*/
case class ParsedBoolean(id: Id = ImplicitId, required: Option[Boolean] = None, model: TypeModel = RamlModel)
extends PrimitiveType
with AllowedAsObjectField {
override def updated(updatedId: Id): ParsedBoolean = copy(id = updatedId)
override def asTypeModel(typeModel: TypeModel): ParsedType = copy(model = typeModel)
}
object ParsedBoolean {
val value = "boolean"
def apply(json: JsValue): Try[ParsedBoolean] = {
val model: TypeModel = TypeModel(json)
val id = JsonSchemaIdExtractor(json)
Success(
ParsedBoolean(
id = id,
required = json.fieldBooleanValue("required"),
model
)
)
}
def unapply(json: JsValue): Option[Try[ParsedBoolean]] = {
(ParsedType.typeDeclaration(json), json) match {
case (Some(JsString(ParsedBoolean.value)), _) => Some(ParsedBoolean(json))
case (_, JsString(ParsedBoolean.value)) => Some(Success(new ParsedBoolean()))
case _ => None
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/htmldoc/simplifiedmodel/SimpleResponse.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.htmldoc.simplifiedmodel
import io.atomicbits.scraml.generator.codegen.GenerationAggr
import io.atomicbits.scraml.ramlparser.model.{ Parameters, Response, StatusCode }
/**
* Created by peter on 7/06/18.
*/
case class SimpleResponse(status: StatusCode, headers: Parameters, body: SimpleBody, description: Option[String])
object SimpleResponse {
def apply(response: Response, generationAggr: GenerationAggr): SimpleResponse = {
SimpleResponse(
status = response.status,
headers = response.headers,
body = SimpleBody(response.body, generationAggr),
description = response.description
)
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/ParsedToCanonicalTypeTransformer.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 org.slf4j.{ Logger, LoggerFactory }
import io.atomicbits.scraml.ramlparser.lookup.transformers._
import io.atomicbits.scraml.ramlparser.model.canonicaltypes._
import io.atomicbits.scraml.ramlparser.model.parsedtypes._
/**
* Created by peter on 17/12/16.
*/
object ParsedToCanonicalTypeTransformer {
val LOGGER: Logger = LoggerFactory.getLogger("ParsedToCanonicalTypeTransformer")
/**
* Transform the given parsed type to a canonical type, recursively parsing and registering all internal parsed types .
*
* @param parsed The parsed type to transform.
* @param canonicalLookupHelper This canonical lookup helper registers all internal parsed types that we see while processing the
* given parsed type.
* @return
*/
// format: off
def transform(parsed: ParsedType,
canonicalLookupHelper: CanonicalLookupHelper,
canonicalName: Option[CanonicalName] = None)
(implicit canonicalNameGenerator: CanonicalNameGenerator): (GenericReferrable, CanonicalLookupHelper) = { // format: on
ParsedTypeContext(parsed, canonicalLookupHelper, canonicalName) match {
case ParsedObjectTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedTypeReferenceTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedEnumTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedArrayTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedBooleanTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedStringTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedNumberTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedIntegerTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedNullTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedGenericObjectTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedDateTransformer(typeReference, updatedLookupHelper) => (typeReference, updatedLookupHelper)
case ParsedTypeContext(fragments: Fragments, _, _, _, _) =>
LOGGER.info(s"Skipped unknown json-schema fragments.")
(NullType, canonicalLookupHelper)
case FallbackTransformer(typeReference, updatedLookupHelper) =>
println(s"WARNING: type ${parsed.getClass.getSimpleName} is not yet supported, we use 'string' as the fallback type for now.")
(typeReference, updatedLookupHelper)
// Currently not yet supported:
// case parsedFile: ParsedFile => ???
// case parsedNull: ParsedNull => ???
// case parsedUnionType: ParsedUnionType => ???
case x => sys.error(s"Error transforming $x")
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/CaseClassGenerator.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 CaseClassGenerator(scalaPlay: ScalaPlay) extends SourceGenerator {
val defaultDiscriminator = "type"
implicit val platform: ScalaPlay = scalaPlay
def generate(generationAggr: GenerationAggr, toClassDefinition: TransferObjectClassDefinition): GenerationAggr = {
/**
* TOs are represented as case classes in Scala and because case classes cannot inherit from each other, we need to work around
* polymorphism using traits. In particular, we need to create a specific trait for each case class that takes part in a subclass
* relation, except for the leaf classes (which don't have any children). Multiple-inheritance is solved using traits as well.
*/
// We need to mark each parent to need a trait of its own that contains the fields of that parent and we will implement the traits
// of all parents in this case class.
val originalToCanonicalName = toClassDefinition.reference.canonicalName
val hasOwnTrait = generationAggr.isParent(originalToCanonicalName)
val actualToCanonicalClassReference: ClassReference =
if (hasOwnTrait) toClassDefinition.implementingInterfaceReference
else toClassDefinition.reference
val initialTosWithTrait: Seq[TransferObjectClassDefinition] =
if (hasOwnTrait) Seq(toClassDefinition)
else Seq.empty
val initialFields: Seq[Field] = toClassDefinition.fields
// Add all parents recursively as traits to implement and collect all fields.
val parentNames: List[CanonicalName] = generationAggr.allParents(originalToCanonicalName)
val traitsAndFieldsAggr = (initialTosWithTrait, initialFields)
val (recursiveExtendedTraits, collectedFields) =
parentNames.foldLeft(traitsAndFieldsAggr) { (aggr, parentName) =>
val (traits, fields) = aggr
val parentDefinition: TransferObjectClassDefinition =
generationAggr.toMap.getOrElse(parentName, sys.error(s"Expected to find $parentName in the generation aggregate."))
val withParentFields = fields ++ parentDefinition.fields
val withParentTrait = traits :+ parentDefinition
(withParentTrait, withParentFields)
}
val discriminator: String =
(toClassDefinition.typeDiscriminator +: recursiveExtendedTraits.map(_.typeDiscriminator)).flatten.headOption
.getOrElse(defaultDiscriminator)
val jsonTypeInfo: Option[JsonTypeInfo] =
if (generationAggr.isInHierarchy(originalToCanonicalName)) {
Some(JsonTypeInfo(discriminator = discriminator, discriminatorValue = toClassDefinition.actualTypeDiscriminatorValue))
} else {
None
}
val traitsToImplement =
generationAggr
.directParents(originalToCanonicalName)
.filter { parent => // ToDo: simplify this!!! If hasOwnTrait, then no parent traits are implemented, only its own trait is!!!
if (hasOwnTrait) !generationAggr.isParentOf(parent, originalToCanonicalName)
else true
}
.foldLeft(initialTosWithTrait) { (traitsToImpl, parentName) =>
val parentDefinition =
generationAggr.toMap.getOrElse(parentName, sys.error(s"Expected to find $parentName in the generation aggregate."))
traitsToImpl :+ parentDefinition
}
.map(TransferObjectInterfaceDefinition(_, discriminator))
val traitsToGenerate = recursiveExtendedTraits.map(TransferObjectInterfaceDefinition(_, discriminator))
// add the collected traits to the generationAggr.toInterfaceMap if they aren't there yet
val generationAggrWithAddedInterfaces =
traitsToGenerate.foldLeft(generationAggr) { (aggr, collectedTrait) =>
aggr.addInterfaceSourceDefinition(collectedTrait)
}
// We know that Play Json 2.4 has trouble with empty case classes, so we inject a random non-required field in that case
val atLeastOneField =
if (collectedFields.nonEmpty) collectedFields
else Seq(Field(fieldName = s"__injected_field", classPointer = StringClassPointer, required = false))
val recursiveFields: Set[Field] = findRecursiveFields(atLeastOneField, toClassDefinition.reference :: toClassDefinition.parents)
generateCaseClass(
traitsToImplement,
atLeastOneField,
jsonTypeInfo.map(_.discriminator),
recursiveFields,
actualToCanonicalClassReference,
jsonTypeInfo,
generationAggrWithAddedInterfaces
)
}
/**
* Find all recursive fields.
*
* All fields that have a type or a type with a type parameter (1) that refers to the containing type or one of its parents is a
* recursive definition.
* (1) We mean all type parameters recursively, as in {@code List[List[Geometry]] } should be lazy as well.
*
* @param fields The fields to test for recursion.
* @param selfAndParents The current TO class reference and all its parents.
* @return The set containing all fields that have a recursive type.
*/
private def findRecursiveFields(fields: Seq[Field], selfAndParents: List[ClassReference]): Set[Field] = {
def isRecursive(field: Field): Boolean = isRecursiveClassReference(field.classPointer.native)
def isRecursiveClassReference(classReference: ClassReference): Boolean = {
val hasRecursiveType = selfAndParents.contains(classReference)
val typeParamClassReferences = classReference.typeParamValues.map(_.native)
typeParamClassReferences.foldLeft(hasRecursiveType) {
case (aggr, typeParamClassReference) => aggr || isRecursiveClassReference(typeParamClassReference.native)
}
}
fields.foldLeft(Set.empty[Field]) {
case (recursiveFields, field) if isRecursive(field) => recursiveFields + field
case (recursiveFields, field) => recursiveFields
}
}
private def generateCaseClass(traits: Seq[TransferObjectInterfaceDefinition],
fields: Seq[Field],
skipFieldName: Option[String],
recursiveFields: Set[Field],
toClassReference: ClassReference,
jsonTypeInfo: Option[JsonTypeInfo],
generationAggr: GenerationAggr): GenerationAggr = {
val importPointers = {
val ownFields = fields.map(_.classPointer) // includes all the fields of its parents for case classes
val traitsToExtend = traits.map(_.classReference)
(ownFields ++ traitsToExtend).toSet
}
val imports: Set[String] = platform.importStatements(toClassReference, importPointers)
val typeHintImport =
if (jsonTypeInfo.isDefined) {
val dslBasePackage = platform.rewrittenDslBasePackage.mkString(".")
s"import $dslBasePackage.json.TypedJson._"
} else {
""
}
val sortedFields = selectAndSortFields(fields, skipFieldName)
val source =
s"""
package ${toClassReference.packageName}
import play.api.libs.json._
$typeHintImport
${imports.mkString("\n")}
${generateCaseClassDefinition(traits, sortedFields, toClassReference)}
${generateCompanionObject(sortedFields, recursiveFields, toClassReference, jsonTypeInfo)}
"""
val sourceFile =
SourceFile(
filePath = toClassReference.toFilePath,
content = source
)
generationAggr.addSourceFile(sourceFile)
}
private def selectAndSortFields(fields: Seq[Field], skipFieldName: Option[String] = None): Seq[Field] = {
val selectedFields =
skipFieldName.map { skipField: String =>
fields.filterNot(_.fieldName == skipField)
}.getOrElse(fields)
val sortedFields = selectedFields.sortBy(field => (!field.required, field.fieldName))
sortedFields
}
private def generateCaseClassDefinition(traits: Seq[TransferObjectInterfaceDefinition],
sortedFields: Seq[Field],
toClassReference: ClassReference): String = {
val fieldExpressions = sortedFields.map(_.fieldDeclarationWithDefaultValue)
val extendedTraitDefs = traits.map(_.classReference.classDefinition)
val extendsExpression =
if (extendedTraitDefs.nonEmpty) extendedTraitDefs.mkString("extends ", " with ", "")
else ""
// format: off
s"""
case class ${toClassReference.classDefinition}(${fieldExpressions.mkString(",")}) $extendsExpression
"""
// format: on
}
private def generateCompanionObject(sortedFields: Seq[Field],
recursiveFields: Set[Field],
toClassReference: ClassReference,
jsonTypeInfo: Option[JsonTypeInfo]): String = {
val formatUnLiftFields = sortedFields.map(field => platform.fieldFormatUnlift(field, recursiveFields))
def complexFormatterDefinition: (String, String) =
("import play.api.libs.functional.syntax._", s"def jsonFormatter: Format[${toClassReference.classDefinition}] = ")
def complexTypedFormatterDefinition: (String, String) = {
/*
* This is the only way we know that formats typed variables, but it has problems with recursive types,
* (see https://www.playframework.com/documentation/2.4.x/ScalaJsonCombinators#Recursive-Types).
*/
val typeParametersFormat = toClassReference.typeParameters.map(typeParameter => s"${typeParameter.name}: Format")
(s"import play.api.libs.functional.syntax._",
s"def jsonFormatter[${typeParametersFormat.mkString(",")}]: Format[${toClassReference.classDefinition}] = ")
}
def singleFieldFormatterBody =
s"${formatUnLiftFields.head}.inmap(${toClassReference.name}.apply, unlift(${toClassReference.name}.unapply))"
def multiFieldFormatterBody =
s"""
( ${formatUnLiftFields.mkString("~\n")}
)(${toClassReference.name}.apply, unlift(${toClassReference.name}.unapply))
"""
def over22FieldFormatterBody = {
val groupedFields: List[List[Field]] = sortedFields.toList.grouped(22).toList
val (fieldGroupDefinitions, fieldGroupNames, groupedFieldDeclarations): (List[String], List[String], List[String]) =
groupedFields.zipWithIndex.map {
case (group, index) =>
val formatFields = group.map(field => platform.fieldFormatUnlift(field, recursiveFields))
val fieldGroupName = s"fieldGroup$index"
val fieldGroupDefinition =
if (formatFields.size > 1) {
s"""
val fieldGroup$index =
(${formatFields.mkString("~\n")}).tupled
"""
} else {
s"""
val fieldGroup$index =
(${formatFields.mkString("~\n")})
"""
}
val fieldDeclarations = group.map { field =>
if (field.required)
platform.classDefinition(field.classPointer)
else
s"Option[${platform.classDefinition(field.classPointer)}]"
}
val groupedFieldDeclaration =
if (fieldDeclarations.size > 1) {
s"""(${fieldDeclarations.mkString(", ")})"""
} else {
fieldDeclarations.head
}
(fieldGroupDefinition, fieldGroupName, groupedFieldDeclaration)
}.foldRight((List.empty[String], List.empty[String], List.empty[String])){ // unzip with 3 elements
case ((definition, group, ttype), (defList, groupList, typeList)) =>
( definition :: defList, group :: groupList, ttype :: typeList)
}
s""" {
${fieldGroupDefinitions.mkString("\n")}
def pack: (${groupedFieldDeclarations.mkString(", ")}) => ${toClassReference.name} = {
case (${groupedFields.map { group =>
s"(${group.map(_.safeDeconstructionName).mkString(", ")})"
}.mkString(", ")}) =>
${toClassReference.name}.apply(${sortedFields.map(_.safeDeconstructionName).mkString(", ")})
}
def unpack: ${toClassReference.name} => (${groupedFieldDeclarations.mkString(", ")}) = {
cclass =>
(${groupedFields.map { group =>
s"(${group.map(_.safeFieldName).map(cf => s"cclass.$cf").mkString(", ")})"
}.mkString(", ")})
}
(${fieldGroupNames.mkString(" and ")}).apply(pack, unpack)
}
"""
}
/**
* The reason why we like to use the easy macro version below is that it resolves issues like the recursive
* type problem that the elaborate "Complex version" has
* (see https://www.playframework.com/documentation/2.4.x/ScalaJsonCombinators#Recursive-Types)
* Types like the one below cannot be formatted with the "Complex version":
*
* > case class Tree(value: String, children: List[Tree])
*
* To format it with the "Complex version" has to be done as follows:
*
* > case class Tree(value: String, children: List[Tree])
* > object Tree {
* > import play.api.libs.functional.syntax._
* > implicit def jsonFormatter: Format[Tree] = // Json.format[Tree]
* > ((__ \ "value").format[String] ~
* > (__ \ "children").lazyFormat[List[Tree]](Reads.list[Tree](jsonFormatter), Writes.list[Tree](jsonFormatter)))(Tree.apply, unlift(Tree.unapply))
* > }
*
* To format it with the "Easy version" is simply:
*
* > implicit val jsonFormatter: Format[Tree] = Json.format[Tree]
*
*/
def simpleFormatter: (String, String) =
("", s"val jsonFormatter: Format[${toClassReference.classDefinition}] = Json.format[${toClassReference.classDefinition}]")
val hasTypeVariables = toClassReference.typeParameters.nonEmpty
val anyFieldRenamed = sortedFields.exists(field => field.fieldName != field.safeFieldName)
val hasSingleField = formatUnLiftFields.size == 1
val hasOver22Fields = formatUnLiftFields.size > 22
val hasJsonTypeInfo = jsonTypeInfo.isDefined
val hasRecursiveFields = recursiveFields.nonEmpty
// ToDo: Inject the json type discriminator and its value on the write side if there is one defined.
// ToDo: make jsonFormatter not implicit and use it in the TypeHint in Animal and make a new implicit typedJsonFormatter that extends
// ToDo: the jsonFormatter with the type discriminator and its value. Peek in the TypeHint implementation for how to do the latter
val ((imports, formatter), body) =
(hasTypeVariables, anyFieldRenamed, hasSingleField, hasOver22Fields, hasJsonTypeInfo, hasRecursiveFields) match {
case (true, _, true, _, _, _) => (complexTypedFormatterDefinition, singleFieldFormatterBody)
case (true, _, _, true, _, _) => (complexTypedFormatterDefinition, over22FieldFormatterBody)
case (true, _, _, _, _, _) => (complexTypedFormatterDefinition, multiFieldFormatterBody)
case (false, _, true, _, _, _) => (complexFormatterDefinition, singleFieldFormatterBody)
case (false, _, _, true, _, _) => (complexFormatterDefinition, over22FieldFormatterBody)
case (false, true, false, _, _, _) => (complexFormatterDefinition, multiFieldFormatterBody)
case (false, false, _, _, _, true) => (complexFormatterDefinition, multiFieldFormatterBody)
case (false, false, _, _, _, false) => (simpleFormatter, "")
}
val objectName = toClassReference.name
// The default formatter is implicit only when there is no need to inject a type descriminator.
val implicitFormatterOrNot = if (hasJsonTypeInfo) "" else "implicit"
val formatterWithTypeField =
jsonTypeInfo.map { jsTypeInfo =>
s"""
implicit val jsonFormat: Format[$objectName] =
TypeHintFormat(
"${jsTypeInfo.discriminator}",
$objectName.jsonFormatter.withTypeHint("${jsTypeInfo.discriminatorValue}")
)
"""
}.getOrElse("")
s"""
object $objectName {
$imports
$implicitFormatterOrNot $formatter $body
$formatterWithTypeField
}
"""
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/CleanNameTools.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
/**
* Created by peter on 13/01/17.
*/
trait CleanNameTools { // ToDo: this is a duplicate of CleanNameUtil, so refactor and remove one of the two
def cleanClassNameFromFileName(fileName: String): String = {
val withOutExtension = fileName.split('.').filter(_.nonEmpty).head
cleanClassName(withOutExtension)
}
def cleanClassName(dirtyName: String): String = {
// capitalize after special characters and drop those characters along the way
// todo: instead of filtering out by listing the 'bad' characters, make a filter that is based on the 'good' characters.
val capitalizedAfterDropChars =
List('-', '_', '+', ' ', '/', '.', '~').foldLeft(dirtyName) { (cleaned, dropChar) =>
cleaned.split(dropChar).filter(_.nonEmpty).map(_.capitalize).mkString("")
}
// capitalize after numbers 0 to 9, but keep the numbers
val capitalized =
(0 to 9).map(_.toString.head).toList.foldLeft(capitalizedAfterDropChars) { (cleaned, numberChar) =>
// Make sure we don't drop the occurrences of numberChar at the end by adding a space and removing it later.
val cleanedWorker = s"$cleaned "
cleanedWorker.split(numberChar).map(_.capitalize).mkString(numberChar.toString).stripSuffix(" ")
}
// final cleanup of all strange characters
prepend$IfStartsWithNumber(dropInvalidCharacters(capitalized))
}
def cleanMethodName: String => String = cleanFieldName
def cleanEnumName: String => String = cleanFieldName
def cleanFieldName(dirtyName: String): String = {
// we don't do capitalization on field names, we keep them as close to the original as possible!
// we cannot begin with a number, so we prepend a '$' when the first character is a number
prepend$IfStartsWithNumber(dropInvalidCharacters(dirtyName))
}
private def prepend$IfStartsWithNumber(name: String): String = {
if ((0 to 9).map(number => name.startsWith(number.toString)).reduce(_ || _)) "$" + name
else name
}
private def dropInvalidCharacters(name: String): String = name.replaceAll("[^A-Za-z0-9$_]", "")
def camelCased(dirtyName: String): String = {
val chars = dirtyName.toCharArray
chars(0) = chars(0).toLower
new String(chars)
}
def cleanPackageName(dirtyName: String): String = {
cleanClassName(dirtyName).toLowerCase
}
def quoteString(text: String): String = s""""$text""""
}
object CleanNameTools extends CleanNameTools
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/htmldoc/simplifiedmodel/SimpleBodyContent.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.htmldoc.simplifiedmodel
import io.atomicbits.scraml.generator.codegen.GenerationAggr
import io.atomicbits.scraml.ramlparser.model.{ BodyContent, MediaType, Parameters, TypeRepresentation }
/**
* Created by peter on 7/06/18.
*/
case class SimpleBodyContent(mediaType: MediaType, bodyType: Option[TypeRepresentation], formParameters: Parameters, html: String)
object SimpleBodyContent {
def apply(bodyContent: BodyContent, generationAggr: GenerationAggr): SimpleBodyContent = {
val html = {
for {
bt <- bodyContent.bodyType
canonical <- bt.canonical
} yield BodyContentRenderer(generationAggr).renderHtmlForType(canonical)
} getOrElse ""
SimpleBodyContent(
mediaType = bodyContent.mediaType,
bodyType = bodyContent.bodyType,
formParameters = bodyContent.formParameters,
html = html
)
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/test/scala/io/atomicbits/scraml/dsl/scalaplay/client/ning/Ning2ClientTest.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.client.ning
import io.atomicbits.scraml.dsl.scalaplay.client.ClientConfig
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen }
import org.scalatest.featurespec.AnyFeatureSpec
/**
* Created by peter on 22/04/16.
*/
class Ning2ClientTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll with ScalaFutures {
Feature("Extracting the charset from the response headers") {
Scenario("test a valid charset in a response header") {
Given("A ning client")
val client = Ning2Client(
protocol = "http",
host = "localhost",
port = 8080,
prefix = None,
config = ClientConfig(),
defaultHeaders = Map.empty
)
val headers = Map(
"Accept" -> List("application/json", "application/bson"),
"Content-Type" -> List("application/json;charset=ascii")
)
When("the charset value is requested")
val charsetValue: Option[String] = client.getResponseCharsetFromHeaders(headers)
Then("the charset from the content-type header is returned")
assert(charsetValue == Some("US-ASCII"))
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedProperties.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.{ TypeModel, TypeRepresentation }
import io.atomicbits.scraml.ramlparser.parser.ParseContext
import io.atomicbits.scraml.util.TryUtils._
import play.api.libs.json.{ JsObject, JsValue }
import scala.util.{ Success, Try }
/**
* Created by peter on 4/12/16.
*/
case class ParsedProperties(valueMap: Map[String, ParsedProperty] = Map.empty) {
def apply(name: String): ParsedProperty = valueMap(name)
def get(name: String): Option[ParsedProperty] = valueMap.get(name)
def -(name: String): ParsedProperties = copy(valueMap = valueMap - name)
def map(f: ParsedProperty => ParsedProperty): ParsedProperties = {
copy(valueMap = valueMap.mapValues(f).toMap)
}
def asTypeMap: Map[String, ParsedType] = {
valueMap.mapValues(_.propertyType.parsed)
}.toMap
val values: List[ParsedProperty] = valueMap.values.toList
val types: List[ParsedType] = valueMap.values.map(_.propertyType.parsed).toList
val isEmpty = valueMap.isEmpty
}
object ParsedProperties {
def apply(jsValueOpt: Option[JsValue], model: TypeModel)(implicit parseContext: ParseContext): Try[ParsedProperties] = {
/**
* @param name The name of the property
* @return A pair whose first element is de actual property name and the second element indicates whether or not the
* property is an optional property. None (no indication for optional is given) Some(false) (it is an optional property).
*/
def detectRequiredPropertyName(name: String): (String, Option[Boolean]) = {
if (name.length > 1 && name.endsWith("?")) (name.dropRight(1), Some(false))
else (name, None)
}
def jsObjectToProperties(jsObject: JsObject): Try[ParsedProperties] = {
val valueMap: Map[String, Try[ParsedProperty]] =
jsObject.value
.mapValues(model.mark)
.collect {
case (name, ParsedType(tryType)) =>
val (actualName, requiredProp) = detectRequiredPropertyName(name)
actualName -> tryType.map { paramType =>
val paramTypeWithRightTypeModel = paramType.asTypeModel(model)
ParsedProperty(
name = actualName,
propertyType = TypeRepresentation(paramTypeWithRightTypeModel),
required = requiredProp.getOrElse(
paramTypeWithRightTypeModel.required.getOrElse(
paramTypeWithRightTypeModel.defaultRequiredValue
)
)
)
}
}.toMap
accumulate(valueMap).map(vm => ParsedProperties(vm))
}
jsValueOpt.collect {
case jsObj: JsObject => jsObjectToProperties(jsObj)
} getOrElse Success(ParsedProperties())
}
}
|
atomicbits/scramlgen | project/Dependencies.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>
*
*/
import sbt._
object Dependencies {
// main dependencies
val logback = "ch.qos.logback" % "logback-classic" % "1.1.1"
// java dsl dependencies
val jacksonAnnotations = "com.fasterxml.jackson.core" % "jackson-annotations" % "2.5.4"
val jacksonCore = "com.fasterxml.jackson.core" % "jackson-core" % "2.5.4"
val jacksonDatabind = "com.fasterxml.jackson.core" % "jackson-databind" % "2.5.4"
val snakeYaml = "org.yaml" % "snakeyaml" % "1.16"
// val asyncClientOld = "com.ning" % "async-http-client" % "1.9.40" % "provided"
val asyncClientProvided = "org.asynchttpclient" % "async-http-client" % "2.8.1" % "provided"
val okHttpProvided = "com.squareup.okhttp3" % "okhttp" % "3.9.0" % "provided"
val playJson = "com.typesafe.play" %% "play-json" % "2.8.1"
val scalariform = "org.scalariform" %% "scalariform" % "0.2.10"
val javaFormat = "com.google.googlejavaformat" % "google-java-format" % "1.2"
val mustacheJava = "com.github.spullara.mustache.java" % "compiler" % "0.9.5"
val slf4j = "org.slf4j" % "slf4j-api" % "1.7.25"
// test dependencies
val scalaTest = "org.scalatest" %% "scalatest" % "3.1.0" % "test"
val wiremock = "com.github.tomakehurst" % "wiremock" % "1.57" % "test"
val junit = "junit" % "junit" % "4.12" % "test"
val asyncClientTest = "org.asynchttpclient" % "async-http-client" % "2.8.1" % "test"
val scramlRamlParserDeps = Seq(
playJson,
snakeYaml,
slf4j
)
// inclusion of the above dependencies in the modules
val scramlGeneratorDeps = Seq(
scalariform,
javaFormat,
mustacheJava,
junit
)
val scramlDslDepsScala = Seq(
slf4j,
playJson,
asyncClientProvided
)
val scramlDslDepsAndroid = Seq(
slf4j,
junit,
jacksonCore,
jacksonAnnotations,
jacksonDatabind,
okHttpProvided
)
val scramlDslDepsJava = Seq(
slf4j,
junit,
jacksonCore,
jacksonAnnotations,
jacksonDatabind,
asyncClientProvided
)
val mainDeps = Seq(
logback
)
val testDeps = Seq(
scalaTest,
wiremock,
asyncClientTest
)
val allDeps = mainDeps ++ testDeps
}
|
atomicbits/scramlgen | version.sbt | <reponame>atomicbits/scramlgen
version in ThisBuild := "0.9.1-SNAPSHOT"
// To publish to https://oss.sonatype.org/#stagingRepositories
// +publishSigned
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/scalaplay/HeaderSegmentClassGenerator.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.scalaplay
import io.atomicbits.scraml.generator.codegen.{ DslSourceRewriter, GenerationAggr }
import io.atomicbits.scraml.generator.platform.{ Platform, SourceGenerator }
import io.atomicbits.scraml.generator.typemodel.HeaderSegmentClassDefinition
import io.atomicbits.scraml.ramlparser.parser.SourceFile
/**
* Created by peter on 18/01/17.
*/
case class HeaderSegmentClassGenerator(scalaPlay: ScalaPlay) extends SourceGenerator {
import Platform._
implicit val platform: ScalaPlay = scalaPlay
def generate(generationAggr: GenerationAggr, headerSegmentClassDefinition: HeaderSegmentClassDefinition): GenerationAggr = {
val dslBasePackage = platform.rewrittenDslBasePackage.mkString(".")
val className = headerSegmentClassDefinition.reference.name
val packageName = headerSegmentClassDefinition.reference.packageName
val imports = platform.importStatements(headerSegmentClassDefinition.reference, headerSegmentClassDefinition.imports)
val methods = headerSegmentClassDefinition.methods
val source =
s"""
package $packageName
import $dslBasePackage._
import play.api.libs.json._
import java.io._
${imports.mkString("\n")}
class $className(_req: RequestBuilder) extends HeaderSegment(_req) {
${methods.mkString("\n")}
}
"""
val filePath = headerSegmentClassDefinition.reference.toFilePath
generationAggr.addSourceFile(SourceFile(filePath = filePath, content = source))
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/transformers/ParsedObjectTransformer.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, ParsedToCanonicalTypeTransformer }
import io.atomicbits.scraml.ramlparser.model.{ ImplicitId, JsonSchemaModel, NativeId, UniqueId }
import io.atomicbits.scraml.ramlparser.model.canonicaltypes._
import io.atomicbits.scraml.ramlparser.model.parsedtypes._
/**
* Created by peter on 22/12/16.
*
* Transformes a ParsedObject into an ObjectType and collects all available type information into the CanonicalLookupHelper.
*
*/
object ParsedObjectTransformer {
type PropertyAggregator = (Map[String, Property[_ <: GenericReferrable]], CanonicalLookupHelper)
// 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
val imposedTypeDiscriminatorOpt: Option[String] = parsedTypeContext.imposedTypeDiscriminator
/**
* Find the type discriminator value if there is one and subtract the type discriminator field from the parsed properties.
*/
def processJsonSchemaTypeDiscriminator(typeDiscriminatorOpt: Option[String],
props: ParsedProperties): (Option[String], ParsedProperties) = {
typeDiscriminatorOpt.flatMap { typeDiscriminator =>
props.get(typeDiscriminator).map(_.propertyType.parsed) collect {
case parsed: ParsedEnum => (parsed.choices.headOption, props - typeDiscriminator)
}
} getOrElse (None, props)
}
def registerParsedObject(parsedObject: ParsedObject, canonicalName: CanonicalName): (TypeReference, CanonicalLookupHelper) = {
val ownTypeDiscriminatorOpt: Option[String] = parsedObject.typeDiscriminator
val typeDescriminatorOpt = List(ownTypeDiscriminatorOpt, imposedTypeDiscriminatorOpt).flatten.headOption
// Prepare the empty aggregator
val aggregator: PropertyAggregator = (Map.empty[String, Property[_ <: GenericReferrable]], canonicalLookupHelper)
// if there is an imposed type discriminator, then we need to find its value and remove the discriminator from the properties.
val (jsonSchemaTypeDiscriminatorValue, propertiesWithoutTypeDiscriminator) =
processJsonSchemaTypeDiscriminator(typeDescriminatorOpt, parsedObject.properties)
val typeDiscriminatorValue = {
val nativeIdOpt =
Option(parsedObject.id).collect {
case NativeId(native) => native
}
List(jsonSchemaTypeDiscriminatorValue, parsedObject.typeDiscriminatorValue, nativeIdOpt).flatten.headOption
}
// Transform and register all properties of this object
val (properties, propertyUpdatedCanonicalLH) =
propertiesWithoutTypeDiscriminator.valueMap.foldLeft(aggregator)(propertyTransformer(parsedObject.requiredProperties))
// Extract all json-schema children from this parsed object and register them in de canonical lookup helper
val jsonSchemaChildrenUpdatedCanonicalLH =
extractJsonSchemaChildren(parsedObject, propertyUpdatedCanonicalLH, canonicalName, typeDescriminatorOpt)
// Get the RAML 1.0 parent from this parsed object, if any
val raml10ParentNameOp: Set[NonPrimitiveTypeReference] =
parsedObject.parents.toSeq // These are the RAML 1.0 parents
.map { parent =>
val (genericRef, unusedCanonicalLH) = ParsedToCanonicalTypeTransformer.transform(parent, canonicalLookupHelper)
genericRef
}
.collect {
case nonPrimitiveTypeReference: NonPrimitiveTypeReference => nonPrimitiveTypeReference
}
.toSet
// Make a flattened list of all found parents
val parents = parentNameOpt.map(raml10ParentNameOp + NonPrimitiveTypeReference(_)).getOrElse(raml10ParentNameOp)
val objectType =
ObjectType(
canonicalName = canonicalName,
properties = properties,
parents = parents.toList, // ToDo: make this a Set in ObjectType as well.
typeParameters = parsedObject.typeParameters.map(TypeParameter),
typeDiscriminator = List(imposedTypeDiscriminatorOpt, parsedObject.typeDiscriminator).flatten.headOption,
typeDiscriminatorValue = typeDiscriminatorValue
)
val typeReference: TypeReference = NonPrimitiveTypeReference(canonicalName) // We don't 'fill in' type parameter values here.
(typeReference, jsonSchemaChildrenUpdatedCanonicalLH.addCanonicalType(canonicalName, objectType))
}
// Generate the canonical name for this object
val canonicalName = canonicalNameOpt.getOrElse(canonicalNameGenerator.generate(parsed.id))
(parsed, canonicalName) match {
case (parsedObject: ParsedObject, NoName(_)) => Some((JsonType, canonicalLookupHelper))
case (parsedMultipleInheritance: ParsedMultipleInheritance, NoName(_)) => Some((JsonType, canonicalLookupHelper))
case (parsedObject: ParsedObject, _) if parsedObject.isEmpty => Some((JsonType, canonicalLookupHelper))
case (parsedObject: ParsedObject, _) => Some(registerParsedObject(parsedObject, canonicalName))
case (parsedMultipleInheritance: ParsedMultipleInheritance, _) =>
Some(registerParsedObject(parsedMultipleInheritanceToParsedObject(parsedMultipleInheritance), canonicalName))
case _ => None
}
}
// format: off
def propertyTransformer(requiredPropertyNames: List[String])
(propertyAggregator: PropertyAggregator,
propKeyValue: (String, ParsedProperty))
(implicit canonicalNameGenerator: CanonicalNameGenerator): PropertyAggregator = { // format: on
val (currentProperties, currentCanonicalLH) = propertyAggregator
val (propName, propValue) = propKeyValue
val (typeReference, updatedCanonicalLH) =
ParsedToCanonicalTypeTransformer.transform(propValue.propertyType.parsed, currentCanonicalLH)
val required = requiredPropertyNames.contains(propName) || propValue.required
val property =
Property(
name = propName,
ttype = typeReference,
required = required
// ToDo: process and add the typeConstraints
)
val updatedProperties = currentProperties + (propName -> property)
(updatedProperties, updatedCanonicalLH)
}
// format: off
/**
* Register the children (if any) of the given parsedObject and return the updated canonical lookup helper.
*/
private def extractJsonSchemaChildren(parsedObject: ParsedObject,
canonicalLookupHelper: CanonicalLookupHelper,
parentName: CanonicalName,
typeDiscriminatorOpt: Option[String])
(implicit canonicalNameGenerator: CanonicalNameGenerator): CanonicalLookupHelper = { // format: on
val typeDiscriminator = typeDiscriminatorOpt.getOrElse("type")
def registerObject(canonicalLH: CanonicalLookupHelper, parsedChild: ParsedType): CanonicalLookupHelper = {
ParsedTypeContext(parsedChild, canonicalLH, None, Some(parentName), Some(typeDiscriminator)) match {
case ParsedObjectTransformer(typeReference, updatedCanonicalLH) => updatedCanonicalLH
case _ => canonicalLH
}
}
parsedObject.selection match {
case Some(OneOf(selection)) =>
selection.foldLeft(canonicalLookupHelper)(registerObject)
case _ => canonicalLookupHelper
}
}
def parsedMultipleInheritanceToParsedObject(parsedMultipleInheritance: ParsedMultipleInheritance): ParsedObject = {
ParsedObject(
id = parsedMultipleInheritance.id,
properties = parsedMultipleInheritance.properties,
required = parsedMultipleInheritance.required,
requiredProperties = parsedMultipleInheritance.requiredProperties,
parents = parsedMultipleInheritance.parents,
typeParameters = parsedMultipleInheritance.typeParameters,
typeDiscriminator = parsedMultipleInheritance.typeDiscriminator,
typeDiscriminatorValue = parsedMultipleInheritance.typeDiscriminatorValue,
model = parsedMultipleInheritance.model
)
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/lookup/ParsedTypeIndexer.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.parsedtypes._
import io.atomicbits.scraml.ramlparser.model._
import io.atomicbits.scraml.ramlparser.parser.RamlParseException
/**
* Created by peter on 14/02/17.
*/
case class ParsedTypeIndexer(canonicalNameGenerator: CanonicalNameGenerator) {
def indexParsedTypes(raml: Raml, canonicalLookupHelper: CanonicalLookupHelper): CanonicalLookupHelper = {
// First, index all the parsed types on their Id so that we can perform forward lookups when creating the canonical types.
val canonicalLookupHelperWithJsonSchemas = raml.types.typeReferences.foldLeft(canonicalLookupHelper)(indexParsedTypesInt)
val canonicalLookupHelperWithResoureTypes = raml.resources.foldLeft(canonicalLookupHelperWithJsonSchemas)(indexResourceParsedTypes)
canonicalLookupHelperWithResoureTypes
}
private def indexParsedTypesInt(canonicalLookupHelper: CanonicalLookupHelper,
idWithParsedType: (Id, ParsedType)): CanonicalLookupHelper = {
val (id, parsedType) = idWithParsedType
val expandedParsedType = expandRelativeToAbsoluteIds(parsedType)
(expandedParsedType.id, id) match {
case (absoluteId: AbsoluteId, nativeId: NativeId) =>
val lookupWithCollectedParsedTypes = collectJsonSchemaParsedTypes(expandedParsedType, canonicalLookupHelper)
val updatedCLH = lookupWithCollectedParsedTypes.addJsonSchemaNativeToAbsoluteIdTranslation(nativeId, absoluteId)
updatedCLH
case (nativeId: NativeId, _) =>
canonicalLookupHelper.addParsedTypeIndex(nativeId, expandedParsedType)
case (_, NoId) => // ToDo: see if we can get rid of this 'NoId' pseudo id
val lookupWithCollectedParsedTypes = collectJsonSchemaParsedTypes(expandedParsedType, canonicalLookupHelper)
lookupWithCollectedParsedTypes
case (ImplicitId, someNativeId) =>
canonicalLookupHelper.addParsedTypeIndex(someNativeId, expandedParsedType)
case (unexpected, _) =>
sys.error(s"Unexpected id in the types definition: $unexpected")
}
}
private def indexResourceParsedTypes(canonicalLookupHelper: CanonicalLookupHelper, resource: Resource): CanonicalLookupHelper = {
// Types are located in the request and response BodyContent and in the ParsedParameter instances. For now we don't expect any
// complex types in the ParsedParameter instances, so we skip those.
def indexParameters(canonicalLH: CanonicalLookupHelper, parameters: Parameters): CanonicalLookupHelper = {
val parameterList: List[(String, Parameter)] = parameters.valueMap.toList
val idWithParamType: List[(NativeId, ParsedType)] =
parameterList.map {
case (paramName, parameter) =>
val nativeIdProposal = NativeId(paramName)
val parsedType = parameter.parameterType.parsed
(nativeIdProposal, parsedType)
}
idWithParamType.foldLeft(canonicalLH)(indexParsedTypesInt)
}
def indexBodyParsedTypes(canonicalLH: CanonicalLookupHelper, body: Body): CanonicalLookupHelper = {
val bodyContentList: List[BodyContent] = body.contentMap.values.toList
// Register body content types
val bodyParsedTypes: List[ParsedType] = bodyContentList.flatMap(_.bodyType).map(_.parsed)
val generatedNativeIds: List[Id] = bodyParsedTypes.map(x => NoId)
val nativeIdsWithParsedTypes: List[(Id, ParsedType)] = generatedNativeIds.zip(bodyParsedTypes)
val canonicalLookupWithBodyTypes = nativeIdsWithParsedTypes.foldLeft(canonicalLH)(indexParsedTypesInt)
// Register form parameter types
bodyContentList.map(_.formParameters).foldLeft(canonicalLookupWithBodyTypes)(indexParameters)
}
def indexActionParsedTypes(canonicalLH: CanonicalLookupHelper, action: Action): CanonicalLookupHelper = {
val canonicalLHWithBody = indexBodyParsedTypes(canonicalLH, action.body)
val responseBodies: List[Body] = action.responses.responseMap.values.toList.map(_.body)
val canonicalLHWithResponses = responseBodies.foldLeft(canonicalLHWithBody)(indexBodyParsedTypes)
// Register headers and query parameters
val canonicalLHWithHeaders = indexParameters(canonicalLHWithResponses, action.headers)
val canonicalLHWithQueryString =
action.queryString
.map(qs => indexParsedTypesInt(canonicalLHWithHeaders, (NoId, qs.queryStringType.parsed)))
.getOrElse(canonicalLHWithHeaders)
indexParameters(canonicalLHWithQueryString, action.queryParameters)
}
val canonicalLookupHelperWithActionTypes = resource.actions.foldLeft(canonicalLookupHelper)(indexActionParsedTypes)
resource.resources.foldLeft(canonicalLookupHelperWithActionTypes)(indexResourceParsedTypes)
}
/**
* Collect all json-schema types
*/
def collectJsonSchemaParsedTypes(ttype: ParsedType, canonicalLookupHelper: CanonicalLookupHelper): CanonicalLookupHelper = {
def collectFromProperties(properties: ParsedProperties,
canonicalLH: CanonicalLookupHelper,
lookupOnly: Boolean,
typeDiscriminator: Option[String]): CanonicalLookupHelper = {
properties.values.foldLeft(canonicalLH) { (canLH, property) =>
typeDiscriminator
.collect {
// We don't register the type behind the type discriminator property, because we will handle it separately
// when creating canonical types.
case typeDisc if property.name == typeDisc => canonicalLH
}
.getOrElse {
collect(
theType = property.propertyType.parsed,
canonicalLH = canLH,
onlyObjectsAndEnums = true, // We only include objects and enums here because ... (?) {needs documentation!}
lookupOnly = lookupOnly
) // Mind that the typeDiscriminator value is NOT propagated here!
}
}
}
def collectFromFragments(fragment: Fragments, canonicalLH: CanonicalLookupHelper, lookupOnly: Boolean): CanonicalLookupHelper = {
val fragmentTypes: List[ParsedType] = fragment.fragments.values
fragmentTypes.foldLeft(canonicalLH) { (canLH, pType) =>
collect(theType = pType, canonicalLH = canLH, lookupOnly = lookupOnly)
}
}
def collectFromSelection(selection: Selection,
canonicalLH: CanonicalLookupHelper,
typeDiscriminator: Option[String]): CanonicalLookupHelper = {
val selectionTypes: List[ParsedType] = selection.selection
selectionTypes.foldLeft(canonicalLH) { (canLH, pType) =>
// Selection types will not be added for generation, but for lookup only, they will be generated through their parent definition.
collect(theType = pType, canonicalLH = canLH, lookupOnly = true, typeDiscriminator = typeDiscriminator)
// Mind that the typeDiscriminator value is MUST be propagated here!
}
}
def collect(theType: ParsedType,
canonicalLH: CanonicalLookupHelper,
onlyObjectsAndEnums: Boolean = false,
lookupOnly: Boolean = false,
typeDiscriminator: Option[String] = None): CanonicalLookupHelper = {
theType match {
case objectType: ParsedObject =>
val actualTypeDiscriminator = List(typeDiscriminator, objectType.typeDiscriminator).flatten.headOption
// Mind that the typeDiscriminator value is only propagated with the properties and the selection!
val lookupWithProperties = collectFromProperties(objectType.properties, canonicalLH, lookupOnly, actualTypeDiscriminator)
val lookupWithFragments = collectFromFragments(objectType.fragments, lookupWithProperties, lookupOnly)
val lookupWithSelection =
objectType.selection
.map(collectFromSelection(_, lookupWithFragments, actualTypeDiscriminator))
.getOrElse(lookupWithFragments)
lookupWithSelection.addParsedTypeIndex(id = objectType.id, parsedType = objectType, lookupOnly = lookupOnly)
case enumType: ParsedEnum => canonicalLH.addParsedTypeIndex(enumType.id, enumType)
case fragment: Fragments => collectFromFragments(fragment.fragments, canonicalLH, lookupOnly)
case arrayType: ParsedArray =>
val lookupWithArrayType = collect(arrayType.items, canonicalLH, onlyObjectsAndEnums, lookupOnly)
val lookupWithFragments = collectFromFragments(arrayType.fragments, lookupWithArrayType, lookupOnly)
if (onlyObjectsAndEnums) lookupWithFragments
else lookupWithFragments.addParsedTypeIndex(id = arrayType.id, parsedType = arrayType, lookupOnly = lookupOnly)
case typeReference: ParsedTypeReference =>
val lookupWithFragments = collectFromFragments(typeReference.fragments, canonicalLH, lookupOnly)
if (onlyObjectsAndEnums) lookupWithFragments
else lookupWithFragments.addParsedTypeIndex(id = typeReference.id, parsedType = typeReference, lookupOnly = lookupOnly)
case other =>
if (onlyObjectsAndEnums) canonicalLH
else canonicalLH.addParsedTypeIndex(id = other.id, parsedType = other, lookupOnly = lookupOnly)
}
}
ttype.id match {
case rootId: RootId => collect(ttype, canonicalLookupHelper)
case relId: RelativeId =>
val rootId: RootId = canonicalNameGenerator.toRootId(relId)
collect(ttype.updated(rootId), canonicalLookupHelper)
case other => canonicalLookupHelper
}
}
/**
* Expand all relative ids to absolute ids and also expand all $ref pointers.
*
* @param ttype
* @return
*/
def expandRelativeToAbsoluteIds(ttype: ParsedType): ParsedType = { // ToDo: move this into a separate class
/**
* Expand the ids in a schema based on the nearest root id of the enclosing schemas.
*
* @param ttype the schema whose ids need expanding
* @param root the nearest (original) root id that was found in the enclosing schemas
* @param expandingRoot the root that we're expanding (creating) based on the seed (the nearest original root id)
* @param path the fragment path we're on
* @return a copy of the original schema in which all ids are replaced by root ids
*/
def expandWithRootAndPath(ttype: ParsedType, root: RootId, expandingRoot: RootId, path: List[String] = List.empty): ParsedType = {
val currentRoot =
ttype.id match {
case rootId: RootId => rootId
case _ => root
}
val expandedId = root.toAbsoluteId(ttype.id, path)
def expandProperty(property: ParsedProperty): ParsedProperty = {
// Treat the property as a fragment to expand it.
val fragment = (property.name, property.propertyType.parsed)
val (name, expandedType) = expandFragment(fragment)
property.copy(propertyType = TypeRepresentation(expandedType))
}
def expandFragment(fragmentPath: (String, ParsedType)): (String, ParsedType) = {
val (pathPart, subSchema) = fragmentPath
val updatedSubSchema = expandWithRootAndPath(subSchema, currentRoot, expandedId.rootPart, path :+ pathPart)
(pathPart, updatedSubSchema)
}
val parsedTypeWithUpdatedFragments: ParsedType =
ttype match {
case objectType: ParsedObject =>
objectType.copy(
fragments = objectType.fragments.map(expandFragment),
properties = objectType.properties.map(expandProperty),
selection = objectType.selection
.map(select => select.map(schema => expandWithRootAndPath(schema, currentRoot, expandingRoot, path)))
)
case fragment: Fragments => fragment.map(expandFragment)
case arrayType: ParsedArray =>
val expandedPath = expandWithRootAndPath(arrayType.items, currentRoot, expandingRoot, path :+ "items")
arrayType.copy(
items = expandedPath,
fragments = arrayType.fragments.map(expandFragment)
)
case typeReference: ParsedTypeReference =>
typeReference.copy(
refersTo = currentRoot.toAbsoluteId(typeReference.refersTo, path),
fragments = typeReference.fragments.map(expandFragment)
)
case _ => ttype
}
parsedTypeWithUpdatedFragments.updated(expandedId)
}
if (ttype.model == RamlModel) { // ToDo: see if we can refactor this to another way of detecting RAML 1.0 versus json-schema types
ttype
} else {
ttype.id match {
case rootId: RootId => expandWithRootAndPath(ttype, rootId, rootId)
case relativeId: RelativeId =>
val anonymousRootId = canonicalNameGenerator.toRootId(NativeId("anonymous"))
expandWithRootAndPath(ttype, anonymousRootId, anonymousRootId)
case ImplicitId =>
// We assume we hit an inline schema without an id, so we may just invent a random unique one since it will never be referenced.
val canonicalName = canonicalNameGenerator.generate(ImplicitId)
val rootId = RootId.fromCanonical(canonicalName)
expandWithRootAndPath(ttype.updated(rootId), rootId, rootId)
case _ => throw RamlParseException("We cannot expand the ids in a schema that has no absolute root id.")
}
}
}
// Todo: remove hasNativeIds
private def hasNativeIds(ttype: ParsedType): Boolean = {
def isNativeId(id: Id): Boolean =
id match {
case nativeId: NativeId => true
case _ => false
}
def hasDeepNativeIds(deepType: ParsedType): Boolean =
deepType match {
case objectType: ParsedObject =>
val hasNativeIdList = objectType.properties.valueMap.values.map(property => hasNativeIds(property.propertyType.parsed)).toList
hasNativeIdList match {
case Nil => false
case i1 :: Nil => i1
case atLeastTwoElements => atLeastTwoElements.reduce(_ || _)
}
case arrayType: ParsedArray => hasNativeIds(arrayType.items)
case typeReference: ParsedTypeReference => isNativeId(typeReference.refersTo)
case _ => false
}
isNativeId(ttype.id) || hasDeepNativeIds(ttype)
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/HeaderMap.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
import _root_.java.util.Locale
/**
* Created by peter on 30/10/15.
*/
case class HeaderMap(private val headerList: Map[String, List[String]] = Map.empty,
private val originalKeys: Map[String, String] = Map.empty) {
/**
* + will add given headers and expand existing headers with additional values
*/
def +(keyValuePair: (String, String)): HeaderMap = {
val (key, value) = keyValuePair
val keyNormalized: String = normalize(key)
val valueOriginal: String = value.trim
if (keyNormalized.isEmpty || valueOriginal.isEmpty) {
this
} else {
val updatedOriginalKeys = originalKeys + (keyNormalized -> key)
val valueList =
headerList.get(keyNormalized) map { currentValues =>
valueOriginal :: currentValues
} getOrElse List(valueOriginal)
val updatedHeaders = headerList + (keyNormalized -> valueList)
this.copy(headerList = updatedHeaders, originalKeys = updatedOriginalKeys)
}
}
/**
* + will add given headers and expand existing headers with additional values
*/
def ++(keyValuePairs: (String, String)*): HeaderMap =
keyValuePairs.foldLeft(this) { (headerMap, keyValuePair) =>
headerMap + keyValuePair
}
/**
* + will add given headers and expand existing headers with additional values
*/
def ++(headerMap: HeaderMap): HeaderMap =
headerMap.headers.foldLeft(this) { (headMap, header) =>
val (key, values) = header
values.foldLeft(headMap) { (hMap, value) =>
hMap + (key -> value)
}
}
/**
* set wil overwrite existing headers rather than extend them with an additional value
*/
def set(keyValuePair: (String, String)): HeaderMap = {
val (key, value) = keyValuePair
setMany((key, List(value)))
}
/**
* set wil overwrite existing headers rather than extend them with an additional value
*/
def setMany(keyValuePair: (String, List[String])): HeaderMap = {
val (key, values) = keyValuePair
val keyNormalized: String = normalize(key)
val valuesOriginal: List[String] = values.map(_.trim)
if (keyNormalized.isEmpty || valuesOriginal.isEmpty) {
this
} else {
val updatedOriginalKeys = originalKeys + (keyNormalized -> key)
val updatedHeaders = headerList + (keyNormalized -> valuesOriginal)
this.copy(headerList = updatedHeaders, originalKeys = updatedOriginalKeys)
}
}
/**
* set wil overwrite existing headers rather than extend them with an additional value
*/
def set(keyValuePairs: (String, String)*): HeaderMap =
keyValuePairs.foldLeft(this) { (headerMap, keyValuePair) =>
headerMap set keyValuePair
}
/**
* set wil overwrite existing headers rather than extend them with an additional value
*/
def set(headerMap: HeaderMap): HeaderMap = {
headerMap.headers.foldLeft(this) { (headMap, header) =>
headMap setMany header
}
}
def headers: Map[String, List[String]] = {
originalKeys.keys.foldLeft(Map.empty[String, List[String]]) { (map, normalizedKey) =>
map + (originalKeys(normalizedKey) -> headerList(normalizedKey))
}
}
def hasKey(key: String): Boolean = {
originalKeys.get(normalize(key)).isDefined
}
def get(key: String): Option[List[String]] = {
headerList.get(normalize(key))
}
def foreach(f: ((String, List[String])) => Unit) = {
originalKeys.keys foreach { normalizedKey =>
f(originalKeys(normalizedKey), headerList(normalizedKey))
}
}
private def normalize(key: String): String = {
key.trim.toLowerCase(Locale.ENGLISH)
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/Segment.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.dsl.scalaplay
import play.api.libs.json.{ Format, JsValue }
import scala.concurrent.Future
import scala.language.reflectiveCalls
sealed trait Segment {
protected def _requestBuilder: RequestBuilder
}
/**
* We DON'T use case classes here to hide the internals from the resulting DSL.
*/
class PlainSegment(pathElement: String, _req: RequestBuilder) extends Segment {
protected val _requestBuilder = _req
}
class ParamSegment[T](value: T, _req: RequestBuilder) extends Segment {
protected val _requestBuilder = _req
}
class HeaderSegment(_req: RequestBuilder) extends Segment {
protected val _requestBuilder = _req
}
// ToDo: rename to MethodSegment to Request (which is what it is)
abstract class MethodSegment[B, R](method: Method,
theBody: Option[B],
queryParams: Map[String, Option[HttpParam]],
queryString: Option[TypedQueryParams],
formParams: Map[String, Option[HttpParam]],
multipartParams: List[BodyPart],
binaryBody: Option[BinaryRequest] = None,
expectedAcceptHeader: Option[String],
expectedContentTypeHeader: Option[String],
req: RequestBuilder)
extends Segment {
val body = theBody
protected val queryParameterMap: Map[String, HttpParam] =
queryString
.map(_.params)
.getOrElse {
queryParams.collect { case (key, Some(value)) => (key, value) }
}
protected val formParameterMap: Map[String, HttpParam] = formParams.collect { case (key, Some(value)) => (key, value) }
protected val _requestBuilder: RequestBuilder = {
val reqUpdated =
req.copy(
method = method,
queryParameters = queryParameterMap,
formParameters = formParameterMap,
multipartParams = multipartParams,
binaryBody = binaryBody
)
val reqWithAccept =
expectedAcceptHeader map { acceptHeader =>
if (reqUpdated.headers.get("Accept").isEmpty)
reqUpdated.copy(headers = reqUpdated.headers + ("Accept" -> acceptHeader))
else reqUpdated
} getOrElse reqUpdated
val reqWithContentType =
expectedContentTypeHeader map { contentHeader =>
if (reqWithAccept.headers.get("Content-Type").isEmpty)
reqWithAccept.copy(headers = reqWithAccept.headers + ("Content-Type" -> contentHeader))
else reqWithAccept
} getOrElse reqWithAccept
/**
* add default request charset if necessary
*
* see https://www.w3.org/Protocols/rfc1341/4_Content-Type.html
* charset is case-insensitive:
* * http://stackoverflow.com/questions/7718476/are-http-headers-content-type-c-case-sensitive
* * https://www.w3.org/TR/html4/charset.html#h-5.2.1
*/
val reqWithRequestCharset =
reqWithContentType.headers.get("Content-Type").map { headerValues =>
val hasCharset = !headerValues.exists(_.toLowerCase.contains("charset"))
val isBinary = headerValues.exists(_.toLowerCase.contains("octet-stream"))
if (hasCharset && !isBinary && headerValues.nonEmpty) {
val newFirstHeaderValue = s"${headerValues.head}; charset=${reqWithContentType.client.config.requestCharset.name}"
val updatedHeaders = reqWithContentType.headers setMany ("Content-Type", newFirstHeaderValue :: headerValues.tail)
reqWithContentType.copy(headers = updatedHeaders)
} else reqWithContentType
} getOrElse reqWithContentType
reqWithRequestCharset
}
def isFormUrlEncoded: Boolean =
_requestBuilder.allHeaders
.get("Content-Type")
.exists { values =>
values.exists(value => value.contains("application/x-www-form-urlencoded"))
}
def jsonBodyToString()(implicit bodyFormat: Format[B]): (RequestBuilder, Option[String]) = {
if (formParams.isEmpty && body.isDefined && isFormUrlEncoded) {
val formPs: Map[String, HttpParam] = HttpParam.toFormUrlEncoded(bodyFormat.writes(body.get))
val reqBuilder = _requestBuilder.copy(formParameters = formPs)
(reqBuilder, None)
} else {
val bodyToSend = body.map(bodyFormat.writes(_).toString())
(_requestBuilder, bodyToSend)
}
}
}
class StringMethodSegment[B](method: Method,
theBody: Option[B] = None,
primitiveBody: Boolean = false,
queryParams: Map[String, Option[HttpParam]] = Map.empty,
queryString: Option[TypedQueryParams] = None,
formParams: Map[String, Option[HttpParam]] = Map.empty,
multipartParams: List[BodyPart] = List.empty,
binaryParam: Option[BinaryRequest] = None,
expectedAcceptHeader: Option[String] = None,
expectedContentTypeHeader: Option[String] = None,
req: RequestBuilder)
extends MethodSegment[B, String](method,
theBody,
queryParams,
queryString,
formParams,
multipartParams,
binaryParam,
expectedAcceptHeader,
expectedContentTypeHeader,
req) {
def call()(implicit bodyFormat: Format[B]): Future[Response[String]] = {
if (primitiveBody) {
val bodyToSend = body.map(_.toString())
_requestBuilder.callToStringResponse(bodyToSend)
} else {
val (reqBuilder, preparedBody) = jsonBodyToString()
reqBuilder.callToStringResponse(preparedBody)
}
}
}
class JsonMethodSegment[B](method: Method,
theBody: Option[B] = None,
primitiveBody: Boolean = false,
queryParams: Map[String, Option[HttpParam]] = Map.empty,
queryString: Option[TypedQueryParams] = None,
formParams: Map[String, Option[HttpParam]] = Map.empty,
multipartParams: List[BodyPart] = List.empty,
binaryParam: Option[BinaryRequest] = None,
expectedAcceptHeader: Option[String] = None,
expectedContentTypeHeader: Option[String] = None,
req: RequestBuilder)
extends MethodSegment[B, JsValue](method,
theBody,
queryParams,
queryString,
formParams,
multipartParams,
binaryParam,
expectedAcceptHeader,
expectedContentTypeHeader,
req) {
def call()(implicit bodyFormat: Format[B]): Future[Response[JsValue]] = {
if (primitiveBody) {
val bodyToSend = body.map(_.toString())
_requestBuilder.callToJsonResponse(bodyToSend)
} else {
val (reqBuilder, preparedBody) = jsonBodyToString()
reqBuilder.callToJsonResponse(preparedBody)
}
}
}
class TypeMethodSegment[B, R](method: Method,
theBody: Option[B] = None,
primitiveBody: Boolean = false,
queryParams: Map[String, Option[HttpParam]] = Map.empty,
queryString: Option[TypedQueryParams] = None,
formParams: Map[String, Option[HttpParam]] = Map.empty,
multipartParams: List[BodyPart] = List.empty,
binaryParam: Option[BinaryRequest] = None,
expectedAcceptHeader: Option[String] = None,
expectedContentTypeHeader: Option[String] = None,
req: RequestBuilder)
extends MethodSegment[B, R](method,
theBody,
queryParams,
queryString,
formParams,
multipartParams,
binaryParam,
expectedAcceptHeader,
expectedContentTypeHeader,
req) {
def call()(implicit bodyFormat: Format[B], responseFormat: Format[R]): Future[Response[R]] = {
if (primitiveBody) {
val bodyToSend = body.map(_.toString())
_requestBuilder.callToTypeResponse[R](bodyToSend)
} else {
val (reqBuilder, preparedBody) = jsonBodyToString()
reqBuilder.callToTypeResponse(preparedBody)
}
}
}
class BinaryMethodSegment[B](method: Method,
theBody: Option[B] = None,
primitiveBody: Boolean = false,
queryParams: Map[String, Option[HttpParam]] = Map.empty,
queryString: Option[TypedQueryParams] = None,
formParams: Map[String, Option[HttpParam]] = Map.empty,
multipartParams: List[BodyPart] = List.empty,
binaryParam: Option[BinaryRequest] = None,
expectedAcceptHeader: Option[String] = None,
expectedContentTypeHeader: Option[String] = None,
req: RequestBuilder)
extends MethodSegment[B, BinaryData](method,
theBody,
queryParams,
queryString,
formParams,
multipartParams,
binaryParam,
expectedAcceptHeader,
expectedContentTypeHeader,
req) {
def call()(implicit bodyFormat: Format[B]): Future[Response[BinaryData]] = {
if (primitiveBody) {
val bodyToSend = body.map(_.toString())
_requestBuilder.callToBinaryResponse(bodyToSend)
} else {
val (reqBuilder, preparedBody) = jsonBodyToString()
reqBuilder.callToBinaryResponse(preparedBody)
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/DateFormat.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 java.time.format.DateTimeFormatter
/**
* Created by peter on 19/08/16.
*/
sealed trait DateFormat {
def pattern: String
def formatter: DateTimeFormatter
}
case object RFC3339FullDate extends DateFormat {
val pattern = "yyyy-MM-dd"
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern(pattern)
}
case object RFC3339PartialTime extends DateFormat {
val pattern = "HH:mm:ss[.SSS]"
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern(pattern)
}
case object DateOnlyTimeOnly extends DateFormat {
val pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS]"
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern(pattern)
// e.g. 2015-07-04T21:00:00
// "yyyy-MM-dd[[ ]['T']HH:mm[:ss][XXX]]"
// "yyyy-MM-dd'T'HH:mm:ss[.SSS]"
}
case object RFC3339DateTime extends DateFormat {
val pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS]XXX"
val formatter: DateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME
// e.g. 2016-02-28T16:41:41.090Z
// e.g. 2016-02-28T16:41:41.090+08:00
}
case object RFC2616 extends DateFormat {
val pattern = "EEE, dd MMM yyyy HH:mm:ss 'GMT'"
// e.g. Sun, 28 Feb 2016 16:41:41 GMT
val formatter: DateTimeFormatter = DateTimeFormatter.RFC_1123_DATE_TIME
/**
* see: http://stackoverflow.com/questions/7707555/getting-date-in-http-format-in-java
*
* java8 time:
* java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(ZoneId.of("GMT")))
*
* joda time:
* private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC().withLocale(Locale.US);
*/
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/restmodel/ActionSelection.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.restmodel
import io.atomicbits.scraml.generator.platform.Platform
import io.atomicbits.scraml.ramlparser.model.{ Action, MediaType, NoMediaType, StatusCode }
/**
* Created by peter on 20/01/17.
*/
case class ActionSelection(action: Action,
contentTypeMap: Map[MediaType, ContentType],
responseTypeMap: Map[MediaType, Set[ResponseTypeWithStatus]],
selectedContentTypeHeader: MediaType = NoMediaType,
selectedResponsetypeHeader: MediaType = NoMediaType) {
val contentTypeHeaders: Set[MediaType] = contentTypeMap.keys.toSet
val responseTypeHeaders: Set[MediaType] = responseTypeMap.keys.toSet
def selectedContentType: ContentType = contentTypeMap.getOrElse(selectedContentTypeHeader, NoContentType)
def selectedResponseType: ResponseType = {
if (selectedResponseTypesWithStatus.isEmpty) NoResponseType
else {
val smallestStatusCode = selectedResponseTypesWithStatus.map(_.status).min
val responseTypeWithSmallestStatusCode = selectedResponseTypesWithStatus.groupBy(_.status)(smallestStatusCode)
responseTypeWithSmallestStatusCode.head.responseType
}
}
def selectedResponseTypesWithStatus: Set[ResponseTypeWithStatus] = responseTypeMap.getOrElse(selectedResponsetypeHeader, Set.empty)
def withContentTypeSelection(contentTypeHeader: MediaType): ActionSelection = copy(selectedContentTypeHeader = contentTypeHeader)
def withResponseTypeSelection(responseTypeHeader: MediaType): ActionSelection = copy(selectedResponsetypeHeader = responseTypeHeader)
}
object ActionSelection {
def apply(action: Action)(implicit platform: Platform): ActionSelection = {
val contentTypeMap: Map[MediaType, ContentType] = {
val contentTypes = ContentType(action.body)
if (contentTypes.isEmpty) Map(NoMediaType -> NoContentType)
else contentTypes.groupBy(_.contentTypeHeader).mapValues(_.head).toMap // There can be only one content type per content type header.
}
val responseTypeMap: Map[MediaType, Set[ResponseTypeWithStatus]] = {
val statusCodes = action.responses.responseMap.keys
if (statusCodes.isEmpty) {
Map(NoMediaType -> Set())
} else {
val minStatusCode = statusCodes.min
val response = action.responses.responseMap(minStatusCode)
val actualResponseTypes = ResponseType(response)
val responseTypes = if (actualResponseTypes.isEmpty) Set(NoResponseType) else actualResponseTypes
val responseTypeWithStatus = responseTypes.map(ResponseTypeWithStatus(_, minStatusCode))
responseTypeWithStatus.groupBy(_.responseType.acceptHeader) // There can be multiple accept types per accept type header (with different status codes).
}
}
ActionSelection(action, contentTypeMap, responseTypeMap)
}
}
case class ResponseTypeWithStatus(responseType: ResponseType, status: StatusCode)
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/javajackson/JavaActionCodeGenerator.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.javajackson
import java.util.Locale
import io.atomicbits.scraml.generator.codegen.{ ActionCode, SourceCodeFragment }
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.parsedtypes._
import io.atomicbits.scraml.ramlparser.model.{ Parameter, QueryString }
import TypedRestOps._
import io.atomicbits.scraml.generator.platform.androidjavajackson.AndroidJavaJackson
import io.atomicbits.scraml.generator.util.CleanNameUtil
/**
* Created by peter on 1/03/17.
*/
class JavaActionCodeGenerator(val javaJackson: CommonJavaJacksonPlatform) extends ActionCode {
import Platform._
implicit val platform: Platform = javaJackson
def contentHeaderSegmentField(contentHeaderMethodName: String, headerSegment: ClassReference) =
s"""public ${headerSegment.fullyQualifiedName} $contentHeaderMethodName =
new ${headerSegment.fullyQualifiedName}(this.getRequestBuilder());"""
// ToDo: generate the imports!
def expandMethodParameter(parameters: List[(String, ClassPointer)]): List[String] = parameters map { parameterDef =>
val (field, classPtr) = parameterDef
s"${classPtr.classDefinition} $field"
}
def queryStringType(actionSelection: ActionSelection): Option[ClassPointer] = actionSelection.action.queryString.map(_.classPointer())
def bodyTypes(actionSelection: ActionSelection): List[Option[ClassPointer]] =
actionSelection.selectedContentType match {
case StringContentType(contentTypeHeader) => List(Some(StringClassPointer))
case JsonContentType(contentTypeHeader) => List(Some(StringClassPointer))
case typedContentType: TypedContentType =>
typedContentType.classPointer match {
case StringClassPointer | JsValueClassPointer | JsObjectClassPointer => List(Some(StringClassPointer))
case _ =>
List(Some(StringClassPointer), Some(typedContentType.classPointer))
}
case BinaryContentType(contentTypeHeader) =>
List(
Some(StringClassPointer),
Some(FileClassPointer),
Some(InputStreamClassPointer),
Some(ArrayClassPointer(arrayType = ByteClassPointer))
)
case AnyContentType(contentTypeHeader) =>
List(
None,
Some(StringClassPointer),
Some(FileClassPointer),
Some(InputStreamClassPointer),
Some(ArrayClassPointer(arrayType = ByteClassPointer))
)
case NoContentType => List(None)
case x => List(Some(StringClassPointer))
}
def responseTypes(actionSelection: ActionSelection): List[Option[ClassPointer]] =
actionSelection.selectedResponseType match {
case StringResponseType(acceptHeader) => List(Some(StringClassPointer))
case JsonResponseType(acceptHeader) => List(Some(StringClassPointer), Some(JsValueClassPointer))
case BinaryResponseType(acceptHeader) =>
List(
Some(StringClassPointer),
Some(FileClassPointer),
Some(InputStreamClassPointer),
Some(ArrayClassPointer(arrayType = ByteClassPointer))
)
case typedResponseType: TypedResponseType =>
List(Some(StringClassPointer), Some(JsValueClassPointer), Some(typedResponseType.classPointer))
case NoResponseType => List(None)
case x => List(Some(StringClassPointer))
}
def createSegmentType(responseType: ResponseType, optBodyType: Option[ClassPointer]): String = {
val bodyType = optBodyType.map(_.classDefinition).getOrElse("String")
responseType match {
case BinaryResponseType(acceptHeader) => s"BinaryMethodSegment<$bodyType>"
case JsonResponseType(acceptHeader) => s"StringMethodSegment<$bodyType>"
case typedResponseType: TypedResponseType => s"TypeMethodSegment<$bodyType, ${typedResponseType.classPointer.classDefinition}>"
case x => s"StringMethodSegment<$bodyType>"
}
}
def responseClassDefinition(responseType: ResponseType): String = responseType match {
case BinaryResponseType(acceptHeader) => "CompletableFuture<Response<BinaryData>>"
case JsonResponseType(acceptHeader) => "CompletableFuture<Response<String>>"
case typedResponseType: TypedResponseType => s"CompletableFuture<Response<${typedResponseType.classPointer.classDefinition}>>"
case x => "CompletableFuture<Response<String>>"
}
def canonicalResponseType(responseType: ResponseType): Option[String] = responseType match {
case BinaryResponseType(acceptHeader) => None
case JsonResponseType(acceptHeader) => None
case typedResponseType: TypedResponseType => Some(typedResponseType.classPointer.fullyQualifiedClassDefinition)
case x => None
}
def canonicalContentType(contentType: ContentType): Option[String] = contentType match {
case JsonContentType(contentTypeHeader) => None
case typedContentType: TypedContentType => Some(typedContentType.classPointer.fullyQualifiedClassDefinition)
case x => None
}
def sortQueryOrFormParameters(fieldParams: List[(String, Parameter)]): List[(String, Parameter)] = fieldParams.sortBy(_._1)
def primitiveTypeToJavaType(primitiveType: PrimitiveType, required: Boolean): String = primitiveType match {
// The cases below go wrong when the primitive ends up in a list like List<double> versus List<Double>.
// case integerType: IntegerType if required => "long"
// case numbertype: NumberType if required => "double"
// case booleanType: BooleanType if required => "boolean"
case stringtype: ParsedString => "String"
case integerType: ParsedInteger => "Long"
case numbertype: ParsedNumber => "Double"
case booleanType: ParsedBoolean => "Boolean"
case other => sys.error(s"RAML type $other is not yet supported.")
}
def expandQueryStringAsMethodParameter(queryString: QueryString): SourceCodeFragment = {
val sanitizedParameterName = platform.safeFieldName("queryString")
val classPointer = queryString.classPointer()
val classDefinition = classPointer.classDefinition
val methodParameter = s"$classDefinition $sanitizedParameterName"
SourceCodeFragment(imports = Set(classPointer), sourceDefinition = List(methodParameter))
}
def expandQueryOrFormParameterAsMethodParameter(qParam: (String, Parameter), noDefault: Boolean = false): SourceCodeFragment = {
val (queryParameterName, parameter) = qParam
val sanitizedParameterName = platform.safeFieldName(queryParameterName)
val classPointer = parameter.classPointer()
val classDefinition = classPointer.classDefinition
val methodParameter = s"$classDefinition $sanitizedParameterName"
SourceCodeFragment(imports = Set(classPointer), sourceDefinition = List(methodParameter))
}
def expandQueryOrFormParameterAsMapEntry(qParam: (String, Parameter)): String = {
val (queryParameterName, parameter) = qParam
val sanitizedParameterName = platform.safeFieldName(queryParameterName)
val classPointer = parameter.classPointer()
val (httpParamType, callParameters) =
classPointer match {
case ListClassPointer(typeParamValue: PrimitiveClassPointer) => ("RepeatedHttpParam", List(sanitizedParameterName))
case primitive: PrimitiveClassPointer => ("SimpleHttpParam", List(sanitizedParameterName))
case complex =>
("ComplexHttpParam", List(sanitizedParameterName, CleanNameTools.quoteString(classPointer.fullyQualifiedClassDefinition)))
}
s"""params.put("$queryParameterName", new $httpParamType(${callParameters.mkString(", ")}));"""
}
def getCallMethod: String =
platform match {
case AndroidJavaJackson(_) => ""
case JavaJackson(_) => ".call()"
}
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 = {
val segmentBodyType = if (isBinary) None else bodyType
val segmentType = createSegmentType(actionSelection.selectedResponseType, segmentBodyType)
val actionType = actionSelection.action.actionType
val actionTypeMethod = actionType.toString.toLowerCase
val queryParameterMapEntries = actionSelection.action.queryParameters.valueMap.toList.map(expandQueryOrFormParameterAsMapEntry)
// The bodyFieldValue is only used for String, JSON and Typed bodies, not for a multipart or binary body
val bodyFieldValue = if (isTypedBodyParam) "body" else "null"
val multipartParamsValue = if (isMultipartParams) "parts" else "null"
val binaryParamValue = if (isBinaryParam) "BinaryRequest.create(body)" else "null"
val expectedAcceptHeader = actionSelection.selectedResponseType.acceptHeaderOpt
val expectedContentTypeHeader = actionSelection.selectedContentType.contentTypeHeaderOpt
val acceptHeader = expectedAcceptHeader.map(acceptH => s""""${acceptH.value}"""").getOrElse("null")
val contentHeader = expectedContentTypeHeader.map(contentHeader => s""""${contentHeader.value}"""").getOrElse("null")
val method = s"Method.${actionType.toString.toUpperCase(Locale.ENGLISH)}"
val (queryParamMap, queryParams) =
if (queryParameterMapEntries.nonEmpty)
(
s"""
Map<String, HttpParam> params = new HashMap<String, HttpParam>();
${queryParameterMapEntries.mkString("\n")}
""",
"params"
)
else ("", "null")
val (formParamMap, formParams) =
if (formParameterMapEntries.nonEmpty)
(
s"""
Map<String, HttpParam> params = new HashMap<String, HttpParam>();
${formParameterMapEntries.mkString("\n")}
""",
"params"
)
else ("", "null")
val queryStringValue =
if (queryStringType.isDefined) "new TypedQueryParams(queryString)"
else "null"
val canonicalResponseT = canonicalResponseType(responseType).map(CleanNameTools.quoteString).getOrElse("null")
val canonicalContentT = canonicalContentType(contentType).map(CleanNameTools.quoteString).getOrElse("null")
val callResponseType: String =
platform match {
case AndroidJavaJackson(_) => segmentType
case JavaJackson(_) => responseClassDefinition(responseType)
}
val primitiveBody = hasPrimitiveBody(segmentBodyType)
val callMethod = getCallMethod
s"""
public $callResponseType $actionTypeMethod(${actionParameters.mkString(", ")}) {
$queryParamMap
$formParamMap
return new $segmentType(
$method,
$bodyFieldValue,
$primitiveBody,
$queryParams,
$queryStringValue,
$formParams,
$multipartParamsValue,
$binaryParamValue,
$acceptHeader,
$contentHeader,
this.getRequestBuilder(),
$canonicalContentT,
$canonicalResponseT
)$callMethod;
}
"""
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Resource.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.ParsedString
import io.atomicbits.scraml.ramlparser.parser.ParseContext
import play.api.libs.json.{ JsObject, Json }
import scala.util.Try
import io.atomicbits.scraml.util.TryUtils._
import io.atomicbits.scraml.ramlparser.parser.JsUtils._
import scala.language.postfixOps
/**
* Created by peter on 10/02/16.
*/
case class Resource(urlSegment: String,
urlParameter: Option[Parameter] = None,
displayName: Option[String] = None,
description: Option[String] = None,
actions: List[Action] = List.empty,
resources: List[Resource] = List.empty,
parent: Option[Resource] = None) {
lazy val resourceMap: Map[String, Resource] = resources.map(resource => resource.urlSegment -> resource).toMap
lazy val actionMap: Map[Method, Action] = actions.map(action => action.actionType -> action).toMap
}
object Resource {
def apply(resourceUrl: String, jsObject: JsObject)(implicit parseContext: ParseContext): Try[Resource] = {
// Make sure we can handle the root segment as wel
val urlSegments: List[String] = {
if (resourceUrl == "/")
Nil
else
resourceUrl.split('/').toList.filter(!_.isEmpty)
}
parseContext.withSourceAndUrlSegments(jsObject, urlSegments) {
// Apply the listed traits to all methods in the resource.
//
// From the spec:
// "A trait can also be applied to a resource by using the is node. Using this node is equivalent to applying the trait to
// all methods for that resource, whether declared explicitly in the resource definition or inherited from a resource type."
//
// This must be done *before* calling the child resources
// recursively to adhere to the trait priority as described in:
// https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/raml-10.md/#algorithm-of-merging-traits-and-methods
parseContext.resourceTypes.applyToResource(jsObject) { resourceJsObj =>
// Actions
val tryMethods: Seq[(Method, Try[JsObject])] =
resourceJsObj.fields
.collect {
case (Method(method), jsObj: JsObject) => (method, jsObj)
case (Method(method), _) => (method, Json.obj())
}
.map {
case (meth, jsOb) =>
val actionOwnTraits = parseContext.traits.mergeInToAction(jsOb)
val actionResourceTraits = actionOwnTraits.flatMap(parseContext.traits.mergeInToActionFromResource(_, resourceJsObj))
(meth, actionResourceTraits)
}
.toSeq
val accumulated: Try[Map[Method, JsObject]] = accumulate(tryMethods.toMap)
val actionSeq: Try[Seq[Try[Action]]] = accumulated.map(methodMap => methodMap.map(Action(_)).toSeq)
val actions: Try[Seq[Action]] = actionSeq.flatMap(accumulate(_))
// Subresources
val subResourceMap =
resourceJsObj.value.toMap.collect {
case (fieldName, jsOb: JsObject) if fieldName.startsWith("/") => Resource(fieldName, jsOb)
} toSeq
val subResources: Try[Seq[Resource]] = accumulate(subResourceMap)
val displayName: Try[Option[String]] = Try(resourceJsObj.fieldStringValue("displayName"))
val description: Try[Option[String]] = Try(resourceJsObj.fieldStringValue("description"))
// URI parameters
val uriParameterMap: Try[Parameters] = Parameters((resourceJsObj \ "uriParameters").toOption)
/**
* Resources in the Java RAML model can have relative URLs that consist of multiple segments in a single Resource,
* e.g.: /rest/some/path/to/{param}/a/resource
* Our DSL generation would benefit form a breakdown of this path into nested resources. The all resulting
* resources would just be path elements to the last resource, which then contains the actions and sub
* resources of the original resource.
*
* Breakdown of the url segments into nested resources.
*/
def createResource(displayN: Option[String],
desc: Option[String],
uriParamMap: Parameters,
actionSeq: Seq[Action],
childResources: Seq[Resource]): Resource = {
def buildResourceSegment(segment: String): Resource = {
if (segment.startsWith("{") && segment.endsWith("}")) {
val pathParameterName = segment.stripPrefix("{").stripSuffix("}")
val pathParameterMeta =
uriParamMap
.byName(pathParameterName)
.getOrElse(Parameter(pathParameterName, TypeRepresentation(new ParsedString()), required = true))
Resource(
urlSegment = pathParameterName,
urlParameter = Some(pathParameterMeta)
)
} else {
Resource(
urlSegment = segment
)
}
}
def connectParentChildren(parent: Resource, children: List[Resource]): Resource = {
val childrenWithUpdatedParent = children.map(_.copy(parent = Some(parent)))
parent.copy(resources = childrenWithUpdatedParent)
}
def breakdownResourceUrl(segments: List[String]): Resource = {
segments match {
case segment :: Nil =>
val resource: Resource = buildResourceSegment(segment)
val connectedResource: Resource = connectParentChildren(resource, childResources.toList)
connectedResource.copy(actions = actionSeq.toList)
case segment :: segs =>
val resource: Resource = buildResourceSegment(segment)
connectParentChildren(resource, List(breakdownResourceUrl(segs)))
case Nil =>
val resource: Resource = buildResourceSegment("") // Root segment.
val connectedResource: Resource = connectParentChildren(resource, childResources.toList)
connectedResource.copy(actions = actionSeq.toList)
}
}
breakdownResourceUrl(urlSegments)
}
withSuccess(displayName, description, uriParameterMap, actions, subResources)(createResource)
}
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/codegen/GenerationAggr.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.generator.codegen
import io.atomicbits.scraml.generator.platform.Platform
import io.atomicbits.scraml.generator.typemodel._
import io.atomicbits.scraml.ramlparser.model.Raml
import io.atomicbits.scraml.ramlparser.model.canonicaltypes.{ CanonicalName, NonPrimitiveType }
import io.atomicbits.scraml.ramlparser.parser.SourceFile
/**
* Created by peter on 18/01/17.
*
* The generation aggregate contains information that may be needed for source definition generation and information
* about data and knownledge that was already collected so far in the generation process. The generation process is
* a recursive operation on the GenerationAggr, which can be expanded during code generation. In other words, new source
* definitions may be added during code generation, especially the interface definitions are expected to be added then.
*
* @param basePackage The base package for the generated codebase.
* @param sourceDefinitionsToProcess The collected source definitions up to 'now'.
* @param sourceFilesGenerated The generated source files so far.
* @param canonicalToMap The canonical TO map.
* @param toMap The TO map is needed to find all fields that we have to put in a class extending from one or more parents.
* @param toInterfaceMap The map containing the transfer objects that require an interface definition so far, keyed on the
* canonical name of the original transfer object. This map is expected to grow while source
* definitions for transfer objects are generated.
* @param toChildParentsMap The direct child parents relations are needed to navigate through the class hierarchy of the transfer
* objects. The toChildParentsMap is build up when the TOs are added to the toMap.
* @param toParentChildrenMap The direct parent children relations are needed to navigate through the class hierarchy of the transfer
* objects. The toParentChildrenMap is build up when the TOs are added to the toMap.
*/
case class GenerationAggr(basePackage: List[String],
sourceDefinitionsToProcess: Seq[SourceDefinition],
canonicalToMap: Map[CanonicalName, NonPrimitiveType],
sourceDefinitionsProcessed: Seq[SourceDefinition] = Seq.empty,
sourceFilesGenerated: Seq[SourceFile] = Seq.empty,
toMap: Map[CanonicalName, TransferObjectClassDefinition] = Map.empty,
toInterfaceMap: Map[CanonicalName, TransferObjectInterfaceDefinition] = Map.empty,
toChildParentsMap: Map[CanonicalName, Set[CanonicalName]] = Map.empty,
toParentChildrenMap: Map[CanonicalName, Set[CanonicalName]] = Map.empty) {
def addSourceDefinition(sourceDefinition: SourceDefinition): GenerationAggr =
copy(sourceDefinitionsToProcess = sourceDefinition +: sourceDefinitionsToProcess)
def addSourceDefinitions(sourceDefinitionsToAdd: Seq[SourceDefinition]): GenerationAggr =
copy(sourceDefinitionsToProcess = sourceDefinitionsToProcess ++ sourceDefinitionsToAdd)
def addSourceFile(sourceFile: SourceFile): GenerationAggr =
copy(sourceFilesGenerated = sourceFile +: sourceFilesGenerated)
def addSourceFiles(sourceFiles: Seq[SourceFile]): GenerationAggr =
copy(sourceFilesGenerated = sourceFiles ++ sourceFilesGenerated)
def addInterfaceSourceDefinition(interfaceDefinition: TransferObjectInterfaceDefinition): GenerationAggr = {
val canonicalName = interfaceDefinition.origin.reference.canonicalName
toInterfaceMap.get(canonicalName) match {
case Some(toInterfaceDefinition) => this
case None =>
this
.copy(toInterfaceMap = toInterfaceMap + (canonicalName -> interfaceDefinition))
.addSourceDefinition(interfaceDefinition)
}
}
def hasParents(canonicalName: CanonicalName): Boolean = toChildParentsMap.get(canonicalName).exists(_.nonEmpty)
def hasChildren(canonicalName: CanonicalName): Boolean = toParentChildrenMap.get(canonicalName).exists(_.nonEmpty)
def hasInterface(canonicalName: CanonicalName): Boolean = toInterfaceMap.get(canonicalName).isDefined
def getInterfaceDefinition(canonicalName: CanonicalName): Option[TransferObjectInterfaceDefinition] = toInterfaceMap.get(canonicalName)
def directParents(canonicalName: CanonicalName): Set[CanonicalName] = toChildParentsMap.getOrElse(canonicalName, Set.empty)
def isParentOf(potentialParent: CanonicalName, potentialChild: CanonicalName): Boolean =
allParents(potentialChild).contains(potentialParent)
def directChildren(canonicalName: CanonicalName): Set[CanonicalName] = toParentChildrenMap.getOrElse(canonicalName, Set.empty)
/**
* Find all leaf children of the given canonical name (itself not included if it is a leaf child).
*/
def leafChildren(canonicalName: CanonicalName): Set[CanonicalName] = {
def findLeafChildren(childrenToCheck: List[CanonicalName], leafChildrenFound: Set[CanonicalName] = Set.empty): Set[CanonicalName] = {
childrenToCheck match {
case Nil => leafChildrenFound
case child :: remainingChildren if isLeafChild(child) => findLeafChildren(remainingChildren, leafChildrenFound + child)
case child :: remainingChildren =>
findLeafChildren(directChildren(child).toList ::: remainingChildren, leafChildrenFound)
}
}
findLeafChildren(directChildren(canonicalName).toList)
}
/**
* Find all non-leaf children of the given canonical name (itself not included if it is a non-leaf child).
*/
def nonLeafChildren(canonicalName: CanonicalName): Set[CanonicalName] = {
def findNonLeafChildren(childrenToCheck: List[CanonicalName],
nonLeafChildrenFound: Set[CanonicalName] = Set.empty): Set[CanonicalName] = {
childrenToCheck match {
case Nil => nonLeafChildrenFound
case child :: remainingChildren if hasChildren(child) =>
findNonLeafChildren(directChildren(child).toList ::: remainingChildren, nonLeafChildrenFound + child)
case child :: remainingChildren => findNonLeafChildren(remainingChildren, nonLeafChildrenFound)
}
}
findNonLeafChildren(directChildren(canonicalName).toList)
}
def isParent(canonicalName: CanonicalName): Boolean = hasChildren(canonicalName)
def isChild(canonicalName: CanonicalName): Boolean = hasParents(canonicalName)
def isInHierarchy(canonicalName: CanonicalName): Boolean = isChild(canonicalName) || isParent(canonicalName)
def isLeafChild(canonicalName: CanonicalName): Boolean = isChild(canonicalName) && !isParent(canonicalName)
def isNonLeafChild(canonicalName: CanonicalName): Boolean = isChild(canonicalName) && isParent(canonicalName)
/**
* A class is a parent in a multiple inheritance relation if it has a child (direct or indirect) that has more than one parent.
*/
def isParentInMultipleInheritanceRelation(canonicalName: CanonicalName): Boolean =
allChildren(canonicalName).exists(directParents(_).size > 1)
/**
* @return A breadth-first list of all parent canonical names.
*/
def allParents(canonicalName: CanonicalName): List[CanonicalName] = {
def findParents(parentsToExpand: List[CanonicalName], parentsFound: List[CanonicalName] = List.empty): List[CanonicalName] = {
parentsToExpand match {
case Nil => parentsFound
case moreParents =>
val nextLevelOfParents =
parentsToExpand.flatMap { parent =>
directParents(parent).toList
}
findParents(nextLevelOfParents, parentsFound ++ parentsToExpand)
}
}
findParents(directParents(canonicalName).toList)
}
def allChildren(canonicalName: CanonicalName): List[CanonicalName] = {
def findChildren(childrenToExpand: List[CanonicalName], childrenFound: List[CanonicalName] = List.empty): List[CanonicalName] = {
childrenToExpand match {
case Nil => childrenFound
case moreChildren =>
val nextLevelOfChildren =
childrenToExpand.flatMap { child =>
directChildren(child).toList
}
findChildren(nextLevelOfChildren, childrenFound ++ childrenToExpand)
}
}
findChildren(directChildren(canonicalName).toList)
}
/**
* Adds a TO definition and update the child-parents map and the parent-children map.
*
* @param canonicalName The canonical name of the TO.
* @param toDefinition The definition of the TO.
* @return The generation aggregate.
*/
def addToDefinition(canonicalName: CanonicalName, toDefinition: TransferObjectClassDefinition): GenerationAggr = {
val parentsMap: (CanonicalName, Set[CanonicalName]) = canonicalName -> toDefinition.parents.map(_.canonicalName).toSet
val updatedAggr = updateChildParentsRelations(parentsMap)
updatedAggr.copy(toMap = updatedAggr.toMap + (canonicalName -> toDefinition))
}
def generate(implicit platform: Platform): GenerationAggr = {
import Platform._
sourceDefinitionsToProcess match {
case srcDef :: srcDefs => srcDef.toSourceFile(this.markSourceDefinitionsHeadAsProcessed).generate
case Nil => this
}
}
private def markSourceDefinitionsHeadAsProcessed: GenerationAggr =
copy(
sourceDefinitionsToProcess = sourceDefinitionsToProcess.tail,
sourceDefinitionsProcessed = sourceDefinitionsToProcess.head +: sourceDefinitionsProcessed
)
private def updateChildParentsRelations(childWithParents: (CanonicalName, Set[CanonicalName])): GenerationAggr = {
val (child, parents) = childWithParents
def updatedAggregate = {
val aggrWithUpdatedParentChildrenRelation =
parents.foldLeft(this) { (aggr, parent) =>
val childrenOfParent = aggr.toParentChildrenMap.getOrElse(parent, Set.empty[CanonicalName])
aggr.copy(toParentChildrenMap = aggr.toParentChildrenMap + (parent -> (childrenOfParent + child)))
}
aggrWithUpdatedParentChildrenRelation
.copy(toChildParentsMap = aggrWithUpdatedParentChildrenRelation.toChildParentsMap + childWithParents)
}
if (parents.nonEmpty) updatedAggregate
else this
}
}
object GenerationAggr {
def apply(apiName: String,
apiBasePackage: List[String],
raml: Raml,
canonicalToMap: Map[CanonicalName, NonPrimitiveType]): GenerationAggr = {
val topLevelResourceDefinitions = raml.resources.map(ResourceClassDefinition(apiBasePackage, List.empty, _))
val clientClassDefinition =
ClientClassDefinition(
apiName = apiName,
baseUri = raml.baseUri,
basePackage = apiBasePackage,
topLevelResourceDefinitions = topLevelResourceDefinitions
)
val sourceDefinitions: Seq[SourceDefinition] = Seq(clientClassDefinition)
val generationAggrBeforeCanonicalDefinitions =
GenerationAggr(basePackage = apiBasePackage, sourceDefinitionsToProcess = sourceDefinitions, canonicalToMap = canonicalToMap)
val finalGenerationAggregate: GenerationAggr =
CanonicalToSourceDefinitionGenerator.transferObjectsToClassDefinitions(generationAggrBeforeCanonicalDefinitions)
finalGenerationAggregate
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/UnionType.scala | <filename>modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/canonicaltypes/UnionType.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 11/12/16.
*/
case class UnionType(types: Set[TypeReference]) extends NonPrimitiveType {
lazy val canonicalName: CanonicalName = {
val classNames = types.map(_.refers.name).toList.sorted
val packages = types.map(_.refers.packagePath).toList
val commonPackage = findCommonPackage(packages)
CanonicalName.create(name = s"UnionOf${classNames.mkString("With")}", packagePath = commonPackage)
}
private def findCommonPackage(packages: List[List[String]]): List[String] = {
def findCommon(packs: List[List[String]], common: List[String] = List.empty): List[String] = {
val headOpts = packs.map(_.headOption)
if (headOpts.contains(None)) {
common
} else {
val heads = headOpts.map(_.get)
val firstHead = heads.head
if (heads.tail.exists(_ != firstHead)) {
common
} else {
val tails = packs.map(_.tail)
findCommon(tails, common :+ firstHead)
}
}
}
findCommon(packages)
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/parsedtypes/ParsedType.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 play.api.libs.json.JsValue
import scala.util.Try
/**
* Created by peter on 10/02/16.
*/
trait ParsedType extends Identifiable {
def required: Option[Boolean]
// The default value according to the RAML 1.0 specs is true. According to the json-schema 0.3 specs, it should be false.
// The json-schema 0.4 specs don't specify a 'required: boolean' field any more, only a list of the required field names at the
// level of the object definition, but this also implies a default value of false.
def isRequired = required.getOrElse(defaultRequiredValue)
def defaultRequiredValue = model match {
case JsonSchemaModel => false
case RamlModel => true
}
def updated(id: Id): ParsedType
}
trait Identifiable {
def id: Id
def updated(id: Id): Identifiable
def asTypeModel(typeModel: TypeModel): ParsedType
def model: TypeModel
}
trait PrimitiveType extends ParsedType
trait NonPrimitiveType extends ParsedType
/**
* Only used in json-schema.
*/
trait Fragmented {
def fragments: Fragments
def fragment(field: String): Option[Identifiable] = fragments.fragmentMap.get(field)
def fragment(fields: List[String]): Option[Identifiable] = {
val aggregate: (Option[Fragmented], Option[Identifiable]) = (Some(this), None)
val (_, identifiableOpt) =
fields.foldLeft(aggregate) {
case ((Some(fragm), _), field) =>
val next = fragm.fragment(field)
next match {
case Some(frag: Fragmented) => (Some(frag), next)
case _ => (None, next)
}
case ((None, _), _) => (None, None)
}
identifiableOpt
}
}
trait AllowedAsObjectField {}
object ParsedType {
def apply(typeName: String)(implicit parseContext: ParseContext): Try[ParsedType] = {
typeName match {
case ParsedString.value => Try(new ParsedString())
case ParsedNumber.value => Try(new ParsedNumber())
case ParsedInteger.value => Try(new ParsedInteger())
case ParsedBoolean.value => Try(new ParsedBoolean())
case ParsedNull.value => Try(new ParsedString())
case ParsedUnionType(tryUnionType) => tryUnionType
case ParsedArray(tryArrayType) => tryArrayType
case namedType => Try(ParsedTypeReference(NativeId(namedType)))
}
}
def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[ParsedType]] = {
val result =
json match {
case ParsedMultipleInheritance(tryMultiType) => Some(tryMultiType)
case ParsedArray(tryArrayType) => Some(tryArrayType) // ArrayType must stay on the second spot of this pattern match!
case ParsedUnionType(tryUnionType) => Some(tryUnionType)
case ParsedString(tryStringType) => Some(tryStringType)
case ParsedNumber(tryNumberType) => Some(tryNumberType)
case ParsedInteger(tryIntegerType) => Some(tryIntegerType)
case ParsedBoolean(tryBooleanType) => Some(tryBooleanType)
case ParsedDateOnly(dateOnlyType) => Some(dateOnlyType)
case ParsedTimeOnly(timeOnlyType) => Some(timeOnlyType)
case ParsedDateTimeOnly(dateTimeOnlyType) => Some(dateTimeOnlyType)
case ParsedDateTimeDefault(dateTimeDefaultType) => Some(dateTimeDefaultType)
case ParsedDateTimeRFC2616(dateTimeRfc2616Type) => Some(dateTimeRfc2616Type)
case ParsedFile(fileType) => Some(fileType)
case ParsedNull(tryNullType) => Some(tryNullType)
case ParsedEnum(tryEnumType) => Some(tryEnumType)
case ParsedObject(tryObjectType) => Some(tryObjectType)
case ParsedGenericObject(tryGenericObjectType) => Some(tryGenericObjectType)
case ParsedTypeReference(tryTypeReferenceType) => Some(tryTypeReferenceType)
case InlineTypeDeclaration(inlineType) => Some(inlineType)
case ParsedFragmentContainer(tryFragmentCont) => Some(tryFragmentCont)
case _ => None
}
result
}
def typeDeclaration(json: JsValue): Option[JsValue] = {
List((json \ "type").toOption, (json \ "schema").toOption).flatten.headOption
}
}
object PrimitiveType {
def unapply(json: JsValue)(implicit parseContext: ParseContext): Option[Try[PrimitiveType]] = {
json match {
case ParsedString(triedStringType) => Some(triedStringType)
case ParsedNumber(triedNumberType) => Some(triedNumberType)
case ParsedInteger(triedIntegerType) => Some(triedIntegerType)
case ParsedBoolean(triedBooleanType) => Some(triedBooleanType)
case ParsedNull(triedNullType) => Some(triedNullType)
case _ => None
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/htmldoc/simplifiedmodel/CombinedResource.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.htmldoc.simplifiedmodel
import java.util.UUID
import io.atomicbits.scraml.generator.codegen.GenerationAggr
import io.atomicbits.scraml.generator.typemodel.ResourceClassDefinition
import io.atomicbits.scraml.ramlparser.model.Parameter
/**
* Created by peter on 4/06/18.
*/
case class CombinedResource(uniqueId: String,
url: String,
urlParameters: List[SimpleParameter],
displayName: Option[String],
description: Option[String],
actions: List[SimpleAction],
subResources: List[CombinedResource])
object CombinedResource {
/**
* Recursively create the combined resource tree from a given resource class definition.
*/
def apply(resourceClassDefinition: ResourceClassDefinition,
generationAggr: GenerationAggr,
parentUrl: String = "",
urlParameters: List[Parameter] = List.empty): List[CombinedResource] = {
val combinedUrlPrameters = resourceClassDefinition.resource.urlParameter.toList ++ urlParameters
val url = resourceClassDefinition.resource.urlParameter match {
case None => s"$parentUrl/${resourceClassDefinition.resource.urlSegment}"
case Some(param) => s"$parentUrl/{${resourceClassDefinition.resource.urlSegment}}"
}
resourceClassDefinition.resource.actions match {
case am :: ams =>
val combinedResource =
CombinedResource(
uniqueId = UUID.randomUUID().toString,
url = url,
urlParameters = combinedUrlPrameters.map(SimpleParameter(_, generationAggr)),
displayName = resourceClassDefinition.resource.displayName,
description = resourceClassDefinition.resource.description,
actions = resourceClassDefinition.resource.actions.map(SimpleAction(_, generationAggr)),
subResources = resourceClassDefinition.childResourceDefinitions.flatMap(rd =>
CombinedResource(rd, generationAggr, url, combinedUrlPrameters))
)
List(combinedResource)
case Nil =>
resourceClassDefinition.childResourceDefinitions.flatMap(rd => CombinedResource(rd, generationAggr, url, combinedUrlPrameters))
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/htmldoc/simplifiedmodel/SimpleBody.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.htmldoc.simplifiedmodel
import io.atomicbits.scraml.generator.codegen.GenerationAggr
import io.atomicbits.scraml.ramlparser.model.{ Body, BodyContent }
/**
* Created by peter on 6/06/18.
*/
case class SimpleBody(bodyContent: List[SimpleBodyContent])
object SimpleBody {
def apply(body: Body, generationAggr: GenerationAggr): SimpleBody =
SimpleBody(bodyContent = body.contentMap.values.toList.map(bc => SimpleBodyContent(bc, generationAggr)))
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/DateWrapper.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
import java.time.{ LocalDate, LocalDateTime, LocalTime, OffsetDateTime }
import java.time.format.DateTimeFormatter
import play.api.libs.json._
import scala.util.{ Failure, Success, Try }
/**
* Created by peter on 7/10/17.
*/
trait DateWrapper
case class DateTimeRFC3339(dateTime: OffsetDateTime) extends DateWrapper
object DateTimeRFC3339 {
// DateTimeFormatter.ISO_OFFSET_DATE_TIME
// "yyyy-MM-dd'T'HH:mm:ss[.SSS]XXX"
val formatter: DateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME
def parse(dateTime: String): DateTimeRFC3339 = DateTimeRFC3339(OffsetDateTime.parse(dateTime, formatter))
def format(dateTimeRFC3339: DateTimeRFC3339): String = formatter.format(dateTimeRFC3339.dateTime)
implicit val jsonFormat = new Format[DateTimeRFC3339] {
override def reads(json: JsValue) = json match {
case JsString(s) =>
Try(parse(s)) match {
case Success(dateTime) => JsSuccess(dateTime)
case Failure(_) => JsError("error.expected.RFC3339DateTime")
}
case _ => JsError("error.expected.jsstring")
}
override def writes(dateTime: DateTimeRFC3339): JsValue = JsString(format(dateTime))
}
}
/**
* RFC2616: https://www.ietf.org/rfc/rfc2616.txt
* HTTP date: rfc1123-date (| rfc850-date | asctime-date)
*/
case class DateTimeRFC2616(dateTime: OffsetDateTime) extends DateWrapper
object DateTimeRFC2616 {
// DateTimeFormatter.RFC_1123_DATE_TIME
// "EEE, dd MMM yyyy HH:mm:ss 'GMT'"
val formatter: DateTimeFormatter = DateTimeFormatter.RFC_1123_DATE_TIME
def parse(dateTime: String): DateTimeRFC2616 = DateTimeRFC2616(OffsetDateTime.parse(dateTime, formatter))
def format(dateTimeRFC2616: DateTimeRFC2616): String = formatter.format(dateTimeRFC2616.dateTime)
implicit val jsonFormat = new Format[DateTimeRFC2616] {
override def reads(json: JsValue) = json match {
case JsString(s) =>
Try(parse(s)) match {
case Success(dateTime) => JsSuccess(dateTime)
case Failure(_) => JsError("error.expected.RFC1123DateTime")
}
case _ => JsError("error.expected.jsstring")
}
override def writes(dateTime: DateTimeRFC2616): JsValue = JsString(format(dateTime))
}
}
case class DateTimeOnly(dateTime: LocalDateTime) extends DateWrapper
object DateTimeOnly {
// DateTimeFormatter.ISO_LOCAL_DATE_TIME
// "yyyy-MM-dd'T'HH:mm:ss[.SSS]"
val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
def parse(dateTime: String): DateTimeOnly = DateTimeOnly(LocalDateTime.parse(dateTime, formatter))
def format(dateTimeOnly: DateTimeOnly): String = formatter.format(dateTimeOnly.dateTime)
implicit val jsonFormat = new Format[DateTimeOnly] {
override def reads(json: JsValue) = json match {
case JsString(s) =>
Try(parse(s)) match {
case Success(dateTimeOnly) => JsSuccess(dateTimeOnly)
case Failure(_) => JsError("error.expected.DateTimeOnly")
}
case _ => JsError("error.expected.jsstring")
}
override def writes(dateTimeOnly: DateTimeOnly): JsValue = JsString(format(dateTimeOnly))
}
}
case class TimeOnly(time: LocalTime) extends DateWrapper
object TimeOnly {
// DateTimeFormatter.ISO_LOCAL_TIME
// "HH:mm:ss[.SSS]"
val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_TIME
def parse(time: String): TimeOnly = TimeOnly(LocalTime.parse(time, formatter))
def format(timeOnly: TimeOnly): String = formatter.format(timeOnly.time)
implicit val jsonFormat = new Format[TimeOnly] {
override def reads(json: JsValue) = json match {
case JsString(s) =>
Try(parse(s)) match {
case Success(timeOnly) => JsSuccess(timeOnly)
case Failure(_) => JsError("error.expected.TimeOnly")
}
case _ => JsError("error.expected.jsstring")
}
override def writes(timeOnly: TimeOnly): JsValue = JsString(format(timeOnly))
}
}
case class DateOnly(date: LocalDate) extends DateWrapper
object DateOnly {
// DateTimeFormatter.ISO_LOCAL_DATE
// "yyyy-MM-dd"
val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE
def parse(date: String): DateOnly = DateOnly(LocalDate.parse(date, formatter))
def format(dateOnly: DateOnly): String = formatter.format(dateOnly.date)
implicit val jsonFormat = new Format[DateOnly] {
override def reads(json: JsValue) = json match {
case JsString(s) =>
Try(parse(s)) match {
case Success(dateOnly) => JsSuccess(dateOnly)
case Failure(_) => JsError("error.expected.DateOnly")
}
case _ => JsError("error.expected.jsstring")
}
override def writes(dateOnly: DateOnly): JsValue = JsString(format(dateOnly))
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/CollectJsonSchemaParsedTypesTest.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.{ CanonicalLookupHelper, CanonicalNameGenerator, CanonicalTypeCollector }
import io.atomicbits.scraml.ramlparser.model._
import io.atomicbits.scraml.ramlparser.model.parsedtypes.{ ParsedObject, ParsedTypeReference }
import io.atomicbits.scraml.ramlparser.parser.RamlParser
import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen }
import scala.util.Try
import org.scalatest.featurespec.AnyFeatureSpec
import org.scalatest.matchers.should.Matchers._
import io.atomicbits.util.TestUtils._
/**
* Created by peter on 2/01/17.
*/
class CollectJsonSchemaParsedTypesTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll {
Feature("Collect all json-schema ParsedTypes after expanding all relative IDs to absolute IDs") {
Scenario("test collecting of all types in a json-schema type declaration") {
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
implicit val canonicalNameGenerator: CanonicalNameGenerator = CanonicalNameGenerator(defaultBasePath)
val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator)
Then("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 barReference = myFragmentsExpanded.fragments.fragmentMap("bar").asInstanceOf[ParsedTypeReference]
barReference.refersTo shouldBe NoId
val collectedParsedTypes: CanonicalLookupHelper =
canonicalTypeCollector.indexer.collectJsonSchemaParsedTypes(myFragmentsExpanded, CanonicalLookupHelper())
collectedParsedTypes.parsedTypeIndex.keys should contain(
AbsoluteFragmentId(
RootId("http://atomicbits.io/schema/fragments.json"),
List("definitions", "bars")
)
)
collectedParsedTypes.parsedTypeIndex.keys should contain(
AbsoluteFragmentId(
RootId("http://atomicbits.io/schema/fragments.json"),
List("definitions", "barlist")
)
)
collectedParsedTypes.parsedTypeIndex.keys should contain(
AbsoluteFragmentId(
RootId("http://atomicbits.io/schema/fragments.json"),
List("definitions", "barpointer")
)
)
// println(s"$collectedParsedTypes")
}
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
implicit val canonicalNameGenerator: CanonicalNameGenerator = CanonicalNameGenerator(defaultBasePath)
val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator)
Then("we get all four actions in the userid resource")
val raml = parsedModel.get
val canonicalLHWithIndexedParsedTypes = canonicalTypeCollector.indexer.indexParsedTypes(raml, CanonicalLookupHelper())
val geometryTypeOpt = canonicalLHWithIndexedParsedTypes.getParsedTypeWithProperId(NativeId("geometry"))
geometryTypeOpt.isDefined shouldBe true
geometryTypeOpt.get.isInstanceOf[ParsedObject] shouldBe true
// ToDo: check for the presence of the Cat and the Fish
val animalTypeOpt = canonicalLHWithIndexedParsedTypes.getParsedTypeWithProperId(NativeId("Animal"))
canonicalLHWithIndexedParsedTypes
.getParsedTypeWithProperId(RootId("http://atomicbits.io/schema/animal.json"))
.isDefined shouldBe true
canonicalLHWithIndexedParsedTypes.getParsedTypeWithProperId(RootId("http://atomicbits.io/schema/dog.json")).isDefined shouldBe true
// println(s"${prettyPrint(canonicalLHWithIndexedParsedTypes)}")
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/QuestionMarkMarksOptionalPropertyOrParameterTest.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.{ ParsedArray, ParsedObject, ParsedString }
import io.atomicbits.scraml.ramlparser.model.{ Get, NativeId, Raml }
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 24/03/17.
*/
class QuestionMarkMarksOptionalPropertyOrParameterTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll {
Feature("Question marks can be used to mark optional properties or parameters") {
Scenario("Test parsing an optional property ") {
Given("a RAML specification with an optional property marked by a '?'")
val defaultBasePath = List("io", "atomicbits", "raml10")
val parser = RamlParser("/questionmarkforoptional/questionmark-api.raml", "UTF-8")
When("we parse the RAML spec")
val raml: Raml = parser.parse.get
Then("we should see that the property is optional")
val parsedAnimal = raml.types.typeReferences(NativeId("Animal")).asInstanceOf[ParsedObject]
parsedAnimal.properties.valueMap("kind").required shouldBe true
parsedAnimal.properties.valueMap("gender").required shouldBe true
parsedAnimal.properties.valueMap("isNice").required shouldBe false
parsedAnimal.properties.valueMap("isVeryNice?").required shouldBe false
parsedAnimal.properties.valueMap.get("isNice?").isDefined shouldBe false
parsedAnimal.properties.valueMap.get("isVeryNice??").isDefined shouldBe false
}
Scenario("Test parsing an optional parameter") {
Given("a RAML specification with an optional parameter marked by a '?'")
val defaultBasePath = List("io", "atomicbits", "raml10")
val parser = RamlParser("/questionmarkforoptional/questionmark-api.raml", "UTF-8")
When("we parse the RAML spec")
val raml: Raml = parser.parse.get
Then("we should see that the parameter is optional")
val queryParameters = raml.resourceMap("animals").actionMap(Get).queryParameters.valueMap
queryParameters("kind").required shouldBe true
queryParameters("gender").required shouldBe false
queryParameters("name").required shouldBe false
queryParameters("caretaker").required shouldBe false
queryParameters("food").required shouldBe true
queryParameters.get("gender?").isDefined shouldBe false
queryParameters("name").parameterType.parsed shouldBe a[ParsedArray]
queryParameters("name").parameterType.parsed.asInstanceOf[ParsedArray].items shouldBe a[ParsedString]
queryParameters("caretaker").parameterType.parsed shouldBe a[ParsedArray]
queryParameters("caretaker").parameterType.parsed.asInstanceOf[ParsedArray].items shouldBe a[ParsedString]
queryParameters("food").parameterType.parsed shouldBe a[ParsedArray]
queryParameters("food").parameterType.parsed.asInstanceOf[ParsedArray].items shouldBe a[ParsedString]
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/license/LicenseVerifier.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.license
import java.security.{ KeyFactory, PublicKey, Signature }
import java.security.spec.X509EncodedKeySpec
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import sun.misc.BASE64Decoder
import scala.util.Try
import scala.util.control.NonFatal
/**
* Created by peter on 29/06/16.
*/
object LicenseVerifier {
val charset = "UTF-8"
val datePattern = "yyyy-MM-dd"
val algorithm = "RSA"
// Encryption algorithm
val signatureAlgorithm = "SHA1WithRSA"
val freeLicenseStatementMandatoryPart =
"use the free scraml license in this project without any intend to serve commercial purposes for ourselves or anyone else"
val freeLicenseStatementOfIntend = s"<We/I>, <enter name here>, $freeLicenseStatementMandatoryPart."
val publicKeyPEM =
"""
<KEY>8M61TJRGKrBV0q+TCudLswcDnLkw0WQpJUE4RgYKJoi4j1K9+R6L1c5/B6cdgaQrIurt52A9Jffj
|aJ4+tlSyNsSmR3w320+KYj5uG+NKSZcghIwzbIYSZkSS+hKfQIEPbAUY0hFWIL0PuEuEuRXxnJXQ
|6+tuQ04hfkJn9NVBFZPOIY+nw7nmzZnstbJsnCPW47Ple2Fyv6VV/jZlRyuE3P2VAn5p+8KPc2uH
|5SnYWQIDAQAB
""".stripMargin.trim
@volatile
private var validatedLicenses: Map[String, Option[LicenseData]] = Map.empty
def validateLicense(licenseKey: String): Option[LicenseData] = {
val cleanKey = cleanCommercialLicenseKey(licenseKey)
// Make sure decodeAndRegister is only executed if the key is not yet contained in validatedLicenses!
// Do not simply the expression below with validatedLicenses.getOrElse(licenseKey, decodeAndRegister(licenseKey)) !
validatedLicenses.get(cleanKey) match {
case Some(optionalLicenseData) => optionalLicenseData.flatMap(checkExpiryDate)
case None => decodeVerifyAndRegister(cleanKey)
}
}
private def decodeVerifyAndRegister(licenseKey: String): Option[LicenseData] = {
val decoded = decodeLicense(licenseKey).flatMap(checkExpiryDate)
addValidatedLicense(licenseKey, decoded)
decoded
}
private def decodeLicense(licenseKey: String): Option[LicenseData] =
decodeFreeLicense(licenseKey).orElse(decodeCommercialLicense(licenseKey))
private def decodeFreeLicense(licenseKey: String): Option[LicenseData] = {
val cleanKey = cleanFreeLicenseKey(licenseKey)
if (cleanKey.toLowerCase.contains(freeLicenseStatementMandatoryPart.toLowerCase)) {
val userName =
getFreeLicenseKeyUser(cleanKey)
.getOrElse(
sys.error(
s"Please state the free license intend as:\n$freeLicenseStatementOfIntend\n and fill in your name between the commas."
)
)
val licenseData =
LicenseData(
customerId = "-1",
licenseId = "-1",
licenseType = "Free",
owner = userName,
period = -1,
purchaseDate = LocalDate.now()
)
println(s"Free Scraml license used by ${licenseData.owner}.")
Some(licenseData)
} else {
None
}
}
private def decodeCommercialLicense(licenseKey: String): Option[LicenseData] = {
val encodedKey = licenseKey.trim
val signedKeyBytes =
Try(new BASE64Decoder().decodeBuffer(encodedKey)).getOrElse(sys.error(s"Cannot verify license key with bad key format."))
val signedKey = new String(signedKeyBytes, charset)
val (unsignedKey, signature) = signedKey.split('!').toList match {
case uKey :: sig :: _ => (uKey, sig)
case _ => sys.error(s"Cannot verify key with bad key format: $signedKey")
}
if (verifySignature(unsignedKey, signature)) {
unsignedKey.split(';').toList match {
case List(licenseType, customerId, licenseId, owner, purchaseDateString, periodString) =>
val licenseData =
LicenseData(
customerId = customerId,
licenseId = licenseId,
owner = owner,
licenseType = licenseType,
period = Try(periodString.toLong).getOrElse(0),
purchaseDate =
Try(LocalDate.parse(purchaseDateString, DateTimeFormatter.ofPattern(datePattern))).getOrElse(LocalDate.ofYearDay(1950, 1))
)
println(s"Scraml license $licenseId is licensed to $owner.")
Some(licenseData)
case x =>
println(s"Invalid license key. Falling back to default AGPL license.")
None
}
} else {
println(s"Invalid license key. Falling back to default AGPL license.\n$licenseKey")
None
}
}
private def checkExpiryDate(licenseKey: LicenseData): Option[LicenseData] = {
val today = LocalDate.now()
val expiryDate = licenseKey.purchaseDate.plusDays(licenseKey.period)
val warningDate = licenseKey.purchaseDate.plusDays(licenseKey.period - 31)
if (licenseKey.period < 0) {
// Key with unlimited period.
Some(licenseKey)
} else if (today.isAfter(expiryDate)) {
println(
s"""
|
|Warning: your scraml license key expired on ${expiryDate.format(DateTimeFormatter.ISO_DATE)}.
|
|We will now fall back to the default AGPL license!
|
|""".stripMargin
)
None
} else if (today.isAfter(warningDate)) {
println(
s"""
|
|Warning: your scraml license key expires on ${expiryDate.format(DateTimeFormatter.ISO_DATE)}.
|
|""".stripMargin
)
Some(licenseKey)
} else {
Some(licenseKey)
}
}
private def verifySignature(text: String, signature: String): Boolean = {
val textBytes: Array[Byte] = text.getBytes("UTF8")
val signer: Signature = Signature.getInstance(signatureAlgorithm)
signer.initVerify(publicKey)
signer.update(textBytes)
Try(signer.verify(new BASE64Decoder().decodeBuffer(signature))).recover {
case NonFatal(exc) => false
}.get
}
lazy val publicKey: PublicKey = {
val b64: BASE64Decoder = new BASE64Decoder
val decoded: Array[Byte] = b64.decodeBuffer(publicKeyPEM)
val spec: X509EncodedKeySpec = new X509EncodedKeySpec(decoded)
val kf: KeyFactory = KeyFactory.getInstance(algorithm)
kf.generatePublic(spec)
}
private def addValidatedLicense(licenseKey: String, licenseData: Option[LicenseData]): Unit = {
LicenseVerifier.synchronized {
validatedLicenses += licenseKey -> licenseData
}
}
private def cleanCommercialLicenseKey(licenseKey: String): String = {
licenseKey.split('\n').map(line => line.trim).mkString("\n")
}
/**
* replace all (successive) whitespace with a single space character
*
* see: https://stackoverflow.com/questions/5455794/removing-whitespace-from-strings-in-java
*
*/
private def cleanFreeLicenseKey(licenseKey: String): String = licenseKey.replaceAll("\\s+", " ")
private def getFreeLicenseKeyUser(licenseKey: String): Option[String] = {
licenseKey.split(',').toList match {
case l1 :: name :: ln => Some(name.trim)
case _ => None
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/restmodel/TypedRestOps.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.restmodel
import io.atomicbits.scraml.generator.platform.Platform
import io.atomicbits.scraml.generator.typemodel.ClassPointer
import io.atomicbits.scraml.ramlparser.model.{ BodyContent, Parameter, QueryString }
/**
* Created by peter on 3/04/17.
*/
object TypedRestOps {
implicit class ParameterExtension(val parameter: Parameter) {
def classPointer(): ClassPointer = {
parameter.parameterType.canonical.collect {
case typeReference => Platform.typeReferenceToClassPointer(typeReference)
} getOrElse sys.error(s"Could not retrieve the canonical type reference from parameter $parameter.")
}
}
implicit class BodyContentExtension(val bodyContent: BodyContent) {
def classPointerOpt(): Option[ClassPointer] = {
for {
bdType <- bodyContent.bodyType
canonicalBdType <- bdType.canonical
} yield {
Platform.typeReferenceToClassPointer(canonicalBdType)
}
}
}
implicit class QueryStringExtension(val queryString: QueryString) {
def classPointer(): ClassPointer = {
queryString.queryStringType.canonical.collect {
case typeReference => Platform.typeReferenceToClassPointer(typeReference)
} getOrElse sys.error(s"Could not retrieve the canonical type reference from queryString $queryString.")
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/test/scala/io/atomicbits/scraml/generator/GeneratorTest.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.Platform
import io.atomicbits.scraml.generator.platform.javajackson.JavaJackson
import io.atomicbits.scraml.generator.platform.scalaplay.ScalaPlay
import io.atomicbits.scraml.generator.typemodel._
import io.atomicbits.scraml.ramlparser.model.canonicaltypes.CanonicalName
import org.scalatest.concurrent.ScalaFutures
import org.scalatest._
import org.scalatest.featurespec.AnyFeatureSpec
import org.scalatest.matchers.should.Matchers._
/**
* Created by peter on 10/09/15.
*/
class GeneratorTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll with ScalaFutures {
import io.atomicbits.scraml.generator.platform.Platform._
Feature("The scraml generator generates DSL classes") {
Scenario("test the generation of an object hierarchy") {
Given("a json-schema containing an object hierarcy")
val apiLocation = "objecthierarchy/TestObjectHierarchyApi.raml"
When("we generate the RAMl specification into class representations")
implicit val platform: ScalaPlay = ScalaPlay(List("io", "atomicbits", "scraml"))
val generationAggr: GenerationAggr =
ScramlGenerator
.buildGenerationAggr(
ramlApiPath = apiLocation,
apiClassName = "TestObjectHierarchyApi",
platform
)
.generate
Then("we should get valid a class hierarchy")
val animalToClassName = CanonicalName.create("Animal", List("io", "atomicbits", "schema"))
val catToClassName = CanonicalName.create("Cat", List("io", "atomicbits", "schema"))
val dogToClassName = CanonicalName.create("Dog", List("io", "atomicbits", "schema"))
val fishToClassName = CanonicalName.create("Fish", List("io", "atomicbits", "schema"))
val animalToDef: TransferObjectClassDefinition = generationAggr.toMap(animalToClassName)
val animalChildren: Set[CanonicalName] = generationAggr.directChildren(animalToClassName)
animalChildren should contain(catToClassName)
animalChildren should contain(dogToClassName)
animalChildren should contain(fishToClassName)
generationAggr.directParents(animalToClassName) shouldBe Set.empty
generationAggr.directParents(catToClassName) shouldBe Set(animalToClassName)
generationAggr.directParents(dogToClassName) shouldBe Set(animalToClassName)
generationAggr.directParents(fishToClassName) shouldBe Set(animalToClassName)
}
Scenario("test generated Scala DSL") {
Given("a RAML specification")
val apiLocation = "io/atomicbits/scraml/TestApi.raml"
When("we generate the RAMl specification into class representations")
implicit val platform: Platform = ScalaPlay(List("io", "atomicbits", "scraml"))
val generationAggr: GenerationAggr =
ScramlGenerator
.buildGenerationAggr(
ramlApiPath = apiLocation,
apiClassName = "TestApi",
platform
)
.generate
Then("we should get valid class representations")
val generatedFilePaths =
generationAggr.sourceFilesGenerated
.map(_.filePath.toString)
.toSet
val expectedFilePaths = Set(
"io/atomicbits/scraml/TestApi.scala",
"io/atomicbits/scraml/rest/RestResource.scala",
"io/atomicbits/scraml/rest/user/UserResource.scala",
"io/atomicbits/scraml/rest/user/userid/dogs/DogsResource.scala",
"io/atomicbits/scraml/rest/user/userid/UseridResource.scala",
"io/atomicbits/scraml/rest/user/userid/AcceptApplicationVndV01JsonHeaderSegment.scala",
"io/atomicbits/scraml/rest/user/userid/AcceptApplicationVndV10JsonHeaderSegment.scala",
"io/atomicbits/scraml/rest/user/userid/ContentApplicationVndV01JsonHeaderSegment.scala",
"io/atomicbits/scraml/rest/user/userid/ContentApplicationVndV10JsonHeaderSegment.scala",
"io/atomicbits/scraml/rest/user/upload/UploadResource.scala",
"io/atomicbits/scraml/rest/user/activate/ActivateResource.scala",
"io/atomicbits/scraml/rest/animals/AnimalsResource.scala",
"io/atomicbits/schema/User.scala",
"io/atomicbits/schema/UserDefinitionsAddress.scala",
"io/atomicbits/schema/Link.scala",
"io/atomicbits/schema/PagedList.scala",
"io/atomicbits/schema/Animal.scala",
"io/atomicbits/schema/AnimalImpl.scala",
"io/atomicbits/schema/Dog.scala",
"io/atomicbits/schema/Cat.scala",
"io/atomicbits/schema/Fish.scala",
"io/atomicbits/schema/Method.scala",
"io/atomicbits/schema/Geometry.scala",
"io/atomicbits/schema/GeometryImpl.scala",
"io/atomicbits/schema/Point.scala",
"io/atomicbits/schema/LineString.scala",
"io/atomicbits/schema/MultiPoint.scala",
"io/atomicbits/schema/MultiLineString.scala",
"io/atomicbits/schema/Polygon.scala",
"io/atomicbits/schema/MultiPolygon.scala",
"io/atomicbits/schema/GeometryCollection.scala",
"io/atomicbits/schema/Crs.scala",
"io/atomicbits/schema/NamedCrsProperty.scala",
"io/atomicbits/scraml/rest/user/void/VoidResource.scala",
"io/atomicbits/scraml/rest/user/void/location/LocationResource.scala",
"io/atomicbits/scraml/Book.scala",
"io/atomicbits/scraml/Author.scala",
"io/atomicbits/scraml/books/BooksResource.scala"
)
generatedFilePaths -- expectedFilePaths shouldBe Set.empty
expectedFilePaths -- generatedFilePaths shouldBe Set.empty
val geometryToClassName = CanonicalName.create("Geometry", List("io", "atomicbits", "schema"))
val bboxFieldClassPointer = generationAggr.toMap(geometryToClassName).fields.filter(_.fieldName == "bbox").head.classPointer
bboxFieldClassPointer shouldBe ListClassPointer(DoubleClassPointer(primitive = false))
}
Scenario("test generated Java DSL") {
Given("a RAML specification")
val apiLocation = "io/atomicbits/scraml/TestApi.raml"
When("we generate the RAMl specification into class representations")
implicit val platform = JavaJackson(List("io", "atomicbits", "scraml"))
val generationAggr: GenerationAggr =
ScramlGenerator
.buildGenerationAggr(
ramlApiPath = apiLocation,
apiClassName = "TestApi",
platform
)
.generate
Then("we should get valid class representations")
val generatedFilePaths =
generationAggr.sourceFilesGenerated
.map(_.filePath.toString)
.toSet
val expectedFilePaths = Set(
"io/atomicbits/scraml/TestApi.java",
"io/atomicbits/scraml/rest/RestResource.java",
"io/atomicbits/scraml/rest/user/UserResource.java",
"io/atomicbits/scraml/rest/user/userid/dogs/DogsResource.java",
"io/atomicbits/scraml/rest/user/userid/UseridResource.java",
"io/atomicbits/scraml/rest/user/userid/AcceptApplicationVndV01JsonHeaderSegment.java",
"io/atomicbits/scraml/rest/user/userid/AcceptApplicationVndV10JsonHeaderSegment.java",
"io/atomicbits/scraml/rest/user/userid/ContentApplicationVndV01JsonHeaderSegment.java",
"io/atomicbits/scraml/rest/user/userid/ContentApplicationVndV10JsonHeaderSegment.java",
"io/atomicbits/scraml/rest/user/upload/UploadResource.java",
"io/atomicbits/scraml/rest/user/activate/ActivateResource.java",
"io/atomicbits/scraml/rest/animals/AnimalsResource.java",
"io/atomicbits/schema/User.java",
"io/atomicbits/schema/UserDefinitionsAddress.java",
"io/atomicbits/schema/Link.java",
"io/atomicbits/schema/PagedList.java",
"io/atomicbits/schema/Animal.java",
"io/atomicbits/schema/Dog.java",
"io/atomicbits/schema/Cat.java",
"io/atomicbits/schema/Fish.java",
"io/atomicbits/schema/Method.java",
"io/atomicbits/schema/Geometry.java",
"io/atomicbits/schema/Point.java",
"io/atomicbits/schema/LineString.java",
"io/atomicbits/schema/MultiPoint.java",
"io/atomicbits/schema/MultiLineString.java",
"io/atomicbits/schema/Polygon.java",
"io/atomicbits/schema/MultiPolygon.java",
"io/atomicbits/schema/GeometryCollection.java",
"io/atomicbits/schema/Crs.java",
"io/atomicbits/schema/NamedCrsProperty.java",
"io/atomicbits/scraml/rest/user/voidesc/VoidResource.java",
"io/atomicbits/scraml/rest/user/voidesc/location/LocationResource.java",
"io/atomicbits/scraml/Book.java",
"io/atomicbits/scraml/Author.java",
"io/atomicbits/scraml/books/BooksResource.java"
)
generatedFilePaths -- expectedFilePaths shouldBe Set.empty
expectedFilePaths -- generatedFilePaths shouldBe Set.empty
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/ResourceTypes.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.{ KeyedList, ParseContext, RamlParseException }
import play.api.libs.json.{ JsArray, JsObject, JsValue }
import scala.util.{ Failure, Success, Try }
/**
* Created by peter on 25/05/17.
*/
case class ResourceTypes(resourceTypesMap: Map[String, JsObject]) extends ModelMerge {
def applyToResource[T](jsObject: JsObject)(f: JsObject => Try[T])(implicit parseContext: ParseContext): Try[T] = {
val appliedResourceTypes: MergeApplicationMap = findMergeNames(jsObject, ResourceTypes.selectionKey)
applyToForMergeNames(jsObject, appliedResourceTypes, resourceTypesMap, optionalTopLevelField = true).flatMap(f)
}
}
object ResourceTypes {
val selectionKey: String = "type"
def apply(): ResourceTypes = ResourceTypes(Map.empty[String, JsObject])
def apply(json: JsValue)(implicit parseContext: ParseContext): Try[ResourceTypes] = {
def doApply(rtJson: JsValue): Try[ResourceTypes] = {
rtJson match {
case rtJsObj: JsObject => Success(ResourceTypes(resourceTypesJsObjToResourceTypeMap(rtJsObj)))
case rtJsArr: JsArray => Success(ResourceTypes(resourceTypesJsObjToResourceTypeMap(KeyedList.toJsObject(rtJsArr))))
case x =>
Failure(
RamlParseException(s"The resourceTypes definition in ${parseContext.head} is malformed.")
)
}
}
def resourceTypesJsObjToResourceTypeMap(resourceTypesJsObj: JsObject): Map[String, JsObject] = {
resourceTypesJsObj.fields.collect {
case (key: String, value: JsObject) => key -> value
}.toMap
}
parseContext.withSourceAndUrlSegments(json)(doApply(json))
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/TypedQueryParams.scala | <filename>modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/TypedQueryParams.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
import play.api.libs.json._
import scala.language.postfixOps
/**
* Created by peter on 14/05/17.
*/
case class TypedQueryParams(params: Map[String, HttpParam] = Map.empty) {
def isEmpty: Boolean = params.isEmpty
}
object TypedQueryParams {
def create[T](value: T)(implicit formatter: Format[T]): TypedQueryParams = {
val json: JsValue = formatter.writes(value)
TypedQueryParams(HttpParam.toFormUrlEncoded(json))
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/ResourceTypesParseTest.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._
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 26/05/17.
*/
class ResourceTypesParseTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll {
Feature("test the application of resourceTypes in a RAML 1.0 model") {
Scenario("test the application of unparameterized resourceTypes in a RAML 1.0 model") {
Given("a RAML 1.0 specification with a resourceTypes definition")
val parser = RamlParser("/resourcetypes/zoo-api.raml", "UTF-8")
When("we parse the specification")
val parsedModel: Try[Raml] = parser.parse
Then("we get the expanded resources")
val raml = parsedModel.get
val zooResource: Resource = raml.resourceMap("zoo")
val zooAnimalsResource: Resource = zooResource.resourceMap("animals")
val zooAnimalGetAction: Action = zooAnimalsResource.actionMap(Get)
val zooAnimalGetResponse: Option[Response] = zooAnimalGetAction.responses.responseMap.get(StatusCode("200"))
val zooAnimalGetBodyContentOpt = zooAnimalGetResponse.get.body.contentMap.get(MediaType("application/json"))
zooAnimalGetBodyContentOpt should not be None
val zooAnimalPostActionOpt: Option[Action] = zooAnimalsResource.actionMap.get(Post)
zooAnimalPostActionOpt shouldBe None
val animalsResource: Resource = raml.resourceMap("animals")
val animalGetAction: Action = animalsResource.actionMap(Get)
val animalGetResponse: Option[Response] = animalGetAction.responses.responseMap.get(StatusCode("200"))
val animalGetBodyContentOpt = animalGetResponse.get.body.contentMap.get(MediaType("application/json"))
animalGetBodyContentOpt should not be None
val animalPostActionOpt: Option[Action] = animalsResource.actionMap.get(Post)
animalPostActionOpt should not be None
}
Scenario("test the application of parameterized resourceTypes in a RAML 1.0 model") {
Given("a RAML 1.0 specification with a parameterized resourceTypes definition")
val parser = RamlParser("/resourcetypes/zoo-api.raml", "UTF-8")
When("we parse the specification")
val parsedModel: Try[Raml] = parser.parse
Then("we get the expanded resources with all parameters filled in")
val raml = parsedModel.get
val zooKeepersResource: Resource = raml.resourceMap("zookeepers")
val zooKeepersGetAction: Action = zooKeepersResource.actionMap(Get)
val allQueryParameters = zooKeepersGetAction.queryParameters.values.map(_.name).toSet
allQueryParameters shouldBe Set("title", "digest_all_fields", "access_token", "numPages", "zookeepers")
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/ModelMerge.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 java.util.Locale
import io.atomicbits.scraml.ramlparser.parser.{ KeyedList, ParseContext, RamlParseException }
import play.api.libs.json._
import io.atomicbits.scraml.util.TryUtils._
import scala.language.postfixOps
import scala.util.matching.Regex
import scala.util.{ Failure, Try }
/**
* Created by peter on 25/05/17.
*/
trait ModelMerge {
val replaceStringPattern: Regex = """<<([^<>]*)>>""".r
def findMergeNames(jsObject: JsObject, selectionKey: String): MergeApplicationMap = {
(jsObject \ selectionKey).toOption
.collect {
case JsString(value) => Json.obj() + (value -> Json.obj())
case typesJsObj: JsObject => typesJsObj
case typesJsArr: JsArray => KeyedList.toJsObject(typesJsArr)
}
.map(MergeApplicationMap(_))
.getOrElse(MergeApplicationMap())
}
def applyToForMergeNames(jsObject: JsObject,
mergeApplicationMap: MergeApplicationMap,
mergeDeclaration: Map[String, JsObject],
optionalTopLevelField: Boolean = false)(implicit parseContext: ParseContext): Try[JsObject] = {
val toMerge: Try[Seq[JsObject]] =
accumulate(
mergeApplicationMap.map {
case (mergeName, mergeApplication) =>
Try(mergeDeclaration(mergeName))
.recoverWith {
case e => Failure(RamlParseException(s"Unknown trait or resourceType name $mergeName in ${parseContext.head}."))
}
.map { jsObj =>
applyMerge(jsObj, mergeApplication)
}
} toSeq
)
val deepMerged =
toMerge.map { mergeBlocks =>
mergeBlocks.foldLeft(jsObject) { (aggr, currentMergeBlock) =>
deepMerge(currentMergeBlock, aggr, optionalTopLevelField)
}
}
deepMerged
}
/**
* Deep merge of the source json object into the target json object according to the
* rules defined by
* https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/raml-10.md/#algorithm-of-merging-traits-and-methods
*
* Summarized: The target object's fields are NOT overwritten by the source fields. Object fields are recursively merged
* and array fields are merged by value.
*
* 1. Method node properties are inspected and those that are undefined in trait node remain unchanged.
* 2. The method node receives all properties of trait node (excluding optional ones), which are undefined in the method node.
* 3. Properties defined in both method node and trait node (including optional ones) are treated as follows:
* - Scalar properties remain unchanged.
* - Collection properties are merged by value, as described later.
* - Values of object properties are subjected to steps 1-3 of this procedure.
*
*/
protected def deepMerge(source: JsObject, target: JsObject, optionalTopLevelField: Boolean = false): JsObject = {
/**
* Deep merges the fieldWithValue into the aggr json object.
*/
def mergeFieldInto(aggregatedTarget: JsObject, fieldWithValue: (String, JsValue)): JsObject = {
val (field, value) = fieldWithValue
val (wasOptionalField, actualField) =
if (optionalTopLevelField && field.endsWith("?")) (true, field.dropRight(1))
else (false, field)
(aggregatedTarget \ actualField).toOption match {
case Some(aggrValue: JsObject) =>
value match {
case jsOb: JsObject => aggregatedTarget + (actualField -> deepMerge(jsOb, aggrValue))
case _ => aggregatedTarget
}
case Some(aggrValue: JsArray) =>
value match {
case jsArr: JsArray => aggregatedTarget + (actualField -> mergeArrays(jsArr, aggrValue))
case _ => aggregatedTarget
}
case Some(aggrValue) => aggregatedTarget
case None if wasOptionalField => aggregatedTarget
case None => aggregatedTarget + (actualField -> value)
}
}
/**
* Merges the source array into the target array by value.
*/
def mergeArrays(jsArrSource: JsArray, jsArrTarget: JsArray): JsArray = {
jsArrSource.value.foldLeft(jsArrTarget) { (aggr, sourceValue) =>
if (!aggr.value.contains(sourceValue)) aggr.+:(sourceValue)
else aggr
}
}
source.value.toMap.foldLeft(target)(mergeFieldInto)
}
private[model] def fetchReplaceStrings(text: String): Seq[ReplaceString] = {
replaceStringPattern
.findAllIn(text)
.matchData
.map { m =>
ReplaceString(m.matched, m.group(1), m.matched != text)
}
.toSeq
}
private def applyMerge(jsObject: JsObject, mergeApplication: MergeApplication)(implicit parseContext: ParseContext): JsObject = {
def mergeStringAsJsValue(text: String): JsValue = {
val replaceStrings: Seq[ReplaceString] = fetchReplaceStrings(text)
if (replaceStrings.size == 1 && !replaceStrings.head.partial) {
mergeApplication.get(replaceStrings.head.matchString) match {
case Some(jsValue) => jsValue
case None => sys.error(s"Did not find trait or resourceType replacement for value ${replaceStrings.head.matchString}.")
}
} else {
val replaced = mergeStringAsStringHelper(text, replaceStrings)
JsString(replaced)
}
}
def mergeStringAsString(text: String): String = {
val replaceStrings: Seq[ReplaceString] = fetchReplaceStrings(text)
mergeStringAsStringHelper(text, replaceStrings)
}
def mergeStringAsStringHelper(text: String, replaceStrings: Seq[ReplaceString]): String = {
replaceStrings.foldLeft(text) { (aggrText, replaceString) =>
val replacement: String =
mergeApplication.get(replaceString.matchString) match {
case Some(JsString(stringVal)) => stringVal
case Some(JsBoolean(booleanVal)) => booleanVal.toString
case Some(JsNumber(number)) => number.toString
case Some(jsValue) =>
sys.error(s"Cannot replace the following ${replaceString.matchString} value in a trait or resourceType: $jsValue")
case None => sys.error(s"Did not find trait or resourceType replacement for value ${replaceString.matchString}.")
}
val transformedReplacement = replaceString.transformReplacementString(replacement)
text.replaceAllLiterally(replaceString.toReplace, transformedReplacement)
}
}
def mergeJsObject(jsObject: JsObject): JsObject = {
val mergedFields =
jsObject.fields.map {
case (fieldName, jsValue) => (mergeStringAsString(fieldName), mergeJsValue(jsValue))
}
JsObject(mergedFields)
}
def mergeJsValue(jsValue: JsValue): JsValue =
jsValue match {
case jsObject: JsObject => mergeJsObject(jsObject)
case JsString(stringVal) => mergeStringAsJsValue(stringVal)
case JsArray(items) => JsArray(items.map(mergeJsValue))
case other => other
}
mergeJsObject(jsObject)
}
}
/**
* In:
*
* /books:
* type: { searchableCollection: { queryParamName: title, fallbackParamName: digest_all_fields } }
* get:
* is: [ secured: { tokenName: access_token }, paged: { maxPages: 10 } ]
*
* these are the MergeSubstitutions:
*
* MergeSubstitution(tokenName, access_token)
* MergeSubstitution(maxPages, 10)
*
* and the MergeApplications:
*
* MergeApplication(secured, ...)
* MergeApplication(paged, ...)
*
* @param name
* @param value
*/
case class MergeSubstitution(name: String, value: JsValue)
case class MergeApplication(name: String, substitutions: Seq[MergeSubstitution]) {
private val mergeDef: Map[String, JsValue] = substitutions.map(sub => (sub.name, sub.value)).toMap
def get(name: String)(implicit parseContext: ParseContext): Option[JsValue] = {
mergeDef
.get(name)
.orElse {
name match {
case "resourcePath" => Some(JsString(parseContext.resourcePath))
case "resourcePathName" => Some(JsString(parseContext.resourcePathName))
case other => None
}
}
}
def isEmpty: Boolean = substitutions.isEmpty
}
object MergeApplication {
def apply(name: String, jsObj: JsObject): MergeApplication = {
val substitutions =
jsObj.value.map {
case (nm, value) => MergeSubstitution(nm, value)
} toSeq
MergeApplication(name, substitutions)
}
}
case class MergeApplicationMap(mergeApplications: Seq[MergeApplication] = Seq.empty) {
val mergeMap: Map[String, MergeApplication] = mergeApplications.map(md => (md.name, md)).toMap
def get(name: String): Option[MergeApplication] = mergeMap.get(name)
def map[T](f: ((String, MergeApplication)) => T): Iterable[T] = mergeMap.map(f)
}
object MergeApplicationMap {
def apply(jsObj: JsObject): MergeApplicationMap = {
val mergeDefinitions =
jsObj.value.collect {
case (name, subst: JsObject) => MergeApplication(name, subst)
case (name, _) => MergeApplication(name, Json.obj())
} toSeq
MergeApplicationMap(mergeDefinitions)
}
}
sealed trait ReplaceOp {
def apply(text: String): String
}
object ReplaceOp {
def apply(opString: String): ReplaceOp =
opString match {
case "!singularize" => Singularize
case "!pluralize" => Pluralize
case "!uppercase" => Uppercase
case "!lowercase" => Lowercase
case "!lowercamelcase" => LowerCamelcase
case "!uppercamelcase" => UpperCamelcase
case "!lowerunderscorecase" => LowerUnderscorecase
case "!upperunderscorecase" => UpperUnderscorecase
case "!lowerhyphencase" => LowerHyphencase
case "!upperhyphencase" => UpperHyphencase
case unknown => NoOp
}
}
case object Singularize extends ReplaceOp {
def apply(text: String): String = {
if (text.endsWith("s")) text.dropRight(1)
else text
}
}
case object Pluralize extends ReplaceOp {
def apply(text: String): String = {
if (!text.endsWith("s")) s"${text}s"
else text
}
}
case object Uppercase extends ReplaceOp {
def apply(text: String): String = text.toUpperCase(Locale.US)
}
case object Lowercase extends ReplaceOp {
def apply(text: String): String = text.toLowerCase(Locale.US)
}
case object LowerCamelcase extends ReplaceOp {
def apply(text: String): String = {
val textChars = text.toCharArray
if (textChars.nonEmpty) {
textChars(0) = Character.toLowerCase(textChars(0))
new String(textChars)
} else {
""
}
}
}
case object UpperCamelcase extends ReplaceOp {
def apply(text: String): String = {
val textChars = text.toCharArray
if (textChars.nonEmpty) {
textChars(0) = Character.toUpperCase(textChars(0))
new String(textChars)
} else {
""
}
}
}
case object LowerUnderscorecase extends ReplaceOp {
def apply(text: String): String = {
val textChars = text.toCharArray
textChars.foldLeft("") { (txt, char) =>
if (char.isUpper && txt.nonEmpty) s"${txt}_${char.toLower}"
else s"$txt$char"
}
}
}
case object UpperUnderscorecase extends ReplaceOp {
def apply(text: String): String = {
val textChars = text.toCharArray
textChars.foldLeft("") { (txt, char) =>
if (char.isUpper && txt.nonEmpty) s"${txt}_$char"
else s"$txt${char.toUpper}"
}
}
}
case object LowerHyphencase extends ReplaceOp {
def apply(text: String): String = {
val textChars = text.toCharArray
textChars.foldLeft("") { (txt, char) =>
if (char.isUpper && txt.nonEmpty) s"$txt-${char.toLower}"
else s"$txt$char"
}
}
}
case object UpperHyphencase extends ReplaceOp {
def apply(text: String): String = {
val textChars = text.toCharArray
textChars.foldLeft("") { (txt, char) =>
if (char.isUpper && txt.nonEmpty) s"$txt-$char"
else s"$txt${char.toUpper}"
}
}
}
case object NoOp extends ReplaceOp {
def apply(text: String): String = text
}
case class ReplaceString(toReplace: String, matchString: String, operations: Seq[ReplaceOp], partial: Boolean) {
def transformReplacementString(replacement: String): String =
operations.foldLeft(replacement) { (repl, op) =>
op(repl)
}
}
case object ReplaceString {
def apply(toReplaceInput: String, matchStringWithOps: String, partial: Boolean): ReplaceString = {
val matchStringParts: Seq[String] = matchStringWithOps.split('|').toSeq.map(_.trim)
val (matchString, ops) =
if (matchStringParts.nonEmpty) (matchStringParts.head, matchStringParts.tail.map(ReplaceOp(_)))
else ("", Seq.empty[ReplaceOp])
ReplaceString(toReplace = toReplaceInput, matchString = matchString, operations = ops, partial = partial)
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Raml.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
import io.atomicbits.scraml.ramlparser.lookup._
import io.atomicbits.scraml.ramlparser.model.parsedtypes.Types
import io.atomicbits.scraml.ramlparser.parser.{ ParseContext, RamlParseException }
import io.atomicbits.scraml.util.TryUtils
import play.api.libs.json._
import scala.util.{ Failure, Success, Try }
import io.atomicbits.scraml.util.TryUtils._
/**
* Created by peter on 10/02/16.
*/
case class Raml(title: String,
mediaType: Option[MediaType],
description: Option[String],
version: Option[String],
baseUri: Option[String],
baseUriParameters: Parameters,
protocols: Option[Seq[String]],
traits: Traits,
types: Types,
resources: List[Resource]) {
def collectCanonicals(defaultBasePath: List[String]): (Raml, CanonicalLookup) = {
implicit val canonicalNameGenerator = CanonicalNameGenerator(defaultBasePath)
val canonicalTypeCollector = CanonicalTypeCollector(canonicalNameGenerator)
canonicalTypeCollector.collect(this)
}
lazy val resourceMap: Map[String, Resource] = resources.map(resource => resource.urlSegment -> resource).toMap
}
object Raml {
def apply(ramlJson: JsObject)(parseCtxt: ParseContext): Try[Raml] = {
val tryTraits: Try[Traits] =
(ramlJson \ "traits").toOption.map(Traits(_)(parseCtxt)).getOrElse(Success(Traits()))
val tryResourceTypes: Try[ResourceTypes] =
(ramlJson \ "resourceTypes").toOption.map(ResourceTypes(_)(parseCtxt)).getOrElse(Success(ResourceTypes()))
val mediaType: Try[Option[MediaType]] = {
(ramlJson \ "mediaType").toOption.collect {
case JsString(mType) => Success(Option(MediaType(mType)))
case x => Failure(RamlParseException(s"The mediaType in ${parseCtxt.sourceTrail} must be a string value."))
} getOrElse Success(None)
}
implicit val parseContext: ParseContext = {
val tryParseCtxt =
for {
resourceTypes <- tryResourceTypes
traits <- tryTraits
defaultMediaType <- mediaType
} yield parseCtxt.copy(resourceTypes = resourceTypes, traits = traits, defaultMediaType = defaultMediaType)
tryParseCtxt match {
case Success(ctxt) => ctxt
case Failure(exc) => sys.error(s"Parse error: ${exc.getMessage}.")
}
}
val title: Try[String] =
(ramlJson \ "title").toOption.collect {
case JsString(t) => Success(t)
case x =>
Failure(RamlParseException(s"File ${parseCtxt.sourceTrail} has a title field that is not a string value."))
} getOrElse Failure(RamlParseException(s"File ${parseCtxt.sourceTrail} does not contain the mandatory title field."))
val types: Try[Types] = {
List((ramlJson \ "types").toOption, (ramlJson \ "schemas").toOption).flatten match {
case List(ts, ss) =>
Failure(
RamlParseException(
s"File ${parseCtxt.sourceTrail} contains both a 'types' and a 'schemas' field. You should only use a 'types' field."
)
)
case List(t) => Types(t)
case Nil => Success(Types())
}
}
val description: Try[Option[String]] = {
(ramlJson \ "description").toOption.collect {
case JsString(docu) => Success(Option(docu))
case x =>
Failure(RamlParseException(s"The description field in ${parseCtxt.sourceTrail} must be a string value."))
} getOrElse Success(None)
}
val protocols: Try[Option[Seq[String]]] = {
def toProtocolString(protocolString: JsValue): Try[String] = {
protocolString match {
case JsString(pString) if pString.toUpperCase == "HTTP" => Success("HTTP")
case JsString(pString) if pString.toUpperCase == "HTTPS" => Success("HTTPS")
case JsString(pString) =>
Failure(RamlParseException(s"The protocols in ${parseCtxt.sourceTrail} should be either HTTP or HTTPS."))
case x =>
Failure(RamlParseException(s"At least one of the protocols in ${parseCtxt.sourceTrail} is not a string value."))
}
}
(ramlJson \ "protocols").toOption.collect {
case JsArray(pcols) => TryUtils.accumulate(pcols.toSeq.map(toProtocolString)).map(Some(_))
case x =>
Failure(RamlParseException(s"The protocols field in ${parseCtxt.sourceTrail} must be an array of string values."))
}.getOrElse(Success(None))
}
val version: Try[Option[String]] = {
(ramlJson \ "version").toOption.collect {
case JsString(v) => Success(Option(v))
case JsNumber(v) => Success(Option(v.toString()))
case x =>
Failure(RamlParseException(s"The version field in ${parseCtxt.sourceTrail} must be a string or a number value."))
}.getOrElse(Success(None))
}
val baseUri: Try[Option[String]] = {
(ramlJson \ "baseUri").toOption.collect {
case JsString(v) => Success(Option(v))
case x =>
Failure(RamlParseException(s"The baseUri field in ${parseCtxt.sourceTrail} must be a string value."))
}.getOrElse(Success(None))
}
val baseUriParameters: Try[Parameters] = Parameters((ramlJson \ "baseUriParameters").toOption)
/**
* According to the specs on https://github.com/raml-org/raml-spec/blob/raml-10/versions/raml-10/raml-10.md#scalar-type-specialization
*
* "The resources of the API, identified as relative URIs that begin with a slash (/). Every property whose key begins with a
* slash (/), and is either at the root of the API definition or is the child property of a resource property, is a resource
* property, e.g.: /users, /{groupId}, etc."
*
*/
val resources: Try[List[Resource]] = {
val resourceFields: List[Try[Resource]] =
ramlJson.fieldSet.collect {
case (field, jsObject: JsObject) if field.startsWith("/") => Resource(field, jsObject)
}.toList
TryUtils.accumulate(resourceFields).map(_.toList).map(unparallellizeResources(_, None))
}
// val resourceTypes: Try[]
// val annotationTypes: Try[]
/**
* title
* traits
* types (schemas - deprecated)
* mediaType
* description
* protocols
* version
* baseUri
* baseUriParameters
*
* resourceTypes
* annotationTypes
* securedBy
* securitySchemes
* documentation
* uses
*/
withSuccess(
title,
mediaType,
description,
version,
baseUri,
baseUriParameters,
protocols,
tryTraits,
types,
resources
)(Raml(_, _, _, _, _, _, _, _, _, _))
}
private def unparallellizeResources(resources: List[Resource], parent: Option[Resource] = None): List[Resource] = {
// Merge all actions and subresources of all resources that have the same (urlSegment, urlParameter)
def mergeResources(resources: List[Resource]): Resource = {
resources.reduce { (resourceA, resourceB) =>
val descriptionChoice = List(resourceA.description, resourceB.description).flatten.headOption
val displayNameChoice = List(resourceA.displayName, resourceB.displayName).flatten.headOption
resourceA.copy(
description = descriptionChoice,
displayName = displayNameChoice,
actions = resourceA.actions ++ resourceB.actions,
resources = resourceA.resources ++ resourceB.resources
)
}
}
// All children with empty URL segment
def absorbChildrenWithEmptyUrlSegment(resource: Resource): Resource = {
val (emptyUrlChildren, realChildren) = resource.resources.partition(_.urlSegment.isEmpty)
val resourceWithRealChildren = resource.copy(resources = realChildren)
mergeResources(resourceWithRealChildren :: emptyUrlChildren)
}
// Group all resources at this level with the same urlSegment and urlParameter
val groupedResources: List[List[Resource]] = resources.groupBy(_.urlSegment).values.toList
val mergedResources: List[Resource] = groupedResources.map(mergeResources)
val resourcesWithAbsorbedChildren = mergedResources.map(absorbChildrenWithEmptyUrlSegment)
resourcesWithAbsorbedChildren.map { mergedAndAbsorbedResource =>
mergedAndAbsorbedResource.copy(
resources = unparallellizeResources(
resources = mergedAndAbsorbedResource.resources,
parent = Some(mergedAndAbsorbedResource)
)
)
}
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/IdTest.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.{ RelativeId, RootId }
import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen }
import org.scalatest.featurespec.AnyFeatureSpec
import org.scalatest.matchers.should.Matchers._
/**
* Created by peter on 14/02/17.
*/
class IdTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll {
Feature("RootId parsing") {
Scenario("test parsing a RootId") {
Given("a RootId string ")
val rootIdString = "http://atomicbits.io/model/home-address.json"
When("we parse the RootId string")
val rootId = RootId(rootIdString)
Then("we get all four actions in the userid resource")
rootId shouldBe RootId(hostPath = List("atomicbits", "io"), path = List("model"), name = "home-address")
}
Scenario("test parsing a less obvious RootId") {
Given("a RootId string ")
val rootIdString = "https://atomicbits.io/home-address.myfile#"
When("we parse the RootId string")
val rootId = RootId(rootIdString)
Then("we get all four actions in the userid resource")
rootId shouldBe RootId(hostPath = List("atomicbits", "io"), path = List(), name = "home-address")
}
}
Feature("RelativeId parsing") {
Scenario("test parsing a relative id") {
Given("relative id strings")
val relativeIdString01 = "some/path/file.json"
val relativeIdString02 = "/some/path/file.json"
val relativeIdString03 = "/some/path/file"
val relativeIdString04 = "book"
When("we parse the relative ids")
val relativeId01 = RelativeId(relativeIdString01)
val relativeId02 = RelativeId(relativeIdString02)
val relativeId03 = RelativeId(relativeIdString03)
val relativeId04 = RelativeId(relativeIdString04)
Then("the relative ids must have the expected parts")
relativeId01.path shouldBe List("some", "path")
relativeId01.name shouldBe "file"
relativeId02.path shouldBe List("some", "path")
relativeId02.name shouldBe "file"
relativeId03.path shouldBe List("some", "path")
relativeId03.name shouldBe "file"
relativeId04.path shouldBe List()
relativeId04.name shouldBe "book"
}
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/Response.scala | <filename>modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/Response.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
import play.api.libs.json.JsValue
/**
* Created by peter on 21/05/15, Atomic BITS (http://atomicbits.io).
*/
case class Response[T](status: Int,
stringBody: Option[String],
jsonBody: Option[JsValue] = None,
body: Option[T] = None,
headers: Map[String, List[String]] = Map.empty) {
def map[S](f: T => S) = {
this.copy(body = body.map(f))
}
def flatMap[S](f: T => Option[S]) = {
this.copy(body = body.flatMap(f))
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/platform/typescript/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.typescript
import io.atomicbits.scraml.generator.codegen.GenerationAggr
import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform, SourceGenerator }
import io.atomicbits.scraml.generator.typemodel.EnumDefinition
import io.atomicbits.scraml.ramlparser.parser.SourceFile
import Platform._
/**
* Created by peter on 15/12/17.
*/
case class EnumGenerator(typeScript: TypeScript) extends SourceGenerator {
implicit val platform: TypeScript = typeScript
def generate(generationAggr: GenerationAggr, enumDefinition: EnumDefinition): GenerationAggr = {
val enumName = enumDefinition.reference.name
val enumValues = enumDefinition.values.map(CleanNameTools.quoteString)
val source =
s"""
|export type ${enumName} = ${enumValues.mkString(" | ")}
""".stripMargin
val sourceFile =
SourceFile(
filePath = enumDefinition.classReference.toFilePath,
content = source
)
generationAggr.addSourceFile(sourceFile)
}
}
|
atomicbits/scramlgen | modules/scraml-gen-simulation/src/test/scala/io/atomicbits/scraml/client/manual/PathparamResource.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 io.atomicbits.scraml.dsl.scalaplay._
import play.api.libs.json.JsValue
/**
* Created by peter on 17/08/15.
*/
class PathparamResource(_value: String, private val _req: RequestBuilder) extends ParamSegment[String](_value, _req) {
def withHeaders(newHeaders: (String, String)*) =
new PathparamResource(_value, _requestBuilder.withAddedHeaders(newHeaders: _*))
def get(queryparX: Double, queryparY: Int, queryParZ: Option[Int] = None) = new TypeMethodSegment[String, User](
method = Get,
queryParams = Map(
"queryparX" -> Option(queryparX).map(SimpleHttpParam.create(_)),
"queryparY" -> Option(queryparY).map(SimpleHttpParam.create(_)),
"queryParZ" -> queryParZ.map(SimpleHttpParam.create(_))
),
queryString = None,
expectedAcceptHeader = Some("application/json"),
req = _requestBuilder
)
def put(body: String) =
new TypeMethodSegment[String, Address](
method = Put,
theBody = Some(body),
expectedAcceptHeader = Some("application/json"),
expectedContentTypeHeader = Some("application/json"),
req = _requestBuilder
)
def put(body: JsValue) =
new TypeMethodSegment[JsValue, Address](
method = Put,
theBody = Some(body),
expectedAcceptHeader = Some("application/json"),
expectedContentTypeHeader = Some("application/json"),
req = _requestBuilder
)
def put(body: User) =
new TypeMethodSegment[User, Address](method = Put,
theBody = Some(body),
expectedAcceptHeader = Some("application/json"),
expectedContentTypeHeader = Some("application/json"),
req = _requestBuilder)
def post(formparX: Int, formParY: Double, formParZ: Option[String]) =
new TypeMethodSegment(
method = Post,
theBody = None,
formParams = Map(
"formparX" -> Option(formparX).map(SimpleHttpParam.create(_)),
"formParY" -> Option(formParY).map(SimpleHttpParam.create(_)),
"formParZ" -> formParZ.map(SimpleHttpParam.create(_))
),
multipartParams = List.empty,
expectedAcceptHeader = Some("application/json"),
expectedContentTypeHeader = Some("application/json"),
req = _requestBuilder
)
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/TypesIncludeTest.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.{ NativeId, Raml }
import io.atomicbits.scraml.ramlparser.model.parsedtypes.{ ParsedObject, ParsedString, ParsedTypeReference }
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 5/03/18.
*/
class TypesIncludeTest extends AnyFeatureSpec with GivenWhenThen with BeforeAndAfterAll {
Scenario("test the inclusion of types at the top level types definition") {
Given("a RAML 1.0 specification with types inclusion")
val parser = RamlParser("/typesinclude/types-include-api.raml", "UTF-8")
When("we parse the specification")
val parsedModel: Try[Raml] = parser.parse
Then("we get the included types")
val raml = parsedModel.get
val bookType = raml.types(NativeId("Book")).asInstanceOf[ParsedObject]
val authorType = raml.types(NativeId("Author")).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.")
}
}
}
|
atomicbits/scramlgen | modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/typemodel/ClientClassDefinition.scala | <reponame>atomicbits/scramlgen<filename>modules/scraml-generator/src/main/scala/io/atomicbits/scraml/generator/typemodel/ClientClassDefinition.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.typemodel
import io.atomicbits.scraml.generator.platform.{ CleanNameTools, Platform }
/**
* Created by peter on 13/01/17.
*
* In a client class definition, we collect all information that is needed to generate a client class, independent from
* the target language.
*/
case class ClientClassDefinition(apiName: String,
baseUri: Option[String],
basePackage: List[String],
topLevelResourceDefinitions: List[ResourceClassDefinition],
title: String = "",
version: String = "",
description: String = "") // ToDo: insert title, version and description from the RAML model
extends SourceDefinition {
override def classReference(implicit platform: Platform): ClassReference = {
val apiClassName = CleanNameTools.cleanClassNameFromFileName(apiName)
ClassReference(name = apiClassName, packageParts = basePackage)
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/test/scala/io/atomicbits/scraml/ramlparser/NativeClassHierarchyTest.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.parser.RamlParser
import org.scalatest.{ BeforeAndAfterAll, GivenWhenThen }
import org.scalatest.featurespec.AnyFeatureSpec
import org.scalatest.matchers.should.Matchers._
/**
* Created by peter on 11/02/17.
*/
class NativeClassHierarchyTest 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("/nativeclasshierarchy/NativeClassHierarchyTest.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)
canonicalLookup
}
}
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/Client.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
import io.atomicbits.scraml.dsl.scalaplay.client.ClientConfig
import play.api.libs.json._
import scala.concurrent.Future
/**
* Created by peter on 21/05/15, Atomic BITS (http://atomicbits.io).
*/
trait Client extends AutoCloseable {
def config: ClientConfig
def defaultHeaders: Map[String, String]
def callToStringResponse(request: RequestBuilder, body: Option[String]): Future[Response[String]]
def callToJsonResponse(requestBuilder: RequestBuilder, body: Option[String]): Future[Response[JsValue]]
def callToTypeResponse[R](request: RequestBuilder, body: Option[String])(implicit responseFormat: Format[R]): Future[Response[R]]
def callToBinaryResponse(request: RequestBuilder, body: Option[String]): Future[Response[BinaryData]]
def close(): Unit
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Parameters.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.ParsedType
import io.atomicbits.scraml.ramlparser.parser.ParseContext
import io.atomicbits.scraml.util.TryUtils._
import play.api.libs.json.{ JsObject, JsValue }
import scala.language.postfixOps
import scala.util.{ Success, Try }
case class Parameters(valueMap: Map[String, Parameter] = Map.empty) {
def nonEmpty: Boolean = valueMap.nonEmpty
def byName(name: String): Option[Parameter] = valueMap.get(name)
val values: List[Parameter] = valueMap.values.toList
val isEmpty = valueMap.isEmpty
def mapValues(fn: Parameter => Parameter): Parameters = copy(valueMap = valueMap.mapValues(fn).toMap)
}
/**
* Created by peter on 26/08/16.
*/
object Parameters {
def apply(jsValueOpt: Option[JsValue])(implicit parseContext: ParseContext): Try[Parameters] = {
/**
* @param name The name of the parameter
* @return A pair whose first element is de actual parameter name and the second element indicates whether or not the
* parameter is an optional parameter. None (no indication for optional is given) Some(false) (it is an optional parameter).
*/
def detectRequiredParameterName(name: String): (String, Option[Boolean]) = {
if (name.length > 1 && name.endsWith("?")) (name.dropRight(1), Some(false))
else (name, None)
}
def jsObjectToParameters(jsObject: JsObject): Try[Parameters] = {
val valueMap: Map[String, Try[Parameter]] =
jsObject.value.collect {
case (name, ParsedType(tryType)) =>
val (actualName, requiredProp) = detectRequiredParameterName(name)
actualName -> tryType.map { paramType =>
Parameter(
name = actualName,
parameterType = TypeRepresentation(paramType),
required = requiredProp.getOrElse(paramType.required.getOrElse(true)) // paramType.defaultRequiredValue
)
}
} toMap
accumulate(valueMap).map(vm => Parameters(vm))
}
jsValueOpt.collect {
case jsObj: JsObject => jsObjectToParameters(jsObj)
} getOrElse Success(Parameters())
}
}
|
atomicbits/scramlgen | modules/scraml-raml-parser/src/main/scala/io/atomicbits/scraml/ramlparser/model/Method.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
/**
* Created by peter on 10/02/16.
*/
sealed trait Method {
def action: String
}
object Method {
def unapply(action: String): Option[Method] = {
action match {
case Get.action => Some(Get)
case Post.action => Some(Post)
case Put.action => Some(Put)
case Delete.action => Some(Delete)
case Head.action => Some(Head)
case Patch.action => Some(Patch)
case Options.action => Some(Options)
case Trace.action => Some(Trace)
case _ => None
}
}
}
case object Get extends Method {
val action = "get"
}
case object Post extends Method {
val action = "post"
}
case object Put extends Method {
val action = "put"
}
case object Delete extends Method {
val action = "delete"
}
case object Head extends Method {
val action = "head"
}
case object Patch extends Method {
val action = "patch"
}
case object Options extends Method {
val action = "options"
}
case object Trace extends Method {
val action = "trace"
}
|
atomicbits/scramlgen | modules/scraml-dsl-scala/src/main/scala/io/atomicbits/scraml/dsl/scalaplay/BinaryRequest.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
import _root_.java.io.{ InputStream, File }
/**
* Created by peter on 15/01/16.
*/
/**
* The Binary Request object is an internal type of the DSL and is not directly visible for the user.
*/
sealed trait BinaryRequest
case class FileBinaryRequest(file: File) extends BinaryRequest
case class InputStreamBinaryRequest(inputStream: InputStream) extends BinaryRequest
case class ByteArrayBinaryRequest(byteArray: Array[Byte]) extends BinaryRequest
case class StringBinaryRequest(text: String) extends BinaryRequest
object BinaryRequest {
def apply(file: File): BinaryRequest = FileBinaryRequest(file)
def apply(inputStream: InputStream): BinaryRequest = InputStreamBinaryRequest(inputStream)
def apply(byteArray: Array[Byte]): BinaryRequest = ByteArrayBinaryRequest(byteArray)
def apply(text: String): BinaryRequest = StringBinaryRequest(text)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.