Share this blog!

I have been using a VPS in which I have hosted a JSP project and after spending quite a long time on the internet, I found the correct way to install the SSL certificate I bought. It is always better to follow the instructions of your certificate provider, but sometimes, these instructions can be somewhat misleading, with popular assumptions such as owning a perfect machine or having an expert knowledge on the prerequisites. In this post, I will be trying to loosen up some such problems but feel free to comment any suggestions or remarks.


The scenario


I have Tomcat 8.5 running on my VPS with Apache server and in that, I have deployed a web app on the root (Let's say http://mysitesname.com/).

Creating the CSR


When you are purchasing an SSL certificate, you will be prompted to input a CSR code which can be easily generated using OpenSSL by running the following command on the command line:

openssl req -new -newkey rsa:2048 -nodes -keyout server.key -out server.csr

This command will generate two files (server.key and server.csr. Never give away your private key ie server.key)

Once you upload the CSR code to the certificate provider, you will be asked to activate it. (Eg: you might need to place a certain file at the root of the site, respond with an admin email etc)

Once the SSL is activated, then only you can install it.

Installing the SSL


I purchased a Comodo SSL certificate and since I selected a PositiveSSL, I could download 3 files such as:
  • mysitesname_com.crt
  • mysitesname_com.p7b
  • mysitesname_com.ca-bundle
Let's say I downloaded those files on a folder names /home/ssl on the VPS and I copied the previously created CSR and Key files into the same folder for convenience.

Installing SSL on Apache vs Tomcat

I spent an annoyingly long time on trying to install SSL on tomcat and then realized that according to my requirement, where I had to install was on Apache. It's basically because that I had previously modified my Apache's virtualhosts file to direct to the deployed webapp. So even though the running webapp was deployed on Tomcat, the http was provided by Apache. It is because Apache is an HTTP Server, serving HTTP while Tomcat is a Servlet and JSP Server serving Java technologies. Tomcat is a servlet container. A servlet, at the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (HttpServlet), which is then compiled to .class files by the server and executed by the Java virtual machine.

Once the certificate files are stored on the VPS, its only a matter of modifying Apache's virtualhosts. Since my VPS is Ubuntu, the file I must modify is /etc/apache2/sites-enabled/mysitesname.com.conf. The filename and the path may vary according to the OS installed.

The file already contained a virtual host on port 80. For this purpose a new host entry must be added on port 443 as follows:

Listen 443

<VirtualHost _default_:443>

        ServerName mysitesname.com

        SSLEngine on

        SSLCertificateFile "/home/ssl/mysitesname_com.crt"

        SSLCertificateKeyFile "/home/ssl/server.key"

        SSLCACertificateFile "/home/ssl/mysitesname_com.ca-bundle" 

</VirtualHost>

Since I had set my webapp to be hosted on the root, my previous settings too had to be added, after which the complete entry will look like the following:

Listen 443

<VirtualHost _default_:443>

        ServerName mysitesname.com

        SSLEngine on

        SSLCertificateFile "/home/ssl/mysitesname_com.crt"

        SSLCertificateKeyFile "/home/ssl/server.key"

        SSLCACertificateFile "/home/ssl/mysitesname_com.ca-bundle"

        ProxyPreserveHost On

        ProxyPass / http://mysitesname.com:8080/

        ProxyPassReverse / http://mysitesname.com:8080/

</VirtualHost>


Redirecting to HTTPS

In order to redirect your domain traffic to your https domain, add the following in your conf file.

Listen 443

<VirtualHost *:80>

        RewriteEngine On 

        RewriteCond %{HTTPS} off 

        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

</VirtualHost>

After the conf file is modified, restart the server using service apache2 restart.

If it generates an error saying Invalid command 'SSLEngine' , you will have to enable the ssl module from the commons package by running sudo a2enmod ssl and restart again.

That's it! Try browsing the site with https and ensure it is installed correctly.


In this post, I will be going through the installations and requirements needed to run the benchmark model presented for DengAI hosted on DrivenData.

What is DrivenData?

Generally, data mining (sometimes called data or knowledge discovery) is the process of analyzing data from different perspectives and summarizing it into useful information - information that can be used to increase revenue, cuts costs, or both. DrivenData is an organization that hosts online data science competitions where the data and problem are posed by a socially-minded organization. You get to put your analytic skills to the test in order to tackle real-world problems with real-world impact. DengAI is a competition hosted by DrivenData that allows competitors to predict the local epidemics of the dengue disease. The blog on this link, presents a benchmark model provided by DrivenData that can be used to compare the competitors results with.

Selecting the correct wheel file

The benchmark is modeled using Python (obviously) and Jupyter Notebook. Therefore the first thing you must have is python, in your machine. I am running this on a Windows machine therefore I had to install some of the required python plugins from the wheel files on gohlke packages.

When selecting the required packages you have to be careful to pick the one that is compatible with your machine. For example, when I run python in my cmd, I get the following:

Therefore when I have to get numpy, I will be selecting "numpy‑1.12.1+mkl‑cp35‑cp35m‑win32.whl" from the list as follows:


Installing the packages

The benchmark requires a handful of libraries, which could be easily installed using pip using the command line as follows. IT's not a problem if some of them are already installed.

1. Upgrade pip
python -m pip install --upgrade pip


2. Install Numpy
  • Download the correct wheel file from numpy on gohlke 
  • Open command line in the downloaded folder
  • Run pip install "numpy wheel filename" (Eg: pip install "numpy‑1.12.1+mkl‑cp35‑cp35m‑win32.whl")

3. Install pandas

pip install "pandas wheel filename"


4. Install SciPy

pip install "scipy wheel filename"


5. Install Statsmodels

pip install "statsmodels wheel filename"


6. Install Scikit-learn

pip install -U scikit-learn


7. Install Seaborn

pip install seaborn


8. Install Matplotlib

pip install matplotlib


9. Install Jupyter

pip install jupyter


10. Run Jupyter

jupyter notebook

When you run this code, the jupyter server will be started which will be used to run our model. It will present a token which will be asked for, when running the notebook.

Create and run a notebook

I am using Jetbrains PyCharm to run this model, which allows users to easily manage python scripts. In PyCharm, create a new project and in that, create a new Jupyter Notebook.

Once the notebook is created, you will be presented with the editor to manage the cells. Copy the In[1] in the benchmark post and past in a new cell. Then click on the run button to run the cell. You might be prompted to enter the token from the jupyter as said in #10 above.


If the first cell is successfully run, it indicates that your library installations are successful. Keep adding the other cells and run the benchmark.

Points to remember


  • It is always better to run each cell individually - which is obviously why jupyter notebooks are useful for.
  • If filepaths are troublesome, try using absolute paths.
  • If there are exceptions and/or errors where the fix does not seem to work, try restarting the jupyter server.


The following sample shows an example code where JSch is used to create an SSH session and connect to a remote Database.

This sample Java project was created using maven and the mysql and JSch dependencies in the pom.xml are as follows:

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

The connectSession() method will be creating a session and returning it (so it can be disconnected later).
The main method is simply accessing the DB using a typical database connection.

package com.sachi;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.sql.*;

/**
 * Created by Sachi on 4/1/2017.
 */
public class JschTrial {
    static int lport;
    static String rhost;
    static int rport;

    public static Session connectSession() {
        Session session = null;
        String user = "mySSHusername";       //ssh username
        String password = "mySSHpassword";   //ssh password
        String host = "myHOSTorIP";          //ssh host/IP
        int port = 22;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(user, host, port);
            lport = 4321;
            rhost = "localhost";
            rport = 3306;
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            System.out.println("Establishing Connection...");
            session.connect();

            int assinged_port = session.setPortForwardingL(lport, rhost, rport);
            System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
        } catch (Exception e) {
            System.err.print(e);
        }
        return session;
    }

    public static void main(String[] args) {
        Session ses = null;
        try {
            ses = connectSession();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("An example for accessing remote db through ssh!");
        Connection con = null;
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://" + rhost + ":" + lport + "/";

        String db = "dabname";                //db name
        String dbUser = "root";               //db username
        String dbPasswd = "dbrootpassword";   //db userpassword
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url + db, dbUser, dbPasswd);
            try {
                String sql = "SELECT name FROM mytable";
                PreparedStatement ps = con.prepareStatement(sql);
                ResultSet rset = ps.executeQuery();
                while (rset.next()) {
                    System.out.println("Id : " + rset.getString("name"));
                }
            } catch (SQLException s) {
                System.out.println("SQL statement is not executed!");
            }
            con.close();
            ses.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

You may have already come across situations where web forms statically alert you about the availability of a username or email without loading another page or refreshing the page. In this post, we will be discussing how to achieve this using AJAX script and JSP.



Let's assume our html form is as follows. Please note that I'm adding only the relevant components. 

<form name="myForm" onsubmit="return validate()">
    <label>Username:</label>
    <input type="text" name="userName" onblur="checkUniqueness()" />
    <span id="eMsg" style="color:red;"></span>
</form>

In this example, I'm using onblur which is triggered when the focus is lost, for example when the user selects the next input or clicks somewhere else on the form after typing the username.There are many other options you can use such as a separate button to check it or check during validation.  I am also using a span with red color text to display the error message.

The onsubmit="return validate()" is also important. If the validate is returning true, or there is no validate, the form will be submitted while we are checking the username and the process after submission will be occurring. The validate method prevents a form from submitting under given conditions. Therefore it is important that there is a condition that prevents the form from submitting during our username checking AJAX call.

The JavaScript function with the AJAX call is as follows:

function checkUniqueness() {
          var xmlhttp = new XMLHttpRequest();
          var username = document.forms["myForm"]["userName"].value;
          var url = "exist.jsp?username=" + username;
          xmlhttp.onreadystatechange = function () {
               if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
                      if (xmlhttp.responseText.includes("NO")) {
                            document.getElementById("eMsg").innerHTML = "Username already exists";
                      }
               }
          };
          try {
                xmlhttp.open("GET", url, true);
                xmlhttp.send();
          } catch (e) {
                alert("unable to connect to server");
          }
}

As you can see, we need a JSP that has the ability to check the uniqueness by reading data from somewhere, probably a database. The following represents a comprehensive example of the JSP, including the database call.

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="DB.DBConnectionHandler"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="Controller.DBDataList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
    if (null != request.getParameter("username")) {   //check if parameter is there
        String uname = request.getParameter("username");  //extract username parameter
        try {

            //create connection and make the db call
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/highertradesmendb", "root", "hahaha");
            String query = "SELECT * FROM user where username=?";
            PreparedStatement ps = con.prepareStatement(query);
            ps.setString(1, uname);
            ResultSet rsetUser = ps.executeQuery();

            //check existance
            boolean stat = !rsetUser.first();
            con.close();

            //print the result
            if (stat) {
                out.print("YES");
            } else {
                out.print("NO");
            }

        } catch (Exception e) {
            System.out.println("get unique username error -  " + e);
        }
    }
%>

What is retrieved in the JavaScript is what we print to out.print and a string comparison is done in the JavaScript to define the results.



The following animation was created to present the basics of blockchain concept including how it is immutable and decentralized.




In this blog post, we will be deploying a sample JSP project in Heroku -  a cloud platform as a service (PaaS) that lets companies build, deliver, monitor, and scale app. Special thanks goes to Chanaka Lakmal for the technical support provided.

Updating the pom file

For Java projects, Heroku requires a pom.xml file which is used to retrieve any data regarding the deployment of the project. Therefore I created a sample JSP project with maven.

Although not necessary for using Webapp Runner it’s a good idea to have your build tool download Webapp Runner for you since your application will need it to run. When you build and deploy the project locally, the webapp-runner.jar will be downloaded to target/dependency. You can specify it in the pom.xml file as follows:

<build>
    ...
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.3</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals><goal>copy</goal></goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>com.github.jsimone</groupId>
                                <artifactId>webapp-runner</artifactId>
                                <version>8.0.30.2</version>
                                <destFileName>webapp-runner.jar</destFileName>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Adding the Procfile

A Procfile is a mechanism for declaring what commands are run by your application’s dynos on the Heroku platform. It is simply a text file named "Procfile" in the root of your project directory. (Note it must be named exactly as Procfile only. Names such as Procfile.txt are not allowed). In the procfile, add the following single line.

web:    java $JAVA_OPTS -jar target/dependency/webapp-runner.jar --port $PORT target/*.war

Adding Git connectivity

Heroku allows projects to be synced with Git therefore I initialized a Git repository too.
In Heroku, I created an application which will be my target application. All the configurations regarding deployment of the application are under the tab Deploy.

Heroku offers multiple deployment methods that include Heroku Git, which can be defined as a more customized version of deploying through Github, but for this project, I chose the default Git deployment method as follows.

Since I had already added projects using Git before, my git account was already added and all I had to do was to search for the repository name and connect it to the application. If it is your first time connecting Git with Heroku, it will prompt you to log in.




Enabling automatic deployment

Once the repository is connected, Heroku will display some additional settings that allow automatic or manual deployment methods. In the Automatic Deploy, your project will be automatically updated with every Git push you perform on your repository.



Adding a buildpack for the application

Next, we will add a build pack for our application. Buildpacks are scripts that are run when your app is deployed. They are used to install dependencies for your app and configure your environment.

You can add a BuildPack from the option under Settings tab.



Since my application is JSP I chose Java as the BuildPack.


Deploying and scaling the application

Once the build pack is added, you can deploy it by clicking on the Deploy Branch under the Deploy tab. You can also try out the automatic deployment feature by pushing a change to the Git repo.


Once deployed, click on Resources tab and you will see the content of your Procfile there. In order to scale our application, we must enable its dyno as follows:



That's it and we successfully deployed a JSP project in Heroku.

I participated in a tech talk about blockchains organised by SLASSCOM Technology Forum held on 31st January 2017 at Dialog. As an undergraduate preparing for the final year research project, I found the tech talk to be very informative.

4 speakers from a thorough industrial and technical background presented about the basics of blockchain technology, the business models of it, how bitcoin works and other implementations that have been built on top of blockchain technology.

The conclusion as a whole was that blockchain technology has a firm infrastructure with unique features which is fairly new in the world of technologies.

After the 4 presentations, a panel discussion was held where participants were given the opportunity to ask questions or comment on the presented ideas. Many participants actively joined the discussion by asking questions, most of which were focused on how the technology can be used in business models.



Blockchain was originally devised for Bitcoin, the digital currency everyone is talking about, but as of now, the concept is currently spreading its wings to reach various other potential uses.

So what is blockchain?

It is a distributed database that is duplicated across a network of computers. The data is not stored in a single location, but distributed across thousands of locations (according to Bitcoin). The changes in the records are handled using hash values that link records with each other. This makes the records easily verifiable and ensures that there is no single point of failure, thus making it difficult for a hacker to alter any record.

Durability, robustness, transparency are the some of the key good features that comes with the blockchain technology. However, according to this research paper, it has been found that the current research done on blockchains is relatively low, possibly because it is a new concept in the world with the first research paper written in 2013.

This research paper analyses the research papers on the topic blockchains and compares and contrasts the content, subtopics, challenges and future directions of the blockchain technology. The authors have developed a search protocol that first conducted a pilot search with the keyword “blockchain” and they have found out that 80% of the results were focused on Bitcoin, the first implementation of blockchains, rather than the concept of blockchains itself. Then the search protocol was customized to look for papers that discussed about the technology and the target was narrowed down to 41 papers.

The authors have emphasized on the fact that the research on blockchains is comparatively low. The research paper mainly identifies 4 questions to which the solutions are sought by analysing the research papers.  The results obtained by the analysis show that the publications were slowly increasing starting from the year 2013, that 80% of the papers are from academic sources, that the papers on the applications are increasing gradually than on the improvements and that 80% of the papers focus on overlapping aspects of blockchains such as security and privacy. The authors conclude that there exist research topics that have not been covered yet, such as throughput, latency, usability from the developer’s perspective, wasted resources and versioning and multiple chains.

The authors have comprehensively analysed the current research topics related to blockchain and the results are significantly useful for future researchers since the paper discusses the potential future directions in the blockchain field. Rather than simply pointing out, the authors have analysed in details what’s missing in the current literature with regard to the importance of the missed topics and the subtopics that are related to them.

Bunny Hop is a simple JavaScript game developed using CreateJS.

The only control function is to click anywhere on the game canvas. Click to start playing, click to jump and click to start over when hit.

A spritesheet is used to animate the bunny, and a ticker keeps the game on the clock. EaselJS, a branch of CreateJS is used for the graphics and SoundJS, another branch of CreateJS provides sounds.

You can play the game using this link: http://sachi-d.github.io/myApps/Bunny_Hop/
You can find the source code on this link: https://github.com/sachi-d/Bunny-Hop

Bunny Hop - play

Bunny Hop - points

Bunny Hop - hit 

Next PostNewer Posts Previous PostOlder Posts Home