Send email using nodemailer node typescript

Standard

Follow following steps :

  1. Install dependancies :

npm install –save nodemailer

npm install @types/node –save
npm install @types/nodemailer –save
npm install @types/nodemailer-direct-transport –save
npm install @types/nodemailer-smtp-transport –save
npm install @types/nodemailer-bluebird –save

2. Create a typescript file say – SendEmail.ts

import * as nodemailer from ‘nodemailer’;

export class SendEmail {

private _transporter: nodemailer.Transporter;

constructor() {

const smtpConfig = {

host: ‘smtp.gmail.com’,

port: 465,

secure: true, // use SSL

auth: {

user: SEND_INVITATION_EMAIL_ID,

pass: SEND_INVITATION_EMAIL_APP_PASS // App password

}

};

this._transporter = nodemailer.createTransport(smtpConfig);

}

async sendMail(emailFrom: string,emailTo: string, subject: string, htmlMessage: string) {

let options = { from: emailFrom, to: emailTo, subject: subject, html: content }

return new Promise<void> ( (resolve: (msg: any) => void, reject: (err: Error) => void) => {

this._transporter.sendMail( options, (error, info) => { if (error) { reject(error); } else {

resolve(`Message Sent ${info.response}`);

}

})

} );

}

3. Call function sendMail from another typescript file as like :

let sendEmail = new SendEmail();

const sendEmailResult = await sendEmail.sendMail( SENDER_EMAIL_ID, RECEIVER_EMAIL_ID, subject, sendingMsg);

4. To create SEND_INVITATION_EMAIL_APP_PASS mentioned above follow following steps :

  1. Go to your Google Account.
  2. Select Security.
  3. Under “Signing in to Google,” select App Passwords. You may need to sign in. If you don’t have this option, it might be because:
    1. 2-Step Verification is not set up for your account.
    2. 2-Step Verification is only set up for security keys.
    3. Your account is through work, school, or other organisation.
    4. You turned on Advanced Protection.
  4. At the bottom, choose Select app and choose the app you using  Select device and choose the device you’re using  Generate.
  5. Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
  6. Tap Done.

Ref. https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor&visit_id=637539142002101586-972788534&rd=1

Run Node.js in background permanently

Standard

Use PM2 :

PM2 is daemon process manager that will help you manage and keep your application online. Getting started with PM2 is straightforward, it is offered as a simple and intuitive CLI, installable via NPM.

Installation

The latest PM2 version is installable with NPM or Yarn:

$ npm install pm2 -g

Start an app

The simplest way to start, daemonize and monitor your application is by using this command line:

$ pm2 start app.js  //or
$ pm2 start server.js

List all processes

$ pm2 list

List all processes

The simplest way to start, daemonize and monitor your application is by using this command line:

$ pm2 list

Managing processes

Managing application state is simple here are the commands:

$ pm2 restart app_name
$ pm2 reload app_name
$ pm2 stop app_name
$ pm2 delete app_name

Instead of app_name you can pass:

  • all to act on all processes
  • id to act on a specific process id

MultiThread – How to Run Multiple Threads Concurrently in Java? ExecutorService Approach

Standard

Let’s take a look at this example again: How to get Ping Status of any HTTP End Point in Java?

Have you noticed the thread execution for that example? It’s sequential. What if you have 500 endpoints? I bet you have to wait for at least 5 mins to get result. Which I’m sure is not the best solution.

Now what? The correct question would be:

  • How to Run multiple threads concurrently?
  • How to implement multiple threads in Java?
  • How do I run different threads in Java?
  • Java – Where is Multithreading Programming Tutorial?
  • Thread: How to use multiple threads to speed processing?

ExecutorService Approach is your answer.

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow()method prevents waiting tasks from starting and attempts to stop currently executing tasks.

Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

Method submit extends base method Executor.execute (java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

  • java – ExecutorService, how to wait for all tasks to finish?
  • A Guide to the Java ExecutorService
  • Java Thread Pool – ExecutorService explanation

Below is a simple Java Example which explains the usage of ExecutorService.

Output:

Now checkout the result. It should be in just seconds. I hope you find this helpful. Try running this more than one time and you may see different result as all threads are executing in parallels and who ever gets fast result, you will see result posted in Eclipse console.

How to setup user authentication in MongoDB 4.0

Standard

Creating the users

Let’s start, for real, by creating the actual users. Open your mongo shell and switch to the admin database:

use admin

Create the “admin” user (you can call it whatever you want)

db.createUser({ user: "admin", pwd: "adminpassword", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })

Don’t panic with all these brackets. We’re passing an “user” object to the createUser function, which contains a “roles” array. In the array we have one “role” object, which defines what the user can do and on which database.

In this case we’re giving the user the userAdminAnyDatabase role. This means that the admin user will be able manage (create, update, delete) users on all the databases of the MongoDB instance.

Make sure you use a safe password for the admin user, preferably generated by a password manager.

You can check that the user has been correctly created with this command:

db.auth("admin", "adminpassword")

The command will log you in as admin. Now exit the shell:

exit

We are now going to enable authentication on the MongoDB instance, by modifying the mongod.conf file. If you’re on Linux:

sudo nano /etc/mongod.conf

Add these lines at the bottom of the YAML config file:

security:
    authorization: enabled

This will enable authentication on your database instance. With nano, save with CTRL+X and confirm with y.

Now restart the mongod service (Ubuntu syntax).

sudo service mongod restart

You can check if the service is up with:

sudo service mongod status

Let’s go back in the mongo shell. Switch to the database admin and authenticate with the previously created user (called “admin”). Given that the user has the “userAdmin” role, it will be able to create and manage other users.

use admin
db.auth("admin", "adminpassword")

Now we will switch to an already created database and create a new user specifically for the database.

The following command will create an user with the role of dbOwner on the database. The dbOwner role will give to the user read and write permissions on all the collections of the database.

use yourdatabase
db.createUser({ user: "youruser", pwd: "yourpassword", roles: [{ role: "dbOwner", db: "yourdatabase" }] })

Check that everything went fine by trying to authenticate, with the db.auth(user, pwd) function.

db.auth("youruser", "yourpassword")
show collections

And that’s it, your MongoDB instance is now secured, provided that you used strong passwords.

When connecting with your favourite MongoDB Client from an application, use a connection string that will look like this:

mongodb://youruser:yourpassword@localhost/yourdatabase

Now, one last thing…

Protecting from external access

We’re now going to check that the MongoDB instance is listening on the local loopback interface only. This means that the DBMS will be accepting connections to the databases only when they come from the host itself.

You can of course adapt this to your needs, for example by enabling access on a private network interface, but the important thing to understand is that you should carefully decide which interfaces MongoDB should listen on. You should therefore avoid to expose the instance on the Internet if you don’t require to access it from the outside. And even if you do, there are much better ways to do that, for example by using an SSH tunnel. But that’s another story.

So, open mongod.conf in edit mode again, as we’re going to check out the net.bindIp option. That option tells the mongod process on which interfaces it should listen.

Examples of bindIp configuration

net:
    bindIp: 127.0.0.1

With this configuration, MongoDB will listen on 127.0.0.1 only (localhost). It means that you’ll be able to connect to your database only from the local machine.

NOTE: 127.0.0.1 is the default bind interface starting with MongoDB 3.6.0.

net:
    bindIp: 0.0.0.0

With this configuration, MongoDB will be listening on 0.0.0.0 (“all the networks”). It means that mongod will listen on all the interfaces configured on your system. Pay attention that in this way you are likely going to allow everyone on the Internet to access your database (as far as they have the credentials, of course, so pay particular attention to poor passwords).

You can also make MongoDB listen on more than one interface, by separing them with commas. This is useful if you want to make MongoDB listen on localhost and a private network interface.

net:
    bindIp: 127.0.0.1,172.21.200.200

A solution that you could consider is to set the bindIp option to 0.0.0.0 and then configure a firewall to filter incoming TCP requests on the MongoDB port and allow them only on specific interfaces.

install mongoDB on Linux

Standard

1) Create a /etc/yum.repos.d/mongodb-org-4.0.repo file so that you can install MongoDB directly using yum:

go to directory: /etc/yum.repos.d/
Create file: vi mongodb-org-4.0.repo
Paste data:
[mongodb-org-4.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc

2) Install the MongoDB packages.
sudo yum install -y mongodb-org

3) Start MongoDB.
sudo service mongod start

4) Begin using MongoDB.
mongo –host 127.0.0.1:27017

Shell script to import JSON files in mongodb

Standard
  • Following script will find all files in directory path mentioned below in “DIR” variable.
  • Read each file name in loop & execute mongodb import command i.e
    • mongoimport -d DATABASE_NAME -c TABLE_NAME –file FILE_PATH\FILE_NAME.json

#!/bin/sh

DIR=”NsBackupFiles/”
for eachFile in “$DIR”*
do
fileName=`echo $eachFile | cut -d’/’ -f 2`
tableName=`echo $fileName | cut -d’_’ -f 1`
echo $tableName
mongoimport -d ns_backup -c $tableName –file $eachFile
done

How to loop ArrayList in Java

Standard

There are four ways to loop ArrayList:

  1. For Loop
  2. Advanced for loop
  3. While Loop
  4. Iterator

Lets have a look at the below example – I have used all of the mentioned methods for iterating list.

import java.util.*;
public class LoopExample {
   public static void main(String[] args) {

      ArrayList<Integer> arrlist = new ArrayList<Integer>();
      arrlist.add(14);
      arrlist.add(7);
      arrlist.add(39);
      arrlist.add(40);

      /* For Loop for iterating ArrayList */
      System.out.println("For Loop");
      for (int counter = 0; counter < arrlist.size(); counter++) { 		      
          System.out.println(arrlist.get(counter)); 		
      }   		

      /* Advanced For Loop*/ 		
      System.out.println("Advanced For Loop"); 		
      for (Integer num : arrlist) { 		      
           System.out.println(num); 		
      }

      /* While Loop for iterating ArrayList*/ 		
      System.out.println("While Loop"); 		
      int count = 0; 		
      while (arrlist.size() > count) {
	 System.out.println(arrlist.get(count));
         count++;
      }

      /*Looping Array List using Iterator*/
      System.out.println("Iterator");
      Iterator iter = arrlist.iterator();
      while (iter.hasNext()) {
         System.out.println(iter.next());
      }
   }
}

Output:

For Loop
14
7
39
40
Advanced For Loop
14
7
39
40
While Loop
14
7
39
40
Iterator
14
7
39
40

How to iterate arraylist elements using Enumeration interface

import java.util.Enumeration;
import java.util.ArrayList;
import java.util.Collections;
 
public class EnumExample {
 
   public static void main(String[] args) {
      //create an ArrayList object
      ArrayList<String> arrayList = new ArrayList<String>();
 
      //Add elements to ArrayList
      arrayList.add("C");
      arrayList.add("C++");
      arrayList.add("Java");
      arrayList.add("DotNet");
      arrayList.add("Perl");
 
      // Get the Enumeration object
      Enumeration<String> e = Collections.enumeration(arrayList);
 
      // Enumerate through the ArrayList elements
      System.out.println("ArrayList elements: ");
      while(e.hasMoreElements())
      System.out.println(e.nextElement());
   }
}

Output:

ArrayList elements: 
C
C++
Java
DotNet
Perl