How to generate swagger.json [duplicate] - spring-mvc

This question already has answers here:
How to export swagger.json (or yaml)
(7 answers)
Closed 3 years ago.
I am using java spring boot framework to create REST api for my project and I am using "springfox-swagger2 and springfox-swagger-ui" for generating swagger documentation. I am able to see my documentation using the URL http://localhost:8080/swagger-ui.html.
How can I create or generate swagger.json / spec.json, The documentation should not be with this application, we are using a separate application for listing the API docs.

You can get the url with your swagger-ui html page:
GET http://localhost:8080/v2/api-docs?group=App
And actually you can get all the urls with chrome/firefox develop tools network feature.

If you use Maven, you can generate client and server side documentation (yaml, json and html) by using swagger-maven-plugin
Add this to your pom.xml:
.....
<plugin>
<groupId>com.github.kongchen</groupId>
<artifactId>swagger-maven-plugin</artifactId>
<version>3.0.1</version>
<configuration>
<apiSources>
<apiSource>
<springmvc>true</springmvc>
<locations>com.yourcontrollers.package.v1</locations>
<schemes>http,https</schemes>
<host>localhost:8080</host>
<basePath>/api-doc</basePath>
<info>
<title>Your API name</title>
<version>v1</version>
<description> description of your API</description>
<termsOfService>
http://www.yourterms.com
</termsOfService>
<contact>
<email>your-email#email.com</email>
<name>Your Name</name>
<url>http://www.contact-url.com</url>
</contact>
<license>
<url>http://www.licence-url.com</url>
<name>Commercial</name>
</license>
</info>
<!-- Support classpath or file absolute path here.
1) classpath e.g: "classpath:/markdown.hbs", "classpath:/templates/hello.html"
2) file e.g: "${basedir}/src/main/resources/markdown.hbs",
"${basedir}/src/main/resources/template/hello.html" -->
<templatePath>${basedir}/templates/strapdown.html.hbs</templatePath>
<outputPath>${basedir}/generated/document.html</outputPath>
<swaggerDirectory>generated/swagger-ui</swaggerDirectory>
<securityDefinitions>
<securityDefinition>
<name>basicAuth</name>
<type>basic</type>
</securityDefinition>
</securityDefinitions>
</apiSource>
</apiSources>
</configuration>
</plugin>
........
You can download *.hbs template at this address:
https://github.com/kongchen/swagger-maven-example
Execute mvn swagger:generate
JSon documentation will be generated at your project /generated/swagger/ directory.
Past it on this address :
http://editor.swagger.io
And generate what ever you want ( Server side or Client side API in your preferred technology )

I'm a little late here, but I just figured out that you can open your browser console and find the URL to the GET request that returns the JSON definition for your Swagger docs. The following technique worked for me when mapping my API to AWS API Gateway.
To do this:
Navigate to your Swagger docs endpoint
Open the browser console
Refresh the page
Navigate to the network tab and filter by XHR requests
Right click on the XHR request that ends in ?format=openapi
You can now just copy and paste that into a new JSON file!

I have done this with a small trick
I have added the following code in the end of my home controller test case
import org.springframework.boot.test.web.client.TestRestTemplate;
public class HomeControllerTest extends .... ...... {
#Autowired
private TestRestTemplate restTemplate;
#Test
public void testHome() throws Exception {
//.......
//... my home controller test code
//.....
String swagger = this.restTemplate.getForObject("/v2/api-docs", String.class);
this.writeFile("spec.json", swagger );
}
public void writeFile(String fileName, String content) {
File theDir = new File("swagger");
if (!theDir.exists()) {
try{
theDir.mkdir();
}
catch(SecurityException se){ }
}
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter("swagger/"+fileName);
bw = new BufferedWriter(fw);
bw.write(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
I don't know this is right way or not But it is working :)
Dependency
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>

You should be able to get your swagger.json at
http://localhost:8080/api-docs
assuming your don't have kept the versioning as in the pet store sample application. In that case the URL would be:
http://localhost:8080/v2/api-docs

To get the api json definition for REST API, if swagger is configured properly. you can use directly swagger/docs/v1, this means the complete url will be, if version v1 (or just specify the version)
http://localhost:8080/swagger/docs/v1

Related

App Insights not using RequestTelemetryFilter for health check Controller in Spring Boot app

I have a Spring Boot app with a few Controllers I want to track their dependencies (including outbound Http requests). That all works as expected. However, I have one controller for a health check (returning 204) that I do not want telemetry for. All other responses mention custom code components, but according to the documentation, this should be doable within the AI-Agent.xml config.
<BuiltInProcessors>
<Processor type="RequestTelemetryFilter">
<Add name="NotNeededResponseCodes" value="204" />
</Processor>
</BuiltInProcessors>
I notice on the classpath that there are two RequestTelemtryFilter instances (one from ai-core and one from ai-web, neither of which get hit when i debug).
Configuring the Agent (via AI-Agent.xml) is different than configuring custom telemetry (via Applicationinsights.xml). Spring boot + the agent requires the use of a custom Telemetry Processor and pulling into your configuration via #Bean. No additional XML in the AI-Agent is necessary.
public class HealthCheckTelemetryFilter implements TelemetryProcessor
{
public HealthCheckTelemetryFilter()
{
// TODO Auto-generated constructor stub
}
#Override
public boolean process(Telemetry telemetry)
{
RequestTelemetry reqTel = (RequestTelemetry) telemetry;
if(reqTel.getResponseCode().equals(HttpStatus.NO_CONTENT.toString()))
return false;
else
return true;
}
}
NOTE: dont forget appropriate type check

Error Connect Database Sqlite in Mule Connector

I want to connect and select database Sqlite on Mule AnypointStudio. But it error. Please help me. Thanks all.
No suitable driver found for jdbc:sqlite
here my code:
#Processor (name="select" ,friendlyName ="select")
public void select() {
ArrayList<Story> list = new ArrayList<Story>();
String sql = "select * from chat";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
// loop through the result set
while (rs.next()) {
Story s = new Story();
s.setStory(rs.getInt("id"), rs.getString("user_chat"),rs.getString("bot_chat"));
list.add(s);
}
} catch (SQLException | ClassNotFoundException e) {
System.out.println(e.getMessage());
}
for (int i =0 ; i < list.size(); i++){
System.out.print(list.get(i).GetID() +"| "+ list.get(i).GetUserChat() + "| "+ list.get(i).GetBotChat() +"\n" );
}
}
private Connection connect() throws ClassNotFoundException {
// SQLite connection string
Class.forName("org.sqlite.JDBC");
String url = "jdbc:sqlite:C:\\data.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
}
Make sure You have valid jar/driver in your project classpath.
Open new Mule Project in Studio, and then follow these steps to add/create a datasource in mule flow:
a. Import the driver
b. Create a Datasource,
c. Create a Connector that uses our Datasource, and finally
d. Create a simple flow that uses our connector.
It seems you are missing driver jar in project classpath.
How to Import the Driver?
Once you have the jar file(you can download jar respective to sqllite from some repo ,eg- maven_repo), the next steps are very simple:
In the Package Explorer,
Right-click over the Project folder
Look in the menu for Build Path > Add External Archives…
Look for the jar file in your hard drive and click Open.
Now you should see in the package explorer that the jar file is present in “Referenced Libraries.”
This will allow you to create an insta
nce of the Object driver you will need.
It's probably a classpath issue. If you are using Maven with your project, simply add the dependency in your pom.xml (and right click on your project > Mule > Update project dependencies):
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.20.1</version>
<scope>test</scope>
</dependency>
Make sure you understand how Maven works and how to manipulate your pom.xml file. Maven getting started and POM Introduction might help.
If you are not using Maven, you need to manually import the dependency in your classpath. #Malesh_Loya answer should help.

Swagger not giving UI for Spring MVC Project

I am new to the Swagger and trying to implement it in the Spring MVC. I'm using latest dependency swagger-springmvc from http://mvnrepository.com/artifact/com.mangofactory/swagger-springmvc. So based on link https://dzone.com/articles/documenting-your-spring-api. I added following configuration in mvc-config.xml.
<!-- Serve static content - required for Swagger -->
<mvc:default-servlet-handler/>
<!-- to enable the default documentation controller-->
<context:component-scan base-package="com.mangofactory.swagger.controllers"/>
<!-- to pick up the bundled spring configuration-->
<context:component-scan base-package="com.mangofactory.swagger.configuration"/>
<!-- Direct static mappings -->
<mvc:resources mapping="*.html" location="/, classpath:/swagger-ui"/>
Also I used following from link shown above.
<bean class="com.xxx.xx.xx.SwaggerConfig"/>
Then I added
git clone https://github.com/wordnik/swagger-ui
cp -r swagger-ui/dist ~/dev/x-auth-security/src/main/webapps/docs
When I launch the site: http://localhost:8080/dp-rest/api-docs I don't see UI format, it only gives JSON format.
{"apiVersion":"1.0","swaggerVersion":"1.2","apis":[{"path":"/default/student-service","description":"Manage Student Service","position":0},{"path":"/default/student-service","description":"Manage Student Service","position":0}],"authorizations":[],"info":{"title":"Student API's","description":"API for Student ","termsOfServiceUrl":"terms.html","contact":"test#yahoo.com","license":"Commercial Proprietary","licenseUrl":"http://www.adbc.com"}}
Ny
#Configuration
#EnableSwagger
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
#Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
#Bean
// Don't forget the #Bean annotation
public SwaggerSpringMvcPlugin customImplementation() {
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(
apiInfo()).includePatterns(".*");
}
private ApiInfo apiInfo() {
return new ApiInfo("Student API", "API for Student",
"term.html", "test#tahoo.com",
"Commercial Proprietary", "http://www.test.com");
}
}
Why UI format not coming when we launch the http://localhost:8080/sample-rest/api-docs site?
Then only I see raw JSON response not any ui, What is missing here? What I need to changed/add/modify my code?
According to the article you'll see a section that tells you where to find the documentation. I'm not sure if you're using spring-boot but...
After making these changes, I was able to open fire up the app with "mvn spring-boot:run" and view http://localhost:8080/docs/index.html in my browser.
In any case, swagger-springmvc is now called springfox and supports the latest swagger specification (2.0). There is also documentation available to help you get started. I would recommend using the latest version (2.3.1 as of this writing) of springfox instead.

Spring MVC Processing multipart form data

Using Craig Walls book "Spring in Action, 4th Edition", 7.2. Processing multipart form data
The code does not run no matter what path you try. I even tried
C:\something. Don't you have to create the directory first?
When I run the code, I get the error below:
root cause org.springframework.web.multipart.MultipartException:
Could not parse multipart servlet request; nested exception is
java.io.IOException: The temporary upload location
[C:\Users\jokra_000\sts-bundle\pivotal-tc-server-developer-3.1.1.RELEASE\base-instance\work\Catalina\localhost\spittr\tmp\spittr\uploads]
is not valid
Has anyone successfully uploaded an image file as outlined in Chapter 7? It seems there's far more to it than what's described, as the code Craig supplied does not run. Instead it crashes and will not upload a file.
Any suggestions on how to implement MultipartFile and the Path?
Craig's suggestion:
in AbstractAnnotationConfigDispatcherServletInitializer:
#Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(
new MultipartConfigElement("/tmp/spittr/uploads", 2097152, 4194304, 0));
}
in Controller processRegistration:
MultipartFile profilePicture = spitterForm.getProfilePicture();
profilePicture.transferTo(new File("/tmp/spittr/" + spitter.getUsername() + ".jpg"));
It worked when I did the following:
I changed MultipartResolver:
#Bean
public MultipartResolver multipartResolver() throws IOException {
return new CommonsMultipartResolver();
}
and also added the dependency:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
and then imported to the file that extends WebMvcConfigurerAdapter:
import org.apache.commons.fileupload.FileItemFactory;

How to implement Dart with Spring MVC and Thymeleaf?

I'm currently trying to implement Dart in an existing project which uses Spring MVC (4.0.0) and Thymeleaf (2.1.1) as template engine.
Currently I am deploying all my Dart resources to /dart as shown belown.
<link rel="import" th:href="#{/dart/wb-control-text.html}" />
<script type="application/dart" th:src="#{/dart/packages/polymer/init.dart}"></script>
<script th:src="#{/dart/packages/browser/dart.js}"></script>
Thymeleaf rewrites the urls to http://localhost:8080/context/dart/..., which is correct.
Dart works really great if you open a HTML file directly which has the packages folder directly beneath it. However, this is not the case in my project, which has friendly urls like /action/users/browse and you don't have access directly to the HTML file.
When a Dart library tries to import a package, I get a 404 error because it is looking for it in the wrong place (e.g. /dart/packages/polymer/packages/polymer/polymer.dart).
Do I need to provide a URL request handler or a filter that handles all **/packages/** requests (and just use paths relative to the current url)? Or is there an option in Dart where you can set where it should look for packages?
What is the solution (or workaround) for this?
Edit
I currently have a temporary solution that works, but it is dirty and I'm still looking for a cleaner solution.
I added the packages to my classpath and I created a DartPackagesFilter that streams the resources:
public class DartPackagesFilter extends OncePerRequestFilter
#Override
protected void doFilterInternal(final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain filterChain)
throws ServletException, IOException {
final String uri = request.getRequestURI();
final int index = uri.indexOf("/packages/");
if ( index != -1 ){
final String resourceName = uri.substring(index);
writeResourceToResponse(response, resourceName);
return;
}
filterChain.doFilter(request, response);
}
private void writeResourceToResponse(final HttpServletResponse response, final String resourceName) throws IOException {
final ClassPathResource resource = new ClassPathResource(resourceName);
response.setContentType(resolveContentType(resourceName));
ChannelUtils.stream(resource.getInputStream(), response.getOutputStream());
}
private String resolveContentType(final String resourceName){
if ( resourceName.endsWith("dart") ){
return "application/dart";
} else if ( resourceName.endsWith("js")){
return "text/javascript";
}
throw new IllegalArgumentException("Resource must be a Dart or Javascript file!");
}
}
In web.xml:
<filter-mapping>
<filter-name>DartPackagesFilter</filter-name>
<url-pattern>*.dart</url-pattern>
<url-pattern>*.js</url-pattern>
</filter-mapping>
In my HTML file I refer to the packages relatively to the current URL:
<script src="packages/browser/dart.js"></script>
You will need to handle /packages/ requests separately, like your work-around. However, these hacks would only be needed for development when you are working with the actual .dart files.
When you deploy your app, you'll use either dart2js, dart2dart or, most likely, both. These tools produce a monolithic script file which does not rely on the external packages directory.
Since you only need the /packages/ directory for development, it is possible to set the the packages URL through a flag in Dartium. However, in my experience, this is an awkward solution since the flag applies to all Dart applications -- all Dart apps would need to fetch packages through the same URL scheme. It also makes it difficult to share your app with other Dartium installations.

Resources