<commit_before>/* Copyright 2015 UniCredit S.p.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.unicredit.swagger.generators

import treehugger.forest._
import definitions._
import treehuggerDSL._
import eu.unicredit.swagger.StringUtils._

import io.swagger.parser.SwaggerParser
import io.swagger.models._
import io.swagger.models.parameters._
import scala.collection.JavaConversions._

class DefaultServerGenerator extends ServerGenerator with SharedServerClientCode {

  def controllerNameFromFileName(fn: String) =
    objectNameFromFileName(fn, "Controller")

  override def generateRoutes(fileName: String, packageName: String): Option[String] = {
    val swagger = new SwaggerParser().read(fileName)

    val basePath = Option(swagger.getBasePath).getOrElse("/")

    val completePaths =
      swagger.getPaths.keySet().toSeq

    def composeRoutes(p: String): Seq[String] = {
      val path = swagger.getPath(p)
      if (path == null) return Seq()

      val ops: Map[String, Operation] =
        Seq(Option(path.getDelete) map ("DELETE" -> _),
            Option(path.getGet) map ("GET" -> _),
            Option(path.getPost) map ("POST" -> _),
            Option(path.getPut) map ("PUT" -> _)).flatten.toMap

      val controllerName =
        packageName + ".controller" + "." + controllerNameFromFileName(fileName)

      (for {
        op <- ops
      } yield {

        val url =
          doUrl(basePath, p)

        val methodName =
          op._2.getOperationId

        def genMethodCall(className: String, methodName: String, params: Seq[Parameter]): String = {
          val p = getMethodParamas(params).map {
            case (n, v) => s"$n: ${treeToString(v.tpt)}"
          }
          // since it is a route definition, this is not Scala code, so we generate it manually
          s"$className.$methodName" + p.mkString("(", ", ", ")")
        }

        val methodCall =
          genMethodCall(controllerName, methodName, op._2.getParameters)

        s"${padTo(8, op._1)}            ${padTo(50, url)}          ${padTo(20, methodCall)}"
      }).toSeq
    }

    val routes =
      completePaths.flatMap(composeRoutes)

    if (routes.nonEmpty) Some(routes.mkString("\n\n", "\n\n", "\n"))
    else None
  }

  def generateImports(packageName: String, codeProvidedPackage: String, controllerName: String): Seq[Tree] =
    Seq(
      IMPORT(packageName, "_"),
      IMPORT(packageName + ".json", "_"),
      IMPORT("play.api.mvc.Results", "_"),
      IMPORT("play.api.mvc", "_"),
      IMPORT("play.api.libs.json", "_"),
      IMPORT(codeProvidedPackage, controllerName + "Impl")
    )

  def generate(fileName: String, packageName: String, codeProvidedPackage: String): Iterable[SyntaxString] = {
    val swagger = new SwaggerParser().read(fileName)

    val controllerPackageName =
      packageName + ".controller"

    val controllerName =
      controllerNameFromFileName(fileName)

    val completePaths =
      swagger.getPaths.keySet().toSeq

    def composeController(p: String): Seq[Tree] = {
      val path = swagger.getPath(p)
      if (path == null) return Seq()

      val ops: Seq[Operation] =
        Seq(Option(path.getDelete), Option(path.getGet), Option(path.getPost), Option(path.getPut)).flatten

      for {
        op <- ops
      } yield {

        try if (!op.getProduces.forall(_ == "application/json"))
          println("WARNING - only 'application/json' is supported")
        catch {
          case _: Throwable =>
        }

        val methodName =
          op.getOperationId

        val okRespType =
          respType(op.getResponses.get)
            .find(x => x._2 ne null)
            .map(x =>
              x._1 ->
                Option(x._2.getSchema).map(y => noOptPropType(y)))

        val methodCall =
          genControllerMethod(methodName, op.getParameters, okRespType.get)

        if (okRespType.isEmpty)
          throw new Exception(s"cannot determine Ok result type for $methodName")

        methodCall
      }<commit_msg>bugfix: Option.get was called before the isEmpty check<commit_after>/* Copyright 2015 UniCredit S.p.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.unicredit.swagger.generators

import treehugger.forest._
import definitions._
import treehuggerDSL._
import eu.unicredit.swagger.StringUtils._

import io.swagger.parser.SwaggerParser
import io.swagger.models._
import io.swagger.models.parameters._
import scala.collection.JavaConversions._

class DefaultServerGenerator extends ServerGenerator with SharedServerClientCode {

  def controllerNameFromFileName(fn: String) =
    objectNameFromFileName(fn, "Controller")

  override def generateRoutes(fileName: String, packageName: String): Option[String] = {
    val swagger = new SwaggerParser().read(fileName)

    val basePath = Option(swagger.getBasePath).getOrElse("/")

    val completePaths =
      swagger.getPaths.keySet().toSeq

    def composeRoutes(p: String): Seq[String] = {
      val path = swagger.getPath(p)
      if (path == null) return Seq()

      val ops: Map[String, Operation] =
        Seq(Option(path.getDelete) map ("DELETE" -> _),
            Option(path.getGet) map ("GET" -> _),
            Option(path.getPost) map ("POST" -> _),
            Option(path.getPut) map ("PUT" -> _)).flatten.toMap

      val controllerName =
        packageName + ".controller" + "." + controllerNameFromFileName(fileName)

      (for {
        op <- ops
      } yield {

        val url =
          doUrl(basePath, p)

        val methodName =
          op._2.getOperationId

        def genMethodCall(className: String, methodName: String, params: Seq[Parameter]): String = {
          val p = getMethodParamas(params).map {
            case (n, v) => s"$n: ${treeToString(v.tpt)}"
          }
          // since it is a route definition, this is not Scala code, so we generate it manually
          s"$className.$methodName" + p.mkString("(", ", ", ")")
        }

        val methodCall =
          genMethodCall(controllerName, methodName, op._2.getParameters)

        s"${padTo(8, op._1)}            ${padTo(50, url)}          ${padTo(20, methodCall)}"
      }).toSeq
    }

    val routes =
      completePaths.flatMap(composeRoutes)

    if (routes.nonEmpty) Some(routes.mkString("\n\n", "\n\n", "\n"))
    else None
  }

  def generateImports(packageName: String, codeProvidedPackage: String, controllerName: String): Seq[Tree] =
    Seq(
      IMPORT(packageName, "_"),
      IMPORT(packageName + ".json", "_"),
      IMPORT("play.api.mvc.Results", "_"),
      IMPORT("play.api.mvc", "_"),
      IMPORT("play.api.libs.json", "_"),
      IMPORT(codeProvidedPackage, controllerName + "Impl")
    )

  def generate(fileName: String, packageName: String, codeProvidedPackage: String): Iterable[SyntaxString] = {
    val swagger = new SwaggerParser().read(fileName)

    val controllerPackageName =
      packageName + ".controller"

    val controllerName =
      controllerNameFromFileName(fileName)

    val completePaths =
      swagger.getPaths.keySet().toSeq

    def composeController(p: String): Seq[Tree] = {
      val path = swagger.getPath(p)
      if (path == null) return Seq()

      val ops: Seq[Operation] =
        Seq(Option(path.getDelete), Option(path.getGet), Option(path.getPost), Option(path.getPut)).flatten

      for {
        op <- ops
      } yield {

        try if (!op.getProduces.forall(_ == "application/json"))
          println("WARNING - only 'application/json' is supported")
        catch {
          case _: Throwable =>
        }

        val methodName =
          op.getOperationId

        val okRespType =
          respType(op.getResponses.get)
            .find(x => x._2 ne null)
            .map(x =>
              x._1 ->
                Option(x._2.getSchema).map(y => noOptPropType(y)))

        if (okRespType.isEmpty)
          throw new Exception(s"cannot determine Ok result type for $methodName")

        val methodCall =
          genControllerMethod(methodName, op.getParameters, okRespType.get)

        methodCall
      }
{'fraction_non_alphanumeric': 0.11806089919753765, 'fraction_numerical': 0.004177201275145652, 'mean_word_length': 2.7089278434569914, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6275384', 'n_tokens_mistral': 2717, 'n_tokens_neox': 2625, 'n_words': 679}