Get IP address of a docker machine

Run following command on host machine to get IP address of your docker container.

docker inspect --format '{{ .NetworkSettings.IPAddress }}' <container_id>
you can also get complete details of you docker container by running

docker inspect <container_id>
container_id can be obtainer by running

docker ps

How to enable authentication in MongoDB?

By default MongoDB does not require username and password to access the data. This is good for development environment, but on production setup we should enable authentication to enhance security.

Follow below steps to setup authentication/access control in MongoDB. These steps are performed on Ubuntu machine but should work on any Linux setup.

1. Start MongoDB without access control enabled
sudo service mongod start

2. Connect to MongoDB instance
mongo --port 27017

3. Switch to 'admin' database
user admin;

4. Create admin user
   
    This creates a new user in 'admin' database with role as 'userAdminAnyDatabase', which allows user to grant any user any privilege on any database.
db.createUser(

  {

    user: "<user-admin>",

    pwd: "<user-admin-password>",

    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]

  }

)

5. Disconnect mongo shell and stop MongoDB.
sudo service mongod stop

6. Edit mongod.conf file to enable authentication.

    Open mongod.conf file in editor (My preference vim)
sudo vi /etc/mongod.conf

7. Add following lines to enable authentication.
security:

  authorization: enabled

8. Restart MongoDB instance.
sudo service mongod restart

9. Connect and authenticate as the user administrator.
mongo --port 27017 -u "<user-admin>" -p "<user-admin-password>" --authenticationDatabase "admin"

10. Create user for application database.
use <app-db>;

db.createUser(

  {

    user: "<app-db-user>",

    pwd: "<app-db-password>",

    roles: [ { role: "readWrite", db: "<app-db>" } ]

  }

)

11. Connect and authenticate to application database.
mongo --port 27017 -u "<app-dv-user>" -p "<app-db-password>" --authenticationDatabase "<app-db>"

*Note: To authentication after connecting to mongo shell.
use <app-db>;

db.auth("<app-db-user>", "<app-db-password>");

Try-with-resources statement in Java 7

Java SE 7 introduced a new type of try-catch block called try-with-resource.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Prior to Java SE 7, you could use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a pre Java 7 finally block to close resource:
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

Now, with Java 7 you can achieve the same by using try-with-resources statement:
static String readFirstLineFromFileWithFinallyBlock(String path) {

    try (BufferedReader br = new BufferedReader(new FileReader(path))) {

        return br.readLine();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Here the BufferedReader will be automatically closed after try catch block exits, regardless of whether the try statement completes normally or abruptly.

How to write text to a file in Java?

1. Using PrintWriter
public class WriteFile {     public static void main(String[] args) {         String fileName = "D:\\temp.txt";         PrintWriter writer = null;         try {             //will replace existing file.             writer = new PrintWriter(fileName);             writer.println("This is first line.");             writer.println("This is second line");             writer.close();         } catch (FileNotFoundException e) {             //occurs when user does not have permission to create file.             e.printStackTrace();
        } finally {             if (writer != null) {                 writer.close();             }         }     } }


2. Using Files class (JDK 7+)
public class WriteFile {
    public static void main(String[] args) throws IOException {
        List<String> lines = Arrays.asList("Line One", "Line Two");
        Path file = Paths.get("D:\\test.txt");
        Files.write(file, lines, Charset.forName("UTF-8"));
    }
}

In Java, how to check if a file is directory or not?

We can use isDirectory() method of File object to check if a given file is a directory or not.
String filePathString = "C:\\test.txt";

File f = new File(filePathString);
if ( f.exists() && !f.isDirectory() ) {
    System.out.println("File is not a directory");
} else {
    System.out.println("Either file is missing or is a directory");
}

Use Java to check if a file exists

We can check if a file exists or not by using exists() method of File object.
String filePathString = "C:\\test.txt";

File f = new File(filePathString);
if ( f.exists() ) {
    System.out.println("File exists.");
} else {
    System.out.println("File does not exist.");
}

How to convert String to Integer or int in Java?

There a two ways to convert String object to integer value.

1. Using Integer.parseInt()

This method takes a String object as parameter and returns it primitive type int value.
String s = "100";

int i = Integer.parseInt(s);

System.out.println("Integer value is " + i);

2. Using Integer.valueOf()

This method takes a String object as parameter and returns an object of Integer class.
String s = "100";

Integer i = Integer.valueOf(s);

System.out.println("Integer value is " + i);

How to change folder location of Google Drive on Windows?

Many of the times we after installing Google Drive, we realize that we want to change the folder location where Google Drive syncs it's documents. It's not very straight forward to change the location. We have to disconnect Google Drive and then login again to change folder location.
  1. Disconnect account.
  2. Delete or rename the existing "Google Drive" folder.
  3. Click the drive icon and select sign in.
  4. After sign in, it will show a first-time tutorial. Click 'Next' through them all, but DO NOT click 'Done' on the last.
  5. There will be a button on the last page called "Sync Options". In here, there is the option to point to a different location.

How to read input from command line in Java?

The Scanner class was implemented in Java 5.0 to make getting input easier.
To read input from standard input that is console input we use scanner with System.in
Scanner input = new Scanner(System.in);
int i = sc.nextInt();    //execution will wait for input.
System.out.println(i);   //print input on console.

Use Spring Data to connect to MongoDB using SSL connection.

This post is in continuation to my earlier post on How to enable SSL in MongoDB Community version. Once we have enabled SSL connection on MongoDB server, how can we connect to MongoDB server using Spring Java application.

In a Spring application connection to MongoDB is controlled by MongoClient and MongoClientOptions classes.

Follow below steps to connect Java Spring application running on Windows server to a MongoDB instance using secure SSL connection.

1. Copy client-cert.crt and mongodb-cert.crt files to Client machine.

You need to copy client-cert.crt and mongodb-cert.crt files used for setting up MongoDB server to machine that will be running your Spring application. (Refer: How to enable SSL in MongoDB Community version)

2. Import client and server certificate files to keystore.

Use below command to import MongoDB certificate.
keytool -import -alias "MongoDB-cert" -file C:\Users\abc\ssl\mongodb-cert.crt -keystore truststore.ts -noprompt
and below command to import Client certificate.
keytool -import -alias "Client-cert" -file C:\Users\abc\ssl\client-cert.crt -keystore client.ts -noprompt
3. Application Configuration

We use SSLSocketFactory to establish secured SSL connection.
public class SSLMongoConnection {

    public static void sample() throws KeyManagementException, KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
        
        InputStream readStream = new FileInputStream("C:\\Users\\abc\\ssl\\clientstore.ts");
        
        KeyStore ksClient = KeyStore.getInstance("JKS");
        ksClient.load(readStream, "<password>".toCharArray());
        Key key = ksClient.getKey("client-cert", "<password>".toCharArray());
        readStream.close();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ksClient, "<password>".toCharArray());
 
        KeyStore ksCACert = KeyStore.getInstance(KeyStore.getDefaultType());
        ksCACert.load(new FileInputStream("C:\\Users\\abc\\ssl\\truststore.ts"), "<password>".toCharArray());
 
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ksCACert);
        
        SSLContext context = SSLContext.getInstance("TLS"); //We now provide our alternate KeyManager
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        SSLSocketFactory sslSocketFactory = context.getSocketFactory();

        MongoClientOptions mongoClientOptions = MongoClientOptions.builder().socketFactory(sslSocketFactory).maxConnectionIdleTime(120000).socketKeepAlive(true).build();

        MongoClient mongoClient = new MongoClient(new ServerAddress("<host-name>", 27017),
                singletonList(MongoCredential.createCredential("<username>", "<database>", "<password>".toCharArray())));

        //use mongoClient to execute queries
    }
}



How to enable SSL in MongoDB Community version

If we want to connect to a MongoDB instance running on one machine from a different machine (over internet), it would be more than advisable to secure the communication using SSL encryption. Fortunately MongoDB has in-built support for SSL and its very straight forward to enable it.

We can setup SSL connection using a certificate issues by a Certificate Authority or by using a self-signed certificate.

In this post we will cover steps for setting up SSL connection using a self-signed certificate on Ubuntu machine.

Follow below steps to setup self-signed SSL secured connection to MongoDB server from a remote machine.

1. Verify that your MongoDB installation supports SSL connection.

Run following command from command line
mongod --version
It should give output like:
db version v3.2.8

git version: ed70e33130c977bda0024c125b56d159573dbaf0

OpenSSL version: OpenSSL 1.0.1f 6 Jan 2014

allocator: tcmalloc

modules: none

build environment:

    distmod: ubuntu1404

    distarch: x86_64

    target_arch: x86_64

Notice the 'OpenSSL version' in the output. This suggests that your MongoDB installation supports SSL.

If you do not see 'OpenSSL' in the output, then your MongoDB installation probably does not support SSL. In this case you will have to install a version that come pre-built with SSL support or manually compile a version of MongoDB by enabling SSL.

2. Generate Self-signed certificate for Server.

To generate a self-signed certificate we would use OpenSSL. Most Ubuntu distributions come pre-installed with OpenSSL.

To install OpenSSL manually type command:
sudo apt-get install openssl

Once you have OpenSSL installed use following command to generate certificate.
openssl req -newkey rsa:2048 -new -x509 -days 365 -nodes -out mongodb-cert.crt -keyout mongodb-cert.key
You will be asked series of questions for generating the certificate.

Now use below command to concatenate certificate and key file to generate .pem file. MongoDB only supports .pem file.
cat mongodb-cert.key mongodb-cert.crt > mongodb.pem
Store mongodb-cert.key, mongodb-cert.crt and mongodb.pem files securely. You will need these files to connect to your MongoDB using SSL connection.

Copy mongodb.pem file to a preferred directory from where you want MongoDB to read this file. E.g.
/etc/ssl
3. Generate Self-signed certificate for Client.

Generating certificate for Client is similar to generating certificate for server. Use below commands to generate client certificates.
openssl req -newkey rsa:2048 -new -x509 -days 365 -nodes -out client-cert.crt -keyout client-cert.key
cat client-cert.key client-cert.crt > client.pem
4. Configure MongoDB to enable SSL

Open mongd.conf file
sudo vi /etc/mongod.conf
and add following lines to enable SSL.
net:    ssl:       mode: requireSSL       PEMKeyFile: /etc/ssl/mongodb.pem       CAFile: /etc/ssl/client.pem
'mode' as 'requireSSL' means that only SSL connects can be established non SSL connection will not work. You can set 'mode' to 'allowSSL' to support both SSL and non-SSL connections.

Restart mongod service to load new configurations.
sudo service mongod restart

4. Test SSL connection

Use --ssl option while starting MongoDB shell to connect using SSL connection
mongo --ssl --sslCAFile /etc/ssl/mongodb.pem --sslPEMKeyFile /etc/ssl/client.pem --host <host-name>