Generate Swagger UI through Grizzly and Jersey Application.

Statement : Generate Swagger UI for the listing of all the REST APIs through Grizzly and Jersey Application.

  • Add following dependency in pom.xml –

<dependency>

<groupId>io.swagger</groupId>

<artifactId>swagger-jersey2-jaxrs</artifactId>

<version>1.5.9</version>

</dependency>

  • Bundle Swagger UI and docs folder through you main application class using the below code –

package com.main;

import java.io.IOException;

import java.net.URI;

import org.glassfish.grizzly.http.server.CLStaticHttpHandler;

import org.glassfish.grizzly.http.server.HttpServer;

import org.glassfish.grizzly.http.server.ServerConfiguration;

import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;

import org.glassfish.jersey.jackson.JacksonFeature;

import org.glassfish.jersey.server.ResourceConfig;

import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;

import io.swagger.jaxrs.config.BeanConfig;

public class MainApp {

// Base URI the Grizzly HTTP server will listen on

public static final URI BASE_URI = URI.create(http://0.0.0.0:8080&#8221;);

public static HttpServer getLookupServer() {

String resources = “com.main”;

BeanConfig beanConfig = new BeanConfig();

beanConfig.setVersion(“1.0.1”);

beanConfig.setSchemes(new String[] { “http” });

beanConfig.setBasePath(“”);

beanConfig.setResourcePackage(resources);

beanConfig.setScan(true);

final ResourceConfig resourceConfig = new ResourceConfig();

resourceConfig.packages(resources);

resourceConfig.register(io.swagger.jaxrs.listing.ApiListingResource.class);

resourceConfig.register(io.swagger.jaxrs.listing.SwaggerSerializers.class);

resourceConfig.register(JacksonFeature.class);

resourceConfig.register(JacksonJsonProvider.class);

return GrizzlyHttpServerFactory.createHttpServer(BASE_URI, resourceConfig);

}

public static void main(String[] args) throws IOException {

final HttpServer server = getLookupServer();

server.start();

ClassLoader loader = MainApp.class.getClassLoader();

CLStaticHttpHandler docsHandler = new CLStaticHttpHandler(loader, “swagger-ui/”);

docsHandler.setFileCacheEnabled(false);

ServerConfiguration cfg = server.getServerConfiguration();

cfg.addHttpHandler(docsHandler, “/docs/”);

}

}

  • Take the latest code of swagger-ui. Copy all the content of the dist folder and create a folder named  swagger-ui inside src/main/resources and paste all the copied contents. Now change the url in index.file which is inside the copied folder like below –

    url: http://0.0.0.0:8080/swagger.json

  • Lastly, annotate your controller with @Api and @ApiOperation.

Hope it works. Now to run your Grizzly Jersey Application, go to browser and type localhost:8080/docs/. You will see Swagger UI having all the details of your REST APIs.

Happy coding and sharing as well. 🙂 You can find the git repo for the above implementation.

Generate Swagger UI through Spring Boot Application.

Statement : Generate Swagger UI for the listing of all the REST APIs through Spring Boot Application.

Follow the below steps to generate the Swagger UI  through Spring Boot application –

  1. Add following dependency in pom.xml –

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.6.1</version>

</dependency>

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>2.6.1</version>

</dependency>

  1.  Add the following piece of code in your main application class having the @EnableSwagger2 annotation.

@EnableSwagger2

@SpringBootApplication

public class MyApp {

public static void main(String[] args) {

SpringApplication.run(MyApp.class, args);

}

@Bean

  public Docket api() {

    return new Docket(DocumentationType.SWAGGER_2).select()

        .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)).paths(PathSelectors.any()).build()

        .pathMapping(“/”).apiInfo(apiInfo()).useDefaultResponseMessages(false);

  }

  @Bean

  public ApiInfo apiInfo() {

    final ApiInfoBuilder builder = new ApiInfoBuilder();

    builder.title(“My Application API through Swagger UI”).version(“1.0”).license(“(C) Copyright Test”)

        .description(“List of all the APIs of My Application App through Swagger UI”);

    return builder.build();

  }

}

  1. Add the below RootController class in your code to redirect to the Swagger UI page. In this way, you don’t need to put the dist folder of Swagger-UI in your  resources directory.

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

@Controller

@RequestMapping(“/”)

public class RootController {

@RequestMapping(method = RequestMethod.GET)

public String swaggerUi() {

return “redirect:/swagger-ui.html”;

}

}

  1. Being a final steps, add the @Api and @ApiOperation notation in all your RESTControllers like below –

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import org.springframework.http.HttpStatus;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseStatus;

import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

@RestController

@RequestMapping(“/hello”)

@Api(value = “hello”, description = “Sample hello world application”)

public class TestController {

@ApiOperation(value = “Just to test the sample test api of My App Service”)

@RequestMapping(method = RequestMethod.GET, value = “/test”)

// @Produces(MediaType.APPLICATION_JSON)

public String test() {

return “Hello to check Swagger UI”;

}

@ResponseStatus(HttpStatus.OK)

@RequestMapping(value = “/test1”, method = GET)

@ApiOperation(value = “My App Service get test1 API”, position = 1)

public String test1() {

System.out.println(“Testing”);

if (true) {

return “Tanuj”;

}

return “Gupta”;

}

}

Now your are done. Now to run your Spring Boot Application, go to browser and type localhost:8080. You will see Swagger UI having all the details of your REST APIs.

Happy Coding 🙂 Enjoy the source code of the above implementation in my git repo.

Continue reading “Generate Swagger UI through Spring Boot Application.”

Git – Permission denied (publickey) Error while cloning the repo on Windows.

The above error comes when either you haven’t made any SSH keys on your local machine or those keys are expired. So to solve this, Please follow the below steps –

  1. Open git bash.
  2. Type cd ~/.ssh. This will take you to the root directory for Git (Likely C:\Users\[YOUR-USER-NAME]\.ssh\ on Windows)
  3. Within the .ssh folder, there should be these two files: id_rsa and id_rsa.pub.
  4. Copy the content of id_rsa.pub with no extra spaces or lines and paste it into GitHub under the Account Settings > SSH Keys. You can name as per your convenience.
  5. Now git clone or git pull should work.

In case the above files are not created, you can use the below command to do so –

cd ~/.ssh && ssh-keygen

Now follow all the above mentioned steps. Hope it will solve your problem.

Stuck in verifying while installing pkg file on MAC

  1. Go to finder. Click on Go and then Go to Folder and type /System/Library/CoreServices/Installer.app. Then invoke the installer.app
  2. Now you just need to go to the location where .pkg file exists and that was stuck in verifying.
  3. Select the file to open and now you will be able to run the installer easily.

It saved my day. Hope it helps for you as well. 🙂

Kill process/port on MAC machine in case of java.net.BindException: Address already in use

  • First try netstat –
    netstat -vanp tcp | grep <PORT Number(8061)>

    Result

    tcp46      0      0  *.8061                 *.*                    LISTEN      131072 131072  71666      0

  • The Find the PID for the locking port –
    lsof -i :<PORT Number(8061)>
    

    Result

    COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME

    java    71666 tangupta   90u  IPv6 0x9f73e601cf2fbd79      0t0  TCP *:8061 (LISTEN)

  • Kill:
    kill -9 <PID(71666)>

Result – Process running on the above port would be killed. Now you can resume your           work on the above port which was blocked.

While running the NUnit (version 2.4.8) Test Cases through command prompt, Success Exception is thrown on MAC machine only

  • Problem Statment : While running the NUnit Test Cases through command prompt, Success Exception is thrown on MAC machine (Xamarin Studio is the IDE for MAC) only. All Test Cases are passing on Xamarin Studio. Even I am able to run all the NUnit Test Cases on Windows machine through IDE (Visual Studio) as well as CMD.

          Command is : nunit-console bin/Test.dll

Below is the stack-trace for the same –

NUnit version 2.4.8 Copyright (C) 2002-2007 Charlie Poole. Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov. Copyright (C) 2000-2002 Philip Craig. All Rights Reserved.

Runtime Environment – OS Version: Unix 15.5.0.0 CLR Version: 4.0.30319.42000 ( 4.6.0 (mono-4.6.0-branch/746756c Thu Sep 8 05:39:12 EDT 2016) )

…F.F.F…F..F.F.F…F.F.F..F.F.F

Tests run: 21, Failures: 13, Not run: 0, Time: 83.483 seconds

Test Case Failures: 1) Com.Tests.Api.ApiTest.TestInvalidXApiHeader : NUnit.Framework.SuccessException : Access token provided is invalid or has expired at Com.Tests.Api.ApiTest.TestInvalidXApiHeader () [0x0003f] in <145cf86ff7fd46c1b4269832d7dbe00f>:0 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in /private/tmp/source-mono-4.6.0/bockbuild-xamarin/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/corlib/System.Reflection/MonoMethod.cs:305

Here I have written Test Case for Invalid Access Token. And one more things, it doesn’t not give the details of number of test cases passes. Again I would like to mention that problem is only faced on MAC machine through CMD.

  • Solution :

Note – This is a known bug in unit-console 2.4.8 which is bundled with Mono installation within Xamarin Studio.

To avoid this issue, I used 3.x version of nunit-console on the command line. Execute the following command –

nuget install nunit.runners

/NUnit.Console.3/bin/nunit3-console bin/Test.dll

Hope this solves your problem. 🙂