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"));
    }
}