Contexts and Dependency Injection – Servlet


Lets create a sample project to demonstrate how contexts and dependency injection (CDI) works with servlet

1. Create a sample bean file

package edu.learn.cdi.demo.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;

@Named
@ApplicationScoped
public class ServiceBean implements Serializable {

    @PostConstruct
    public void init() {
        System.out.println("ServiceBean->Cdi bean");
    }

    //Will be called when @SessionScoped
    @PreDestroy
    public void destroying() {
        System.out.println("ServiceBean->Cdi bean");
    }



    public int doWork(int a, int b) {
        return a + b;
    }
}

2. Create a test servlet to consume CDI
package edu.learn.cdi.demo.servlet;

import edu.learn.cdi.demo.bean.ServiceBean;

import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "testServlet", urlPatterns = {"/testcdi"})
public class TestServlet extends HttpServlet {

  private static final long serialVersionUID = 2638127270022516617L;
  
  @Inject
  private ServiceBean service;
  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int a = 2;
        int b = 3;

        PrintWriter out = response.getWriter();
        out.println("Hello World: " + service.doWork(a, b));
        out.close();

        //Just to call @PreDestroy method in ServiceBean
        request.getSession().invalidate();
    }
}

3. Create a beans.xml file in WEB-INF
<beans
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
        bean-discovery-mode="annotated"
>

    <!--Optional, just write to keep remember how to exclude not needed classes-->
    <scan>
        <exclude name="edu.learn.cdi.demo.servlet"></exclude>
    </scan>
</beans>

4. Create a context.xml file in META-INF (optional)
<?xml version='1.0' encoding='utf-8'?>

<Context>
    <!--<Resource name="BeanManager"
              auth="Container"
              type="javax.enterprise.inject.spi.BeanManager"
              factory="org.jboss.weld.resources.ManagerObjectFactory"/>-->
</Context>

5. Add the following dependencies in your pom.xml
<dependencies>

    <!-- Jersey cdi (weld) dependency -->
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>${jersey2.version}</version>
    </dependency>

     <dependency>
         <groupId>org.glassfish.jersey.ext.cdi</groupId>
         <artifactId>jersey-cdi1x-servlet</artifactId>
         <version>${jersey2.version}</version>
     </dependency>

      <dependency>
        <groupId>org.jboss.weld.servlet</groupId>
        <artifactId>weld-servlet-core</artifactId>
        <version>3.1.2.Final</version>
     </dependency>

     <!-- JDK 11 support for XML -->
     <dependency>
         <groupId>javax.xml.bind</groupId>
         <artifactId>jaxb-api</artifactId>
         <version>2.3.1</version>
     </dependency>

    <dependency>
       <groupId>org.glassfish.jaxb</groupId>
       <artifactId>jaxb-runtime</artifactId>
       <version>2.3.1</version>
    </dependency>
</dependencies>
<build>
    <finalName>cdi</finalName>
</build>

6. To test your CDI application by typing the following 
http://localhost:8080/cdi/testcdi

Store Procedures with Hibernate


This section breifly describe how to call store procedure with Hibernate 5.x, I have created some store procedure in PostgreSQL 9.4/11 and Oracle 12c for demonstrating purpose.

Store procedure

PostgreSQL

DROP FUNCTION IF EXISTS db_version();
CREATE OR REPLACE FUNCTION db_version() RETURNS refcursor AS $body$
DECLARE
ref refcursor;
BEGIN
OPEN ref FOR SELECT TEXT ‘1.0.1’ AS RESULT;
RETURN ref;
END;
$body$ LANGUAGE plpgsql;

Oracle

CREATE OR REPLACE PROCEDURE DB_VERSION (CURSOR OUT SYS_REFCURSOR)
AS
BEGIN
OPEN CURSOR FOR SELECT ‘1.0.1’ AS RESULT FROM DUAL;
END;

Hibernate API code to call store procedure from JAVA

try{
StoredProcedureQuery procedureCall = session.createStoredProcedureCall("DB_VERSION")
.registerStoredProcedureParameter(1, Class.class, ParameterMode.REF_CURSOR);
String applicationVersions = (String) procedureCall.getSingleResult();

}catch (PersistenceException ex){
LOG.error("PersistenceException: ",ex);
}

Reactive Springboot


Springboot is a production ready suite for java/kotlin developer, springboot provides flexibility to build an application with zero configuration. The only difference which i feel in spring framework and springboot, in spring framework you have to do configuration yourself but in springboot its hides the configuration part and let you focus on what you intend to do.

e.g. if i want to build an application which supports both SQL and NoSQL (for caching purpose), why should i waste my time on configuration.

This is the beauty of springboot just add the dependency and its ready to work.

let me show you how flexible springboot is, please create a project by visiting: http://start.spring.io and just add “Reactive Web and Lombok” dependency. Now open your project in your favorite IDE. Now make the following changes in your main application to expose hello rest service

@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}

@RequestMapping(path = "users")
@RestController
class UserRest {
@GetMapping
public String hello(){
return "Hello World !!!";
}
}

You can visit the sample rest service for the following URL: http://localhost:8080/users

Now add the following dependencies to add JPA support into your Application

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

Now make the following changes in your main application, CommandLineRunner execute after configuration part which manage by spring IOC, CommandLineRunner add the sample users.

@Slf4j
@SpringBootApplication
public class SpringbootApplication {

@Bean
public CommandLineRunner addSampleData(UserRepo userRepo){
return args -> {
userRepo.save(new User("nabbasi", "x"));
userRepo.save(new User("fabbasi", "x"));
userRepo.save(new User("aabbasi", "x"));
log.info("Sample users have been added ...");
};
}

public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}

@RequestMapping(path = "users")
@RestController
class UserRest {
private UserRepo userRepo;

public UserRest(UserRepo userRepo){
this.userRepo = userRepo;
}

@GetMapping
public Iterable<User> hello(){
return this.userRepo.findAll();
}
}

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString(exclude = "password")
@Entity
class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private String username;
private String firstName;
private String lastName;
private String email;
private String password;

User(String username, String password) {
this.username = username;
this.password = password;
}
}

interface UserRepo extends CrudRepository<User, Long> {}

As you can see i haven’t done any configuration to utilize JPA in application. Now visit the sample rest service for the following URL: http://localhost:8080/users which return all users from database

Checkout the working copy from github

Jersey 2.x documentation with Swagger.io


This project contains jersey2, cdi, swagger, swagger is being used to generate jersey 2.x services documentation
Add the following dependency in your pom.xml

<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-jersey2-jaxrs</artifactId>
    <version>1.5.21</version>
</dependency>

Add the following in web.xml

Note: No servlet mapping is required

<servlet>
    <servlet-name>Jersey2Config</servlet-name>
    <servlet-class>io.swagger.jersey.config.JerseyJaxrsConfig</servlet-class>
    <init-param>
        <param-name>api.version</param-name>
        <param-value>1.0.0</param-value>
    </init-param>
    <init-param>
        <param-name>swagger.api.basepath</param-name>
        <param-value>http://localhost:8080/cdi/services</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

Add the register(io.swagger.jaxrs.listing.ApiListingResource.class); and register(io.swagger.jaxrs.listing.SwaggerSerializers.class); in your existing rest configuration

public class RestController extends ResourceConfig {
    public RestController(){
        register(ResponseCorsFilter.class);
        register(io.swagger.jaxrs.listing.ApiListingResource.class);
        register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
        registerClasses(getResourcesInstance());
    }

    private Set<Class<?>> getResourcesInstance() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        Class jsonProvider = null;
        try {
            jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        resources.add(jsonProvider);
        resources.add(UserWS.class);

        return resources;
    }
}

Add the following line at the top of your rest service e.g. UserWS.java
@io.swagger.annotations.Api(value = “user”)

Now open the following url
http://localhost:8080/cdi/services/swagger.json

Download the swagger ui from the following url
https://github.com/swagger-api/swagger-ui/archive/master.zip

Now extract the master.zip and copy the content from dist folder and past into webapp directory

Now open http://localhost:8080/cdi in your browser and now you should see swagger page, Now add url http://localhost:8080/cdi/services/swagger.json and press Explore button

Checkout the working example code https://github.com/ahlesunnatwaljammat/Jersey2-Cdi-Tomcat9/tree/Jersey2-Swagger

CDI with Jersey 2


1. Please first have a look Getting started with Jersey 2
2. Use the pom.xml from above link and add the following dependencie3
        <!-- Jersey cdi (weld) dependency -->
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>${jersey2.version}</version>
        </dependency>

       <dependency>
            <groupId>org.glassfish.jersey.ext.cdi</groupId>
            <artifactId>jersey-cdi1x-servlet</artifactId>
            <version>${jersey2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.weld.servlet</groupId>
            <artifactId>weld-servlet-core</artifactId>
            <version>3.1.2.Final</version>
        </dependency>
        <!-- JDK 13 support for XML -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.1</version>
        </dependency>
3. Create a CDI bean (ServiceBean.java)
package edu.learn.cdi.demo.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;

@Named
@ApplicationScoped
public class ServiceBean implements Serializable {

    @PostConstruct
    public void init() {
        System.out.println("ServiceBean->Cdi bean");
    }

    //Will be called when @SessionScoped
    @PreDestroy
    public void destroying() {
        System.out.println("ServiceBean->Cdi bean");
    }

    public int doWork(int a, int b) {
        return a + b;
    }
}
4. Now consume the service bean in UserWS (please check the above link)
package edu.learn.cdi.demo.ws;

import edu.learn.cdi.demo.bean.ServiceBean;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/users")
//RequestScoped will help cdi container to lookup and resolve cdi (ServiceBean) 
@RequestScoped 
public class UserWS {

    public UserWS(){
    }

    @Inject
    private ServiceBean service;

    @GET
    @Path("/userInfo")
    @Produces(MediaType.APPLICATION_JSON)
    public String userInfo(){        
        return "User info " + this.service.doWork(1,2);
    }
}

Checkout the complete code

Getting started with Jersey 2


1. Create a maven project and the following depedencies

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.learn.rest</groupId>
    <artifactId>Jersey-Demo</artifactId>
    <version>0.0.0.1</version>
    <packaging>war</packaging>

    <name>Jersey-Demo Maven Webapp</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jersey2.version>2.29.1</jersey2.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0</version>
            <scope>compile</scope>
        </dependency>

        <!-- Jersey 2.29.1 -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey2.version}</version>
        </dependency>

        <!-- Json support -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>13</source>
                    <target>13</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
2. Create a config java file (RestController.java)

import edu.learn.cdi.demo.ws.UserWS;
import org.glassfish.jersey.server.ResourceConfig;

import java.util.Set;

public class RestController extends ResourceConfig {
    public RestController(){
        registerClasses(getResourcesInstance());
    }

    private Set<Class<?>> getResourcesInstance() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        Class jsonProvider = null;
        try {
            jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        resources.add(jsonProvider);
        resources.add(UserWS.class);

        return resources;
    }
}
3. Create a sample rest service (UserWS.java)

package edu.learn.cdi.demo.ws;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/users")
public class UserWS {
    public UserWS(){
    }

    @GET
    @Path("/userInfo")
    @Produces(MediaType.APPLICATION_JSON)
    public String userInfo(){
        return "User info";
    }
}

4. Visit your rest service by typing the following:
http://localhost:8080/cdi/services/users/userInfo

Checkout the complete code

Jersey 2.x Server Sent Event with Angular 6


Jersey 2.8 bring Server Sent Event (SSE) support, SSE is similar to the long-polling mechanism, except it does not send only one message per connection. The client sends a request and server holds a connection until a new message is ready, then it sends the message back to the client while still keeping the connection open so that it can be used for another message once it becomes available. Once a new message is ready, it is sent back to the client on the same initial connection. Client processes the messages sent back from the server individually without closing the connection after processing each message. So, SSE typically reuses one connection for more messages (called events). SSE also defines a dedicated media type that describes a simple format of individual events sent from the server to the client. SSE also offers standard JavaScript client API implemented most modern browsers. For more information about SSE, see the SSE API specification.

Lets get started with SSE

first you have to add SSE dependency in your pom.xml

<dependency>
   <groupId>org.glassfish.jersey.media</groupId>
   <artifactId>jersey-media-sse</artifactId>
   <version>2.8</version>
</dependency>

Write a sample SSE service
@GET
@Path("sse/events")
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput getServerSentEvent(){
    final EventOutput eventOutput = new EventOutput();
    new Thread(() -> {
        try {
            for (int i = 0; i < 10; i++) {
                // ... code that waits 1 second
                final OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
                eventBuilder.name("message-to-client");
                eventBuilder.data(String.class,"Hello world " + i + "!");
                final OutboundEvent event = eventBuilder.build();
                eventOutput.write(event);
            }
        } catch (IOException e) {
            throw new RuntimeException("Error when writing the event.", e);
        } finally {
            try {
                eventOutput.close();
            } catch (IOException ioClose) {
                throw new RuntimeException("Error when closing the event output.", ioClose);
            }
        }
    }).start();
    return eventOutput;
}

Now define a method to consume SSE (generic.service.ts)
declare var EventSource;
public sseEvent(sseUrl: string): Observable<string> {
  return new Observable<string>(obs => {
    const es = new EventSource(this.serviceUrl + sseUrl, {withCredentials: true});
    es.addEventListener('message-to-client', (evt) => {
      obs.next(evt.data);
    });
    return () => es.close();
  });
}

withCredentials: true is being used to work with CORS, if you are deploying your angular app on same server the you don't need withCredentials.
If your angular app is being deployed on different server then you have to write ResponseCorsFilter.java
@Provider
public class ResponseCorsFilter implements ContainerResponseFilter {

    public ResponseCorsFilter() {
        System.out.println("ServerResponseFilter initialization");
    }

    @Override
    public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) {
        containerResponseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
        containerResponseContext.getHeaders().add("Access-Control-Allow-Origin", "http://noman");
        containerResponseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    }
}

Now consume SSE from component (app.component.ts)
private sseStream: Subscription;

ngOnInit() {
    this.sseStream = this.dashboardService.sseEvent("sse/events").subscribe(message => {
        console.log(message);
    });
}

ngOnDestroy() {
    if(this.sseStream){
        this.sseStream.unsubscribe(); 
    }
}

Checkout the complete code

Kotlin/Kotlin Native Intro


Kotlin is a statically type language and provide good interoperability with java, which means you can use kotlin with your existing code base. Spring community also providing good support for kotlin. Lets create a helloworld program in kotlin but befor that you have to setup kotlin at your machine.

Download the followings:

Alternatively you can use kotlin with jetbrains idea or eclipse

  • Jetbrains has built-in support for kotlin
  • Eclipse also has kotlin plug-in

Now create a helloworld in kotlin

fun main(args: Array) {
    println("Hello World")
    
    //count will automatically infer as Int 
    //or you can declare variable with Int
    val count = 0 //val value can't be change
    var loggedInUsers : Int = 0 //var value can be change
    
    for(i in 1..10 step 2){
        println("Hello World " + i)
    }
    
    val list = mutableListOf()
    list.add("Hello World 1....")
    list.add("Hello World 2....")
    list.add("Hello World 3....")
    println(list)
}

Compile the above program using kotlin/kotlin native compiler:

  • %KOTLIN%\bin\kotlinc HelloWorld.kt
    • compile it for jvm and it will create .class file
  • %KOTLIN%\kotlinc-js HelloWorld.kt -output HelloWorld.js
  • %KOTLIN%\bin\konanc HelloWorld.kt -o HelloWorld.exe -opt
    • -opt for optimize compilation
  • %KOTLIN%\bin\kotlinc HelloWorld.kt -o HelloWorld.exe

To generate webassembly (wasm) file by typing the following

  • %KOTLIN_NATIVE%\bin\konanc -target wasm32 HelloWorld.kt
    • above will generate program.wasm and program.wasm.js files
  • Create an index.html file with the following content
  • <!DOCTYPE html>
    <html lang="en">
     <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title>WASM with Kotlin</title>
     </head>
     <body>
     <h1>Welcome to WASM with Kotlin</h1>
     <script wasm="./program.wasm" src="./program.wasm.js"/>
     </body>
    </html>
  • Copy index.html, program.wasm and program.wasm.js files and put them into a http server
  • Once you visit that page, open console from dev tool

Docker Installation on Windows 10/Ubuntu17.04


Docker installation for Windows 10

  • Create an account on docker
  • Download docker-toolbox from
  • Set environment variables in docker.cmd
    • set DOCKER_CERT_PATH=%USERPROFILE%\.docker\machine\machines\default
    • set DOCKER_HOST=tcp://192.168.99.100:2376
    • set DOCKER_MACHINE_NAME=default
    • set DOCKER_TLS_VERIFY=1
    • set DOCKER_TOOLBOX_INSTALL_PATH=”D:\docker\Docker Toolbox”
  • If you want to use MINGW64 the set the following environment variables in docker.sh
    • export DOCKER_CERT_PATH=$USERPROFILE\\.docker\\machine\\machines\\default
    • export DOCKER_HOST=tcp://192.168.99.100:2376
    • export DOCKER_MACHINE_NAME=default
    • export DOCKER_TLS_VERIFY=1
    • export DOCKER_TOOLBOX_INSTALL_PATH=/D/docker/Docker Toolbox
  • Verify your installation by running the following
    • Run docker.cmd
    • docker run hello-world
  • Issue on windows while starting kitematic
    • Start-up stops at 99% – IP: 192.168.99.100 is not in the cert’s list: 192.168.99.101
    • Open docker.cmd and type docker-machine env
      • There was an error validating certificates for host “192.168.99.100:2376”: x509: certificate is valid for 192.168.99.101, not 192.168.99.100
    • Type docker-machine regenerate-certs default to resolve above error

 

Docker installation for Ubuntu 17.04

  • Run the following commands
    • sudo wget -qO- https://get.docker.com/ | sh
    • If you want to run docker without sudo then run following command
    • sudo usermod -aG docker hostname
  • Verify your installation by running the following
    • sudo docker run hello-world

SSL Certificate with OpenSSL


OpenSSL with Windows 10/Ubuntu 17

Download OpenSsl for Windows

Generate SSL certificate with OpenSSL do the following.

  1. Create the server private key
    sudo openssl genrsa -des3 -out server.key 2048
  2. Create the Certificate signing request
    sudo openssl req -new -newkey rsa:2048 -nodes -out server.csr -keyout server.key -subj “/C=PK/ST=Sind/L=Karachi/O=Matrix Systems pvt ltd/OU=Software Development/CN=your_machine_hostname”
  3. Remove the necessity of entering a passpharse for starting up nginx with ssl
    sudo cp server.key server.key.org
    sudo openssl rsa -in server.key.org -out server.key
  4. Sign the certificate
    sudo openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Configure Nginx for SSL

  1. uncomment the ssl section from conf/nginx.conf
  2. change the server_name in my case
    1. server_name noman.example.com
    2. ssl_certificate E:\\ssl_certificate\\server.crt
    3. ssl_certificate_key E:\\ssl_certificate\\server.key

Configure Tomcat for SSL

export the generated certificate as pkcs12 format

  1. Export openssl certificate for tomcat
    sudo openssl pkcs12 -export -in server.crt -inkey server.key -out server.p12 -name tomcat -CAfile server.crt -caname root -chain
  2. <Connector port=”8443″ protocol=”org.apache.coyote.http11.Http11NioProtocol” maxThreads=”150″ SSLEnabled=”true”>
    <SSLHostConfig>
    <Certificate certificateKeystoreFile=”E:\\ssl_certificate\\server.p12″ certificateKeystorePass=”changeit” type=”RSA” />
    </SSLHostConfig>
    </Connector>

Install digicert certificate do the following:

  • To check the alias name of your certificate (which you gives to digicert e.g. mysite_com.jks)
    • keytool -list -keystore mysite_com.jks -v
  • To install the digicert ssl certificate (which provided you by digicert e.g. mysite_com.p7b)
    • keytool -import -trustcacerts -alias server -keystore mysite_com.jks -file mysite_com.p7b