Make Kotlin models Serializable using swagger codegen - kotlin

I am trying to generate my API logic using swagger codegen. However, I need to implement java.io.Serializable for the generated models.
I tried to add the following:
"serializeModel": true
to the config.json file, which didn't do anything.
My generated models come out like this:
package dms.models
/**
*
* #param id
* #param name
*/
data class GetCompanyResponse (
val id: kotlin.Int? = null,
val name: kotlin.String? = null
) {
}
But I need them to be like this:
package dms.models
import java.io.Serializable
/**
*
* #param id
* #param name
*/
data class GetCompanyResponse (
val id: kotlin.Int? = null,
val name: kotlin.String? = null
): Serializable {
}
My config.json looks like this:
{
"modelPackage": "dms.models",
"apiPackage": "dms.api",
"serializableModel": true
}
And the script I call to generate looks like this:
swagger-codegen generate -i $SWAGGER_URL -l $CLIENT -o $OUT_DIR -D modelDocs=$MODEL_DOCS -D apiTests=$API_TESTS -D apiDocs=$API_DOCS --config config.json
Does anyone know what I need to change in order for this to work?
I am using swagger codegen v3.0.25

Related

MapStruct Property has no write accessor in MetaData for target name

I have a FlatDTO that needs to be mapped to a nested Response containing InfoData and MetaData
The code for the response is generated by OpenAPI. So the below definitions can't be changed.
package org.mapstruct.example.kotlin.openapi
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.Valid
data class Response(
#field:Valid #field:JsonProperty("infoData", required = true) val infoData: InfoData,
#field:Valid #field:JsonProperty("metaData", required = true) val metaData: MetaData
)
data class InfoData(
#field:JsonProperty("id", required = true) val id: kotlin.String,
)
data class MetaData(
#field:JsonProperty("firstProperty") val firstProperty: String? = null,
)
I have defined FlatDTO as follows.
package org.mapstruct.example.kotlin.models
data class FlatDTO(
var id: String? = null,
var firstProperty: String,
)
Here is my mapper class which maps FlatDTO to Response
package org.mapstruct.example.kotlin.mapper
import org.mapstruct.Mapper
import org.mapstruct.Mapping
import org.mapstruct.Mappings
import org.mapstruct.example.kotlin.models.FlatDTO
import org.mapstruct.example.kotlin.openapi.Response
#Mapper
interface DataMapper {
#Mappings(
Mapping(target = "infoData.id", source = "id"),
Mapping(target = "metaData.firstProperty", source = "firstProperty")
)
fun flatToResponse(flatDTO: FlatDTO): Response
}
When I try to build the code using mvn clean install
I get the following error.
error: Property "firstProperty" has no write accessor in MetaData for target name "metaData.firstProperty".
[ERROR] #org.mapstruct.Mappings(value = {#org.mapstruct.Mapping(target = "infoData.id", source = "id"), #org.mapstruct.Mapping(target = "metaData.firstProperty", source = "firstProperty")})
I understand that this message is trying to say that there is no setter function for firstProperty because it's defined as val but that code cannot be edited. I can write my own custom mapper that works just fine.
I wanted to understand if there is a way to use MapStruct in this scenario.

How to traverse through a Json in Karate

I am trying to have a Karate test where I need to traverse through a json to get the required test data.
I have the below json.
{
"dev":{
"scenario1":{
"data":"data1"
},
"scenario2":{
"data":"data2"
}
},
"qa":{
"scenario1":{
"data":"data1"
},
"scenario2":{
"data":"data2"
}
}
}
Below is my feature file.
Background:
* def env = dev
Scenario:
* Given url someurl
* def inputData = testdata.env.scenario1.data
* And request { input: '#(inputData)'}
* When method post
* Then status 200
I need the test data that matches the value env that I have defined above.
How can I set the json path to my input data. Basically, the json path should take the value from a variable I have defined previously.
For this you don't even need Json-Path, just JS will do:
* def data = { foo: 1, bar: 2 }
* def env = 'bar'
* def res = data[env]
* match res == 2
Also see: https://stackoverflow.com/a/59162760/143475
You can also do dynamic Json-Path, see: https://stackoverflow.com/a/50855425/143475

API Platform and custom POST operation with custom body

I hope I'm right to ask this. I've looked at (almost) all similar concern but I ain't satisfied yet.
I'm working on a User entity and for days (weeks actually) now i'm trying to POST a user with a custom body. Here's some part of my entity User :
/**
* #ApiResource(
* normalizationContext={"groups"={"read"}},
* denormalizationContext={"groups"={"write"}},
* itemOperations={
* "get",
* "put",
* "delete",
* "get_active_user"={
* "method"="GET",
* "path"="/users/active/me",
* "controller"=UserReadAction::class,
* "defaults"={"_api_receive"=false},
* "swagger_context"={
* "parameters"={
*
* }
* }
* },
* },
* collectionOperations={
* "change_password"={
* "method"="POST",
* "path"="/users/active/changepassword",
* "controller"=UserChangePasswordAction::class,
* "normalization_context"={"groups"={"afup"}},
* "defaults"={"_api_receive"=false},
* "swagger_context"={
* "summary" = "Change user password",
* "parameters"={
* {
* "name" = "User",
* "in" = "body",
* "schema" = {
* "type" = "object",
* "properties" = {
* "password" = {"type"="string"},
* "nom" = {"type"="string"},
* }
* },
* "required" = "true",
* }
* },
* }
* }
* }
* )
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
* #ORM\Table(name="users")
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
* #Groups({"read", "write", "afup"})
*/
private $id;
Here is the controller:
namespace App\Controller\SDK;
use App\Entity\User;
use App\Service\SDK\UserService;
use Symfony\Component\Security\Core\Security;
class UserChangePasswordAction
{
public function __invoke(User $data)
{
var_dump($data);die;
}
}
And the services.yaml (some part) file
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller/*'
tags: ['controller.service_arguments']
When I try this (see var_dump in controller), i get an error saying:
Cannot autowire argument $data of "App\Controller\SDK\UserChangePasswordAction()": it references class "App\Entity\User" no such service exists
I read the official doc and it seems that the _invoke method should automatically retrieve the entity. But it does not work for me.
Notice: I also defined a custom item operation "get_active_user" and it works fine.
Please I would like to understand :
what I did wrong,
how it actually works,
Thank you.
EDIT:
In the collectionOperation definition, i removed the following setting which means that we manually want to handle data (User) retrieval :
"defaults"={"_api_receive"=false},
Now, the controller returns an empty User entity, not an error. I still can't get the submitted data.
The edit of my question fix the concern. Actually, I just needed to remove this annotation from the POST opration definition :')
"defaults"={"_api_receive"=false},
Now, when I submit the data, I get them as on the following image :
This annotation is important when you write custom GET operation.
It is not working because that is a CollectionOperation. In this case, you can get the user through TokenStorageInterface
namespace App\Controller\SDK;
use App\Entity\User;
use App\Service\SDK\UserService;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class UserChangePasswordAction
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function __invoke(Request $request) //Get request if you want o keep args empty
{
var_dump($this->tokenStorage->getToken()->getUser());die;
}
}

How to call a specific function from JS file to feature file in karate [duplicate]

I need to perform two operations on the result of JSON responses.so can we have those different operations inside single JS file? or do we need to have mapping like one JS file for one operation.
Please help on this
I don't recommend trying to create complicated JavaScript in Karate, it just leads to maintainability issues. If you really want an object with multiple utility methods on it, write a Java class with static methods, and it will be much easier to maintain / debug.
That said, if you really insist - look at this answer: https://stackoverflow.com/a/47002604/143475
But this is what I recommend for most projects. In one "common" feature file, define multiple methods like this:
Scenario:
* def now = function(){ return java.lang.System.currentTimeMillis() }
* def uuid = function(){ return java.util.UUID.randomUUID() + '' }
You can now call this feature like this:
* call read('common.feature')
And now all the functions in that feature are available for use:
* def time = now()
* def id = uuid()
#kmancusi This is how I did a common.feature file with my common functions and then the following my.test.feature shows how I import that to use it in another feature.
common.feature
#ignore
Feature:
Scenario:
* def now =
"""
function() {
return java.lang.System.currentTimeMillis()
}
"""
* def uuid =
"""
function() {
return java.util.UUID.randomUUID() + ''
}
"""
my.test.feature
Feature: my tests
Background:
* configure logPrettyRequest = true
* configure logPrettyResponse = true
* configure ssl = true
Scenario: basic test
* def util = call read('common.feature')
* def sessionId = util.uuid()
* print sessionId

Is it possible to have multiple JS functions inside one JS file of karate framework?

I need to perform two operations on the result of JSON responses.so can we have those different operations inside single JS file? or do we need to have mapping like one JS file for one operation.
Please help on this
I don't recommend trying to create complicated JavaScript in Karate, it just leads to maintainability issues. If you really want an object with multiple utility methods on it, write a Java class with static methods, and it will be much easier to maintain / debug.
That said, if you really insist - look at this answer: https://stackoverflow.com/a/47002604/143475
But this is what I recommend for most projects. In one "common" feature file, define multiple methods like this:
Scenario:
* def now = function(){ return java.lang.System.currentTimeMillis() }
* def uuid = function(){ return java.util.UUID.randomUUID() + '' }
You can now call this feature like this:
* call read('common.feature')
And now all the functions in that feature are available for use:
* def time = now()
* def id = uuid()
#kmancusi This is how I did a common.feature file with my common functions and then the following my.test.feature shows how I import that to use it in another feature.
common.feature
#ignore
Feature:
Scenario:
* def now =
"""
function() {
return java.lang.System.currentTimeMillis()
}
"""
* def uuid =
"""
function() {
return java.util.UUID.randomUUID() + ''
}
"""
my.test.feature
Feature: my tests
Background:
* configure logPrettyRequest = true
* configure logPrettyResponse = true
* configure ssl = true
Scenario: basic test
* def util = call read('common.feature')
* def sessionId = util.uuid()
* print sessionId