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.

Advertisements

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.”

Dockerize Java RESTful Application

Please follow the below steps to dockerize your java RESTful application –

Prerequisites : Please insure that Docker, java and mvn is installed on your machine.

  1. Create Dockerfile : Go to the root of the application where pom.xml is contained. Below is the content of my Dockerfile –

cd yourProjectFolder -> vi Dockerfile

#Fetch the base Jav8 image

FROM java:8

#Expose the local application port

EXPOSE 8088

#Place the jar file to the docker location

ADD /target/lookupService-1.0-SNAPSHOT.jar lookupService-1.0-SNAPSHOT.jar

#Place the config file as a part of application

ADD /src/main/java/com/test/config/config.properties config.properties

#execute the application

ENTRYPOINT [“java”,”-jar”,”yourService-1.0-SNAPSHOT.jar”]

  1.  Build Docker Image :

docker build -f Dockerfile -t yourservice .

  1. Run the Docker Image :

docker run -p 8088:8088 -tyourservice

Option -p publishes or maps host system port 18080 to container port 8080.

Note* Please don’t forget to change your base uri that is localhost:8088 to 0.0.0.0:8080 network interface created inside the container listen to all available address.

Few important commands of docker to know :

  1. To find the Id of your running container –

docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES

77558fabec6c       yourservice       “java -jar lookupS…”   38 minutes ago      Up 38 minutes       0.0.0.0:8088->8088/tcp   affectionate_brahmagupta

  1. To kill the process inside the docker using container is –

docker container kill 77558fabec6c(Container Id)

Now you can test your RESt call on port 0.0.0.0:8080 using any of the REST client . Hope it helps 🙂

Expose a local web server to the internet

ngrok allows you to expose a web server running on your local machine to the internet. Just tell ngrok what port your web server is listening on.

If you don’t know what port your web server is listening on, it’s probably port 80, the default for HTTP.

Example: Expose a web server on port 9876 of your local machine to the internet
ngrok http 9876

When you start ngrok, it will display a UI in your terminal with the public URL of your tunnel and other status and metrics information about connections made over your tunnel.

The ngrok console UI
ngrok by @inconshreveable
 
Tunnel Status                 online
Version                       2.0/2.0
Web Interface                 http://127.0.0.1:4040
Forwarding                    http://3472fdsu.ngrok.io -> localhost:9876
Forwarding                    https://3472fdsu.ngrok.io -> localhost:9876
 
Connnections                  ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

Hope it helps. For more details, you can refer https://ngrok.com/docs/.

Way to redirect the url from HTML page getting in the response of REST call through AJAX

Problem Statement – I have one CDN server (mylocalmachinedomain:8022) hosted through XAMPP (Apache) on my local machine. In parallel to it, I have written the micro-service (microservicedomainname.com:8444)  to expose it’s REST end point hosted on tomcat server on my local machine. Now First I have to make a REST call (expose end point written in my micro-service) from the HTML page through AJAX. Secondly while exposing the REST call, it would redirect to some other page. So that I need to handle in the HTML page through AJAX. There are 2 ways to do the same –

My micro-service end point java code-

    @GET

    @Path(“/authCall”)

    @ApiOperation(value = “Displays a message”, notes = “The message is read from the properties”, response = Test.class )

    @ApiResponses(value = { @ApiResponse(code = 500, message = “Something went wrong”, response=Test.class) })

    @Produces(MediaType.APPLICATION_JSON)

    public Response authCall() throws Exception {

        logger.info(“This is a log to check oAuth api”);

        //HttpsURLConnection conn = null;

        String url = “https://account.service.com/api/oauth2/authorize?response_type=code&client_id=MY_CLIENT_ID&redirect_uri=MY_REDIRECT_URI&state=MY_STATE;

        URI uri=new URI(url);

        return Response.status(Status.TEMPORARY_REDIRECT).location(uri).header(“Content-Type”, “application/json;charset=UTF-8”).build();

    }

 1st way –

 

  $.ajax({

  type: “GET”,

  url: “https://microservicedomainname.com:8444/myapp/authCall“,

  success: function(data){

  //alert(data);

 document.open();

 document.write(data);

document.close();

   }

 });

2nd way –

var xmlhttp;

    function init() {

       // put more code here in case you are concerned about browsers that do not provide XMLHttpRequest object directly

       xmlhttp = new XMLHttpRequest();

        var url =”https://microservicedomainname.com:8444/myapp/authCall“;

        xmlhttp.open(‘GET’,url,true);

        xmlhttp.send(null);

        xmlhttp.onreadystatechange = function() {

               if (xmlhttp.readyState == 4) {

                  if ( xmlhttp.status == 200) {

                     document.open();

document.write(xmlhttp.responseText);

document.close();

                 }

                 else

                       alert(“Error ->” + xmlhttp.responseText);

              }

        };                           

    }

<body onload=”init()”> 

</body> 

Hope it helps 🙂

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.

How to redirect an URL using REST Java

There are multiple ways to perform redirection. Actually 3x family of HTTP plays a vital role while performing URL redirection in the below ways –

1. 301 Moved Permanently

String url = https://google.com/api/oauth/code?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=https://localhost:8443/myapp/test&#8221;;

URI uri=new URI(url);

return Response.status(Status.MOVED_PERMANENTLY).location(uri).build();

Now it’ll redirect you to your localhost endpoint defined in the parameter redirect_uri permanently.

2. 307 Temporary Redirect

return Response.temporaryRedirect(uri).build();