Openapi-generator spring: How to replace #RequestMapping("${openapi.someproject.base-path:/v1}") - openapi-generator

I'm importing a jar file containing the RestResources generated with openapi-codegen.
#Controller
#RequestMapping({"${openapi.someproject.base-path:/v1}"}) // <-- ${openapi.someproject.base-path:/v1} should be replaced by /v1
public class ApiApiController implements ApiApi {
private final ApiApiDelegate delegate;
public ApiApiController(#Autowired(required = false) ApiApiDelegate delegate) {
this.delegate = (ApiApiDelegate)Optional.ofNullable(delegate).orElse(new ApiApiDelegate() {
});
}
public ApiApiDelegate getDelegate() {
return this.delegate;
}
}
When deploying my application is see an endpoint named "${openapi.someproject.base-path:/v1}". How can I configure this to be "/v1".
I tried to put the following the application.yml of the using project:
openapi:
someproject:
base-path: ""
The imported jar was generated as follows with the openapi-generator-maven-plugin:
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<id>back-end-swagger</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${project.basedir}/src/main/resources/swagger/api.yml</inputSpec>
<generatorName>spring</generatorName>
<apiPackage>com.test.api</apiPackage>
<modelPackage>com.test.api.model</modelPackage> <supportingFilesToGenerate>ApiUtil.java</supportingFilesToGenerate>
<validateSpec>true</validateSpec>
<configOptions>
<delegatePattern>true</delegatePattern>
</configOptions>
</configuration>
</execution>
The api.yml file looks as follows:
swagger: "2.0"
info:
version: "1.0.0"
title: "someproject"
host: "somehost.io"
basePath: "/v1"
tags:
- name: "endpoint"
schemes:
- "https"
- "http"
paths:
/api/test:
get:
produces:
- "application/json"
responses:
200:
description: OK

Related

Custom 404 page on Azure App Service Linux asp.net core webapp

Like the long title say:
how can I redirect all the non-existing requests to a /404 page?
I try the web.config solution, the routes.json and/or the staticwebapp.config.json solution, both in /site/wwwroot folder (where dll and exe are) and in /site/wwwroot/wwwroot, but without success.
It is an Asp,net core razor Pages webapp, .net core 6, deployed on App Service Linux
Thanks
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/404" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
</configuration>
{
"responseOverrides": {
"404": {
"rewrite": "/404"
}
},
"platformErrorOverrides": [
{
"errorType": "NotFound",
"serve": "/404"
}
]
}
To add custom Error page in ASP.Net Core Web App, please check the below workaround.
In Program.cs file , add UseStatusCodePagesWithReExecute middleware to generate the unique error page.
My Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
else
{
app.UseStatusCodePagesWithReExecute("/Error/{0}");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Add a new Controller, name it as HandleErrorController and add a view with name Error.cshtml.
My HandleErrorController.cs
using Microsoft.AspNetCore.Mvc;
namespace CustomErrorPage.Controllers
{
public class HandleErrorController : Controller
{
[Route("Error/{statusCode}")]
public IActionResult StatusCodeHandler(int StatusCode)
{
switch (StatusCode)
{
case 404:
ViewBag.StatusErrorMessage = "Sorry, the requested resource is not available";
break;
}
return View("Error");
}
}
}
My Error.cshtml
#{
ViewBag.Title = "Not Found";
}
<h1>#ViewBag.StatusErrorMessage</h1>
<a asp-action="index" asp-controller="home">
Navigate to the home page
</a>
Re-Deploy the WebApp.
Navigate to Azure portal => Your Web App => Configuration => Application Settings, add the below Environment variable
ASPNETCORE_ENVIRONMENT
Output:
Thanks to KudVenkat for the clear Explaination

JMS Serializer Annotation Group not working on Entity using Symfony 4

I have been using the Group annotation for years on SF2 and SF3.
I'm trying SF4.1. And I'm getting an empty JSON when I send a GET to my endpoint.
The interesting parts of my composer.json:
"friendsofsymfony/rest-bundle": "^2.3",
"jms/serializer-bundle": "^2.3",
"sensio/framework-extra-bundle": "^5.1",
"symfony/serializer-pack": "^1.0"
The config:
framework:
serializer:
enabled: true
enable_annotations: true
sensio_framework_extra:
view: { annotations: true }
fos_rest:
routing_loader:
default_format: json
view:
view_response_listener: 'force'
format_listener:
rules:
- { path: ^/, prefer_extension: true, fallback_format: json, priorities: [ json,xml, html ] }
The Entity
use JMS\Serializer\Annotation\Groups;
class User implements UserInterface, \Serializable
{
private $id;
/**
* #Groups({"api"})
*/
private $username;
And the endpoint API Controller:
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
class UserController extends FOSRestController {
public function getUserAction(Request $request, EntityManagerInterface $em)
{
$user = $em->getReference('App:User', 1);
$view = View::create();
$context = new Context();
$context->setGroups(['api']);
$view->setContext($context);
$view->setData($user);
return $this->handleView($view);
}
}
If I remove `$context->setGroups(['api']), the JSON has all the User attributes.
Any idea? Thanks!
Debug Info:
bin/console debug:container jms
Select one of the following services to display its information [fos_rest.serializer.jms]:
[0] fos_rest.serializer.jms
0
Information for Service "fos_rest.serializer.jms"
=================================================
Option Value
Service ID fos_rest.serializer.jms
Class FOS\RestBundle\Serializer\JMSSerializerAdapter
Tags -
Public no
Synthetic no
Lazy yes
Shared yes
Abstract no
Autowired no
Autoconfigured no
By default FOSRest prefers the JMSSerializer if it is installed. So first check if the service defined by the JMSSerializerBundle is defined:
./bin/console debug:container jms_serializer.serializer
If this command displays an error message (ServiceNotFound) then the bundle is not correctly installed. Check the config/bundles.php and add the following line if it's missing:
JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true],
If it actually is installed, you can check the fos_rest configuration, if it maybe changes the serializer service. You can configure it like that:
fos_rest:
service:
serializer: "fos_rest.serializer.jms"

Service Container Alias only for a certain environment

Symfony 2.8.7 I have a simple alias definition in my services.yml:
h4cc_alice_fixtures:
alias: h4cc_alice_fixtures.manager
This works perfectly in DEV because in my AppKernel h4cc is registered:
public function registerBundles()
{
$bundles = [
//...
];
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new h4cc\AliceFixturesBundle\h4ccAliceFixturesBundle();
}
return $bundles;
}
In PROD now I get an dependency injection error because of course h4cc_alice_fixtures.manager cannot be resolved.
I want to have h4ccAliceFixturesBundle only in DEV and TEST but currently I have only one services.yml.
Is there a way to define the alias only for DEV and TEST?
UPDATE:
As there is something like:
my_service:
class: Acme\AcmeBundle\Services\MyService
arguments: [ '#tenant_user_service', '#?debug.stopwatch' ]
which is only injecting Stopwatch when App is in debug-mode...
I thought there might be existing something similar for Alias, too.
You can have separate services.yml similar what you have already with your routing_dev.yml. In the imports section of your config_dev.yml and config_test.yml you can replace the existing line:
imports:
- { resource: config.yml }
with following entry:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services_dev.yml }
like you have it in your global config.yml already. Just add your suffix to the files.

Cannot load resource "." after writing in routing.yml

I made a command that automatically writes in routing.yml.
My problem is that when I try to browse one of the routes
api:
resource: "."
type: "api"
prefix: /api
I get this exception
Cannot load resource "."
I tried to add a cache:clear to my command but I get the same exception.
I added a cache warmup that runs after the command termination that way Symfony dumps routes into generated code .
class TerminateListener {
public function onConsoleTerminate(ConsoleTerminateEvent $event) {
if ($event->getCommand()->getName() == ('my:command')) {
$app = new Application();
$cache_clear_command = $event->getCommand()->getApplication()->find('cache:warmup');
$cache_clear_command->setApplication($app);
$event->getOutput()->setVerbosity('VERBOSITY_QUIET');
$cache_clear_command->run($event->getInput(), $event->getOutput());
}
}
}
services:
warmup.listener:
class:TerminateListener
tags:
- { name: kernel.event_listener, event: console.terminate , method: onConsoleTerminate }

Symfony 2: Injecting logger for specific channel/handler to services

I am working on a Symfony 2 web app and I would like to inject a Monolog logger using a specific channel to a service:
The Config:
monolog:
handlers:
main:
type: stream
path: %kernel.root_dir%/%kernel.environment%.log
level: error
#channels: [!alert]
alert:
type: stream
path: %kernel.root_dir%/%kernel.environment%.alert.log
level: info
channels: [alert]
Service Config:
services:
some_service:
class: Some\Service
arguments: [#logger]
tags:
- { name: monolog.logger, channel: alert }
The Service:
class SomeService {
protected $logger;
public function __construct($logger) {
$this->logger = $logger;
$this->logger->info('Log this!');
}
The prod.log file:
[2016-03-28 11:25:47] alert.INFO: Log this!
The Problem: Although I specifically inject the logger using the alert channel, the message is handled by the main handler. Thus the messages are logged into the prod.log file instead of the prod.alert.log file.
When I leave the line channels: [!alert] as comment, the message is logged to prod.log. When I activate this line by removing the comment, the message is not logged at all (main handler ignores the channel correctly).
What have I to to, in order to use a specific handler to target a specific log file, mailer, etc? Messages to alert channel should be handled by the alert handler while all other handlers are ignored.
Use special service created for Monolog handler:
services:
some_service:
class: Namespace\Some\Service
arguments: ["#monolog.logger.alert"]

Resources