Tuesday, August 23, 2022

How to setup auto renewable free SSL certificate using Lets Encrypt and Nginx on Ubuntu machine

In this tutorial, we are going to set up free SSL auto-renewable Let's Encrypt along with Nginx.

Prerequisites:

Before we start setup, first make sure your domain e.g. example.com is pointed to the server's public IP address. You can set up and point this configuration from the dashboard of your domain service provider.

Connect to the remote server:

First SSH into the remote server where we want to set up the SSL.

If you are using a server password to connect, use the following command

sudo ssh server_username@ip_address

Here use your server username and server IP address to connect. For example ubuntu@34.344.56

If you are using a .pem file or other private keys to connect to a server then use the following command

sudo ssh -i path_to_pem_file server_username@ip_address

Install Nginx:

First, let's install Nginx on the server using the following commands.

sudo apt-get update
sudo apt-get install nginx

If nginx got successfully installed, then use the following command to verify.

nginx -v
nginx version: nginx/1.18.0 (Ubuntu)

Or we can verify by checking the status

sudo systemctl status nginx

Setup Nginx Configuration:

Now let's configure the Nginx for our domain. For this navigate to the Nginx directory

cd /etc/nginx/sites-available

Here, if we use the ls command we can see the default file for configuration. We will create a new file for our domain to configure for e.g 360learntocode.com, you can create using your domain name.

sudo vim 360learntocode.com

Now the new empty file is open lets edit and inserts the configuration by entering Shift + i

server {
      server_name 360learntocode.com;

      location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass              http://568.19.34.63:8080;
      }
}

Make sure to replace 360learntocode.com with your domain name and http://568.19.34.63:8080 with your IP address and the port in which your application is running.

Now save the configuration. Enter Esc and type :wq and hit Enter.

Now, symlink this file with the directory “sites-available” in our Nginx for this navigate to sites-available

cd /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/360learntocode.com /etc/nginx/sites-enabled/

To check the Nginx configuration use the following command

sudo nginx -t

We are supposed to see the output as below

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Reload the Nginx to reflect the changes:

sudo systemctl reload nginx

If we try to open our domain, we can see the Nginx 502 Bad Gateway if our application is not running otherwise we will see the running application.

Setup SSL Certificate:

For the SSL certificate, we are using the let's encrypt and certbot client. For more detail check let's Encrypt and Certbot

- Install Certbot client

Use the following commands to install certbot client

sudo apt-get update
 sudo apt-get install python3-certbot-nginx

Now, the certbot is successfully installed on our server. Let's create an SSL certificate for our domain

sudo certbot --nginx -d 360learntocode.com

Note: use your own domain name. Follow the steps asked afterward.

Here are some sample examples screens.

Now, let's reload the Nginx so that our configuration changes will reflect.

sudo systemctl reload nginx

If we load our domain URL then it will open over HTTPS.

If you want to see the overall configuration setup, please open the file that we created previously i.e 360learntocode.com inside /etc/nginx/sites-available/, there we can see all the setup done. The sample file looks like as below.

server {
      server_name 360learntocode.com;

      location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass              http://568.19.34.63:8080;
      }


    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/360learntocode.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/360learntocode.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = 360learntocode.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


      server_name 360learntocode.com;
    listen 80;
    return 404; # managed by Certbot


}

Here, the auto-renew script is managed by certbot client so we don't have to worry about the SSL expiration. To verify the auto-renew scripts navigate to the script file.

cd /etc/cron.d/
sudo vi certbot

In the certbot file, we can see the auto-renew script as below added by cerbot client

0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q renew

Thanks for following the tutorial, Happy coding !!

Share:

Mail Sending Issue in Java Application

Sometimes while sending the mail in the Java application we might get the following issue.

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
  nested exception is:
	java.net.ConnectException: Connection timed out (Connection timed out). Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
  nested exception is:
	java.net.ConnectException: Connection timed out (Connection timed out)
	at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:432)
	at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
	at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
	at org.springframework.mail.javamail.JavaMailSender$send$0.call(Unknown Source)
	at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
	at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
	at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
	at grails.plugins.mail.MailMessageBuilder.sendMessage(MailMessageBuilder.groovy:130)
	Caused by: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1
Caused by: java.net.ConnectException: Connection timed out (Connection timed out)

This might be due to a different reason.

Due to Firewall setup:

While sending mail we are using ports like 465 or 587 or other ports. So if you enable the firewall rules on your server then we might get this issue. So, enable the firewall rules for those TCP ports for outbound in your firewall settings.

The service provider disabled the port:

For security reasons, some server service providers disable those ports. For e.g:

For this, contact the service provider to allow the port or change the port on your configuration for your application. In the java application, for Gmail smtp.gmail.com we can use 587 instead of 465. The SMTP configuration looks as below:

["mail.smtp.host"           : "smtp.gmail.com",
				 "mail.smtp.starttls.enable": "true",
				 "mail.smtp.auth"           : "true",
				 "mail.smtp.port"           : "587",
		]
Share:

Tuesday, August 16, 2022

Convert Date to Pretty Time in Grails and Groovy

In this tutorial, we will learn how to convert Java Date to pretty time like moments ago, 1 hour ago, 1 week ago, 1 month ago, 1 year ago, and so on in grails application.

For this, we are using the prettytime plugin in our project.

Load PrettyTime in Grails Gradle project:

Add the following inside dependencies in the build.gradle file.

dependencies {
//other dependencies
 
compile 'org.grails.plugins:grails-pretty-time:4.0.0'
}

PrettyTime format Date:

Now let's create a method that formats the Java Date

import org.ocpsoft.prettytime.PrettyTime
import java.util.Date
public static String formatPrettyTime(Date date) {
        PrettyTime p = new PrettyTime()
        return p.format(date).trim()
    }

This will format the given date to a pretty time like moments ago.

Pretty Time Support Locale:

Prettytime supports different languages, for this use request to get the current locale and format it.

public static String formatPrettyTime(Date date, request) {
        Locale locale = RequestContextUtils.getLocale(request)
        PrettyTime prettyTime = new PrettyTime(locale)
        return prettyTime.format(date).trim()
    }

Here, we are using the locale from the request which gives the session locale for the current user

Current locale in grails application can also be achieved using LocaleContextHolder

import org.springframework.context.i18n.LocaleContextHolder
Locale locale = LocaleContextHolder.getLocale()

For pretty time supported language please follow prettyTime

Use in Gsp page:

If we are using the GSP pages HTML as server-side rendering, then we can use pretty time in GSP pages as below

<prettytime:display date="${someDate}" />
Share:

Monday, August 15, 2022

Convert Java Date to Pretty Time in Java

In this tutorial, we will learn how to convert Java Date to pretty time like moments ago, 1 hour ago, 1 week ago, 1 month ago, 1 year ago, and so on.

For this, we are using the prettytime dependency in our project.

If we are using a jar file download the desired jar file from the Maven repository and load the jar file in the application. Please follow How to add external jar or library on IntelliJ IDEA project

Loading PrettyTime in Gradle Project:

Add the following inside dependencies in the build.gradle file.

dependencies {
//other dependencies
 
implementation 'org.ocpsoft.prettytime:prettytime:5.0.3.Final'
}

Loading PrettyTime in Maven Project:

Add the following dependency inside the pom.xml file.

<dependency>
  <groupId>org.ocpsoft.prettytime</groupId>
  <artifactId>prettytime</artifactId>
  <version>5.0.3.Final</version>
  <type>bundle</type>
</dependency>

Pretty Time Format Date:

Now let's create a sample java class PrettyDateTime.java and create a converter method.

import org.ocpsoft.prettytime.PrettyTime;

import java.util.Date;

public class PrettyDateTime {

    public static void main(String[] args) {
        Date dateToConvert = new Date();
        System.out.println(convert(dateToConvert));
    }

    private static String convert(Date date) {
        PrettyTime p = new PrettyTime();
        return p.format(date);
    }
}

Here, we are creating the method convert which will convert the given Java Date to pretty time e.g moments ago.

Pretty Time format LocalDateTime:

import org.ocpsoft.prettytime.PrettyTime;

import java.time.LocalDateTime;

public class PrettyDateTime {

    public static void main(String[] args) {
        System.out.println(convert(LocalDateTime.now().minusSeconds(864000)));
    }

    private static String convert(LocalDateTime date) {
        PrettyTime p = new PrettyTime();
        return p.format(date);
    }
}

Pretty Time format in multiple languages:

Pretty time supports i18n and multiple languages.

import org.ocpsoft.prettytime.PrettyTime;

import java.util.Date;
import java.util.Locale;

public class PrettyDateTime {

    public static void main(String[] args) {
        Date dateToConvert = new Date();
        System.out.println(convert(dateToConvert, new Locale("de")));
    }

    private static String convert(Date date, Locale locale) {
        PrettyTime p = new PrettyTime(locale);
        return p.format(date);
    }
}

Here, we are using german support with "de" locale. For available language support follow prettyTime

Share:

Thursday, August 11, 2022

Java format date string to date and vice versa

This is a quick tutorial on formatting date in the string to java Date and Date to a date in string.

Let's create a sample Java class called DateTimeUtils.java.

Parse Date String to Date:

Let's look into the example that we want to parse the date string 2022-08-22 or 2022-08-22 04:22:100 to Date.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeUtils {

    public static void main(String[] args) throws ParseException {
        String format = "yyyy-MM-dd HH:mm:ss";
        String dateToFormat = "2022-08-22 04:22:100";
        Date formattedDate = parseDate(dateToFormat, format);
        System.out.println(formattedDate);
    }

    static Date parseDate(String date, String format) throws ParseException {
        if (date.isEmpty()) return null;
        return new SimpleDateFormat(format).parse(date);
    }
}

Here, we are using the SimpleDateFormat java class for parsing the date string to Date. We can provide any valid format as needed instead of yyyy-MM-dd HH:mm:ss For e.g if we want to format "2022-08-22" to Date then we need to use the format "yyyy-MM-dd"

Parse Date to Date in String:

Now let's look into another example where we want to parse the date into the date string. Here we are trying to parse the current date to the desired format like "yyyy-MM-dd HH:mm:ss"

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeUtils {

    public static void main(String[] args) throws ParseException {
        String format = "yyyy-MM-dd HH:mm:ss";
        Date dateToFormat = new Date();
        String formattedDate = formatDate(dateToFormat, format);
        System.out.println(formattedDate);
    }

    static String formatDate(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }
}

We are using SimpleDateFormat class to format the desired Date to date in string

The format will be the desired valid format that might be "yyyy-MM-dd" as well.

Share: