Category Archives: General

Install Let’sEncrypt ssl certificate in nginx hosted on Amazon Linux

If you need ssl certificate for only single EC2 instance, you need to use ELB to use AWS issued free certificate manager, which incurs ~$20 monthly cost. An alternative is to install free certificate by Let’sEncrypt on the nginx hosted on EC2 instance.

Here are the steps for that:

  1. Get letsencrypt

    git clone && cd letsencrypt/

  2. Create a config file  for certificate request, so you can reuse that

    # File: /etc/letsencrypt/config.ini
    # the domain we want to get the cert for
    domains =

    # key size
    rsa-key-size = 4096

    # this address will receive renewal reminders, IIRC
    email =

    # turn off the ncurses UI, we want this to be run as a cronjob
    text = True

    # authenticate by placing a file in the webroot (under .well-known/acme-challenge/) and then letting
    # LE fetch it
    authenticator = webroot
    webroot-path = /var/www/html

  3. Now create the certificate by requesting to letsencrypt, it will validate your domain by placing some file in your webroot-path, that has been mentioned in config file

sudo ./letsencrypt-auto --config /etc/letsencrypt/config.ini certonly -d"

4 files will be created in location: /etc/letsencrypt/live/

  • cert.pem: Your domain’s certificate
  • chain.pem: The Let’s Encrypt chain certificate
  • fullchain.pem: cert.pem and chain.pem combined
  • privkey.pem: Your certificate’s private key

You shall need the last two file for your nginx configuration.

4. Now change your nginx config file

# File: /etc/nginx/nginx.conf

# Settings for a TLS enabled server.

  server {

        listen *:443 ssl;


        root         /var/www/html;

        ssl on;

        ssl_certificate  "/etc/letsencrypt/live/";

        ssl_certificate_key "/etc/letsencrypt/live/";

      # It is *strongly* recommended to generate unique DH parameters

      # Generate them with: openssl dhparam -out /etc/letsencrypt/dhparams.pem 2048

      ssl_dhparam "/etc/letsencrypt/dhparams.pem";

      ssl_session_cache shared:SSL:1m;

      ssl_session_timeout  10m;

      ssl_protocols TLSv1 TLSv1.1 TLSv1.2;


      ssl_prefer_server_ciphers on;

      # Load configuration files for the default server block.

      include /etc/nginx/default.d/*.conf;

      location / {

        root /var/www/html/yourdomain;


      error_page 404 /404.html;

          location = /40x.html {


      error_page 500 502 503 504 /50x.html;

          location = /50x.html {



And don't forget to forward http request to https:

server {
listen 80 default_server;
listen [::]:80 default_server;
rewrite ^ https://$server_name$request_uri? permanent;

5. Reload nginx

sudo service nginx reload

now you should be ok with

Simplest possible Java State Machine

Simplest possible Java State Machine

This simple state machine consists of few dead simple contracts for defining constraints and actions along with single engine file of ~80 lines.

This code base also includes few example file to show how to implement the contracts.

Transition Rule

Transition rules are defined in the state enum which implements a simple interface. Look at the example code to see how to define the rules.

Every state in the state enum defines from which states this state can be reached and what are the preconditions(a list) to statisfy for the transition and it allows to define a set of actions while doing the transition after satisfying all the preconditions.

Below is an example to define rule

public enum BlogState implements State {

public Map<State, ConstraintActionPair> getTransitions() {
return null;
public Map<State, ConstraintActionPair> getTransitions() {
Set stateActions = new HashSet<>();
stateActions.add(new PublishAction());

List stateConstraints = new ArrayList<>();
stateConstraints.add(new RoleConstraint());

ConstraintActionPair constraintActionPair =
new ConstraintActionPair<>(stateConstraints, stateActions);

Map<State, ConstraintActionPair> constraintActionPairMap = new HashMap<>();
//here the key is the state from which this state can be reached and
//the value is a pair of constraints and actions for that state
constraintActionPairMap.put(BlogState.DRAFT, constraintActionPair);

return constraintActionPairMap;

It indicates that state DELETED can only be reached from DRAFT, satisfying RoleConstraint and if satisfied, it executes Publish Action (just for example).

Transition Constraints

Constrains are classes implementing below simple contract. Constraints have access to old value, new value, old state, new state; making it easy to validate the business logic.

public interface StateConstraint {
boolean validate(T oldValue, T newValue, State fromState, State toState);

ConstraintViolationException getViolationException(T oldValue, T newValue, State fromState, State toState);

Transition Actions

Actions are class implementing below simple contract. The only method required to implement is execute(), which have access to old value, new value, old state, new state.

public interface StateAction {

int DEFAULT_ORDER = 100;

T execute(T oldValue, T newValue, State fromState, State toState) throws ActionFailedException;

* Determines if this action will halt the transition.
* If false, other actions will continue to execute.
* @return
default boolean isBlocking() {
return true;

* Low means higher priority.
* @return
default int getOrder() {

String toString();

Action Order

Actions are executed in order. You can override getOrder() method to set order of action. Lower the order number means higher prioriy. But you are not required to override this method, by default all actions have same priority(100).

Blocking & Non-blocking

Some actions may be blocking i.e if exception is thrown, no other actions is executed. In case of non-blocking actions, if it thows exception, next actions are executed sequentially. You can define a task blocking/non-blocking by simply overriding isBlocking() method in the action class. Be default all actions are blocking.

Get MySQL Tabel size sorted

Recently to dump a database with lots of large table which are not needed, I had to find out the large tables first and then use sequel pro to export the database with small tables and only structure of large table. I have used the following query to find out the large tables:

     table_schema as `Database`, 
     table_name AS `Table`, 
     round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` 
FROM information_schema.TABLES 
ORDER BY (data_length + index_length) DESC;

Enable Content Compression in nginx

To enable content encryption in nginx, put the below configuration inside server block of nginx configuration file (usually in /etc/nginx/nginx.conf):

       gzip on;
       gzip_disable "msie6";
       gzip_http_version  1.1;
       gzip_comp_level    5;
       gzip_min_length    256;
       gzip_proxied       any;
       gzip_vary          on;

You should get content size reduction unto 80%!

Upgrade PHP version to 5.5 in amazon linux

If you have older version of php in your amazon linux instance, follow the below steps to upgrade it to php 5.5:

  1. Find the list of old php packages and remove those:
    sudo yum list installed | grep "php"
    sudo yum remove php php-cli php-common php-devel php-fpm php-gd php-imap php-mbstring php-mcrypt php-mysql php-odbc php-pdo php-pear php-pecl-apc php-process php-xml (adjust according to your list from previous command)
    sudo yum remove httpd*
  2. Install new packages
  3. sudo yum install php55 php55-devel php55-common php55-cli php55-pecl-apc php55-pdo php55-mysql php55-xml php55-gd php55-mbstring php-pear php55-mcrypt mysql55 php55-server php55-mysqlnd php55-fpm
  4. Restart servers
  5. sudo service php-fpm restart
    sudo service nginx start
    sudo service mysqld start
  6. Check php-fpm config:
    sudo vim /etc/php-fpm-5.5.d/www.conf
    <blockquote> Enter the following content:
    listen = /var/run/php-fpm/php-fpm.sock
    listen.owner = nginx = nginx
    listen.mode = 0664
    user = nginx
    group = nginx

PHP Conference Asia 2015 Recap

The First Pan-Asian PHP conference happened in Singapore on last 22 – 23 September, 2015. Many international and regional speakers presented their valuable speeches in the event.

Group Picture from PHPConfAsia

Group Picture from PHPConfAsia

While in USA, EU lots of community events happens through the year, comparatively very few events happen in Asia! Now at least some people has taken the initiative to organize this great event. Heartiest thanks to Michael Cheng (@coderkungfu) and other people who worked hard to make the conference smooth & enjoyable.
It was really an awesome experience being in the conference.

At Widespace, we use PHP (specifically Laravel) for several platforms, two of us from our Dhaka office joined the event.

Events on Tuesday:

  • Rasmus Lerdorf started the conference with his keynote presentation. It was mostly about upcoming PHP 7. Listening about the next PHP version from the PHP creator was really exciting. He showed some new feature coming with PHP 7, compatibility and also provided performance comparison of PHP7 with other PHP versions and HHVM for different projects. You can get the rich presentation slides here.
  • After the tea break, Stéphane Boisvert came into stage with his in-depth discussion about WordPress Security. He discussed different security topics like sql injection, csrf attack, sanitization, authorization in wordpress. Thanks Stéphane for providing nice ‘WordPress’ branded Sunglasses 🙂 His talk will be very valuable for WordPress developers.
  • Later came a storyteller, telling a faily tale with animation! Well, Steven Cooper described PayPal and Braintree API’s and how they can be integrated into code with the help of fairy tale. You can enjoy his fairy tale here.
  • Before Lunch, the last session was about application (Magento) performance improvement by Harald Zeitlhofer from Austria. He gave an example how a magento installation performance issues were detected and corrected with the help of Dynatrace performance monitoring tool.
  • First session after awesome lunch was by Jack Lenox. He has shown the way of combining React development techniques with a more traditional PHP workflow. His lecture can be found here.
  • After that Bagus Aji Santoso came into stage telling about Panada Framework, Simple but High Performance PHP Framework from Indonesia. He was a bit shy, presenting for the first time in front of international audience 🙂 Panada framework seems to be popular in Indonesia powering up several popular local sites. See features about Panada in presentation here.
  • Edwin Ong then gave a lightning talk about PHP streams. PHP Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. He discussed how we use it knowingly or unknowingly regularly.
  • Before the tea break, last talk was given by Sam Yong, a student from NUS, with topic: Go Reinvent The Wheel. It is certainly true that reinventing the wheel in software industry drives numerous innovations which we see today.
  • Pierre Joye, PHP Core Developer and OSS contributor, then gave rich talk about PHP7, HHVM and Co. Besides showing performance statistics, new features about PHP 7, he also talked about Zephir and alternate PHP implementations including HHVM. See his presentation.
  • Premshree Pillai explained how they built a scalable system for tracking shipping packages for Etsy. He shared their architecture in Etsy and interested audience also asked several questions about their implementation. His presentation is shared in slideshare.
  • The last session of first day was with the topic ‘Why Your Test Suite Sucks’ given by Ciaran McNulty, Senior Trainer, Inviqa. He has nicely shown how to evolve from no-test to TDD state. He also showed several code snippet and how to improve the code in those cases. We should really follow the practices that Ciaran mentions in this nice presentation.

Events on day 2 will be published soon…