Reverse a string in place


public class ReverseStringInplace {

	public static void main(String[] args) {
		String str = "siva";
		String reverse = reverseTheString(str);
		System.out.println("original String "+ str);
		System.out.println("reverse String "+ reverse);
	}

	private static String reverseTheString(String str) {
		StringBuilder builder = new StringBuilder(str);
		int length = builder.length();
		for(int i=0 ; i< length/2; i++){
			char current = builder.charAt(i);
			int otherEnd = length-i-1;
			builder.setCharAt(i, builder.charAt(otherEnd));
			builder.setCharAt(otherEnd, current);
		}
		return builder.toString();
	}
}
Posted in Programing questions | Tagged , | Leave a comment

working with Mongo db + Java (subcollections)

subcollectionsCRUD.png

In the previous post we have seen different ways to use find() method. Today lets check out different operations we can perform on Sub Collections.

Index:

  • Creating a sub Collection in Collection
  • Adding Objects to sub collections
  • Updating sub collection data
  • Removing Objects from Sub Collection
  • Removing Sub Collection

Creating a sub Collection in Collection:

In mongo DB:

db.users.update({},{"Address":[]})

In Java :

Document subCollection = new Document("$set", new Document("Address",new ArrayList<Object>()));
         Document query = new Document();
         UpdateResult result =collection.updateMany(query, subCollection);
         if(result.isModifiedCountAvailable()){
         System.out.println("sub collections added");
         }else{
         System.err.println("not added");
         }

Adding Objects to sub collections:

In mongo DB:

db.users.update({"_id" : ObjectId("583febc7ac9dd6aa88de4fc6")},{$push:{"Address":{"city":"Banglore","country":"india","zipcode":"someZipCode"}}})

In Java :


Document subCollectionObject1 = new Document("city", "Banglore").append("country", "india").append("zipcode", "someZipCode");
        Document subCollectionObject2 = new Document("city", "Chennai").append("country", "india").append("zipcode", "5211251");
        Document query1 = new Document("_id", new ObjectId("583febc7ac9dd6aa88de4fc5"));
        collection.updateOne(query1, new Document("$push", new Document("Address", new Document(subCollectionObject1))));
        collection.updateOne(query1, new Document("$push", new Document("Address", new Document(subCollectionObject2))));

Updating sub collection data:

Since we don’t know the position of the Object in the array we use position parameter ‘$’

In mongo DB:

db.users.update({"Address.zipcode":"someZipCode"},{$set:{"Address.$.zipcode":"524896"}})

In Java :


 Document query2 = new Document("Address.zipcode", "someZipCode");
 collection.updateOne(query2, new Document("$set", new  Document("Address.$.zipcode","524896")));

Removing Objects from Sub Collection:

$pull works on Array, so we have to give array and the conditions, from which we have to remove array

In mongo Db:

db.users.update({"Address.zipcode":"524896"},{$pull:{"Address":{"zipcode":"524896"}}})

In Java :


 Document query2 = new Document("Address.zipcode", "someZipCode");
 collection.updateOne(query2, new Document("$set", new  Document("Address.$.zipcode","524896")));

Removing Sub Collection:

In mongo DB:

db.users.update({"_id" : ObjectId("583febc7ac9dd6aa88de4fc6")},{$unset:{"Address":1}})

In Java :


  Document query1 = new Document("_id", new ObjectId("583febc7ac9dd6aa88de4fc5"));
         collection.updateOne(query1, new Document("$unset", new Document("Address", 1)));

Below is full java program

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
import java.util.ArrayList;
import org.bson.Document;
import org.bson.types.ObjectId;

public class OperationsOnSubCollections {

    public static void main(String[] args) {
        MongoClient mongoClient = new MongoClient("localhost");
        MongoDatabase database = mongoClient.getDatabase("library");

        MongoCollection collection = database.getCollection("users");

        // create a sub collection
        Document subCollection = new Document("$set", new Document("Address", new ArrayList<Object>()));
        Document query = new Document();
        UpdateResult result = collection.updateOne(query, subCollection);
        if (result.isModifiedCountAvailable()) {
            System.out.println("sub collections added");
        } else {
            System.err.println("not added");
        }

        // Add objects to the subcollectins
        Document subCollectionObject1 = new Document("city", "Banglore").append("country", "india").append("zipcode", "someZipCode");
        Document subCollectionObject2 = new Document("city", "Chennai").append("country", "india").append("zipcode", "5211251");
        Document query1 = new Document("_id", new ObjectId("583febc7ac9dd6aa88de4fc5"));
        collection.updateOne(query1, new Document("$push", new Document("Address", new Document(subCollectionObject1))));
        collection.updateOne(query1, new Document("$push", new Document("Address", new Document(subCollectionObject2))));

        // modify data in sub collectin objects
        //(since we dont know the exacet posing of the onject in Address Array we use '$' as a positional parameter)
        Document query2 = new Document("Address.zipcode", "someZipCode");
        collection.updateOne(query2, new Document("$set", new Document("Address.$.zipcode", "524896")));

        // delete a sepecific sub collectin Object
        // $pull workes on Array, so have to give array and the conditons, from which i have to remove array
        Document query3 = new Document("Address.zipcode", "someZipCode");
        collection.updateOne(query3, new Document("$pull", new Document("Address", new Document("zipcode", "524896"))));

        // delete a key from colleciton
        Document query4 = new Document("_id", new ObjectId("583febc7ac9dd6aa88de4fc5"));
        collection.updateOne(query4, new Document("$unset", new Document("Address", 1)));

    }

 

Posted in mongodb | Tagged , , , | Leave a comment

SELECT vs FIND() [search records in Mongo way]

mongoselect.png

In the previous post we have seen some of the basic operations we perform on the mongo db from java. Today we will focus only on the SELECT operations.

In this post we will go through different searching operations such as , Greater than, less than, equals,  and some or the Logical operations such as And, Or, Not  and others such as  Starts with, Ends With, Contains,IN etc .

Before going into the program, lets setup a basic database and sample collections data.
Run the below script on your mongoDB, so that you will be ready with test data.

use mydb

db.user.save({"name":"jhon","email":"jhon@gmail.com","password":"jhon134","salary":2000})
db.user.save({"name":"casey","email":"casey@gmail.com","password":"casey","salary":1025})
db.user.save({"name":"candis","email":"candis@gmail.com","password":"candis","salary":100})
db.user.save({"name":"marcus","email":"marcus@gmail.com","password":"marcus","salary":250125})

The key point here is  to perform equal, less than, greater than, and Logical operations, the mongo java driver 3.2 provided very use full class com.mongodb.client.model.Filters.
It is a final class provides many static methods, to perform the search operations.

To perform string search operations such as Starts with, ends with, contains we need to opt for regular expressions.The important point here is , in relations databases we use ‘%’ the equivalent value for that in Mongo db is ‘.*’

Having the database ready, now lets jump into the code, all the respective operations description is written in comments.

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import static com.mongodb.client.model.Filters.regex;
import java.util.ArrayList;
import java.util.regex.Pattern;
import org.bson.Document;

public class SomeMoreSelectOperations {

    public static void main(String[] args) {

        // connect to mongodb
        MongoClient mongoClient = new MongoClient("localhost");
        MongoDatabase database = mongoClient.getDatabase("mydb");

        MongoCollection collection = database.getCollection("user");

        // equals
        collection.find(Filters.eq("name", "jhon"));

        // less than
        collection.find(Filters.lt("salary", 200));

        // greater than
        collection.find(Filters.gt("salary", 200));

        //Logical operations

        // where salary less than 200 and greater than 100
        collection.find(Filters.and((Filters.lt("salary", 200)), (Filters.gt("salary", 1000))));

        // where salary less than 200 or greater than 100
        collection.find(Filters.or((Filters.lt("salary", 200)), (Filters.gt("salary", 1000))));

        // where salary neither 200 nor 1000
        collection.find(Filters.nor((Filters.lt("salary", 200)), (Filters.gt("salary", 1000))));

        // not equals
        collection.find(Filters.not(Filters.eq("salary", 200)));

        //IN operation
        ArrayList values = new ArrayList();
        values.add(200);
        values.add(100);
        values.add(3000);
        collection.find(Filters.in("salary", values));

        // contains
        Pattern pattern = Pattern.compile(".*" + Pattern.quote("contain string") + ".*", Pattern.CASE_INSENSITIVE);
        MongoCursor<Document> cursor = collection.find(regex("columnName", pattern)).iterator();

       // For startswith
        Pattern pattern1 = Pattern.compile("^" + Pattern.quote("begin string"), Pattern.CASE_INSENSITIVE);
        MongoCursor<Document> cursor1 = collection.find(regex("columnName", pattern1)).iterator();

       // For endswith
        Pattern pattern2 = Pattern.compile(Pattern.quote("end string") + "$", Pattern.CASE_INSENSITIVE);
        MongoCursor<Document> cursor2 = collection.find(regex("columnName", pattern)).iterator();

        // iterate throght the cursor
        while (cursor2.hasNext()) {
            Document doc = cursor2.next();
            System.out.println(doc);
        }

    }

References:
http://stackoverflow.com/questions/37120845/mongodb-find-contains-startswith-endswith-and-exact-string-with-java-driver

Posted in mongodb | Tagged , , | 1 Comment

Basic CRUD Operations on MongoDB + Java

crudmongodb

In previous Post , we have seen 5 ways to connect to Mongo DB , now perform CRUD operations on Mongo DB using Java Driver 3.2.

Dependency Needed:

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.0.4</version>
    </dependency>
</dependencies>

Add the above dependency in the maven project.

To Insert One Document

Document doc = new Document("name", "dilip")
                .append("email", "dilip@gmail.com")
                .append("password", "secreat")
                .append("address", new Document("steet", "zyx").append("city", "somecity").append("country", "india"));

collection.insertOne(doc);

To Insert Multiple Document

 List<Document> docList = new ArrayList<Document>();
        for (int i = 0; i < 10; i++) {
            docList.add(new Document("i" , i));
        }
        collection.insertMany(docList);

To get the count of documents present in the Collection

 long count = collection.count();
 System.out.println("Total documents in collection is ::"+ count);

To get All the documents present in the Collection

MongoCursor<Document> cursor = collection.find().iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }

Note: the find() methods returns all the documents, and we need to iterate through the documents using the iterator.

To update document in a collection

collection.updateOne(Filters.eq("i", 10),
         new Document("$set", new Document("i", 110)));

Note: the above code,update the first document that has the i value as 10. if you want to update all the documents to be updated you can use

updateMany()

Lest see the full Example

import com.mongodb.CursorType;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;

public class MongoCrud {

    public static void main(String[] args) {

        // Connect to database

        MongoClient mongoClient = new MongoClient("localhost");
        MongoDatabase database = mongoClient.getDatabase("test");

        // get collection
        MongoCollection collection = database.getCollection("user");

        // To insert one docuemnt
        Document doc = new Document("name", "dilip")
                .append("email", "dilip@gmail.com")
                .append("password", "secreat")
                .append("address", new Document("steet", "zyx").append("city", "somecity").append("country", "india"));

//         collection.insertOne(doc);

        // to insert many docuements
        List<Document> docList = new ArrayList<Document>();
        for (int i = 0; i < 10; i++) {
            docList.add(new Document("i" , i));
        }
        collection.insertMany(docList);

        // to Count the number of documents in collection
        long count = collection.count();
        System.out.println("Total documents in user is ::"+ count);

        // get the first document
        Document firstDoc = (Document) collection.find().first();

        // get All Documents
        MongoCursor<Document> cursor = collection.find().iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }

        UpdateResult result =  collection.updateOne(Filters.eq("i", 10), new Document("$set", new Document("i", 110)));

    }
}

References:
http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/

Posted in mongodb | Tagged , , , | 1 Comment

5 ways to connect to MongoDB

mongojava

I have been working on Mongo java 2.x driver , Recently we planned to update our Java driver version to 3.x.  Then i got realized that a lot has been changed.
Now lets start working on Mongo-Java-Driver 3.2 version.

Depenedency:

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.0.4</version>
    </dependency>
</dependencies>

Example Program:

Lets look at the different ways to connect to the mongoDB

public class ConnectToMongoDb {
    public static void main(String[] args) {

        // 1. directly connect to single local mongo server
        MongoClient mongoClient1 =  new MongoClient();

        //2. or
        MongoClient mongoClient2 =  new MongoClient("localhost");

        //3. connect to the local mongo server with specific port
        MongoClient mongoClient3 =  new MongoClient("localhost",27017);

        //4 connect to the mongo servers with auto discovery features
        MongoClient mongoClient4 =  new MongoClient(
                Arrays.asList(new ServerAddress("localhost", 27017),
                              new ServerAddress("localhost", 27018),
                              new ServerAddress("localhost", 27019)));

        //5 connect to mongo server using connection string
        MongoClientURI mongoClientURI =  new MongoClientURI("mongo://username:passowrd@localhost:27018/dbname");
        MongoClient mongoClient5= new MongoClient(mongoClientURI);

        MongoDatabase database = mongoClient1.getDatabase("databaseName");
    }
}

References:
http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/installation-guide/

Posted in mongodb | Tagged , , , , | 1 Comment

Json to CSV using ng-csv

ng-csv.png

ng-csv is the simple directive that converts arrays and objects to CSV files.

Steps:

1. Add ng-csv.min.js  and angular-sanitize.min.js
    cdn for these are :


2. add 'ngSanitize', 'ngCsv' dependecies to your module
3. use ng-csv directive in html

Lets see a sample application

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!--angular js-->
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

        <!--ngcsv CDN-->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/ng-csv/0.3.6/ng-csv.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.8/angular-sanitize.js"></script>

        <script>
            angular.module('app', ['ngSanitize', 'ngCsv']).controller('downloader', function($scope) {
                // json data to be exported
                $scope.data = [
                    {
                        "id": "1",
                        "name": "avis"
                    },
                    {
                        "id": "2",
                        "name": "tasis"
                    },
                    {
                        "id": "3",
                        "name": "ticus"

                    }
                ]
            });
        </script>
    </head>
    <body ng-app="app" ng-controller="downloader">
<table border="1px">
<th>Id</th>
<th>Name</th>
<tr ng-repeat="user in data">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
</tr>
</table>
<h3> Hello , click the below button to export your data to CSV</h1>
<button class="btn  btn-xs btn-white" ng-csv="data" filename="mycsvfile.csv">Download Report</button>
</body>
</html>

References:

https://github.com/asafdav/ng-csv
http://ngmodules.org/modules/ng-csv

Posted in angularjs | Tagged , , , , | Leave a comment

Export JSON TO CSV Using AlaSQL.js

jsontocsv

AlaSQL is a client side in memory SQL database. It is very light weight and fast.It is fully functional and work in all modern browsers.

Below program show to we can export json data to CSV format, and download it.

STEPS:

1. ADD alasql libray  (you can dowload js file or use cdn ) 
     https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js
2. WRITE QUERY FROM YOUR JSON.
      EX: (SELECT * INTO FILENAME.XLSX FROM $scope.data )
3. RUN THE FILE
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!--angular js-->
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

        <!--alasql library-->
        <script src="https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script>

        <script>
            angular.module('app', []).controller('downloader', function($scope) {
                // json data to be exported
                $scope.data = [
                    {
                        id: 1,
                        name: "avis",

                    },
                    {
                        id: 2,
                        name: "tasis"
                    },
                    {
                        id: 3,
                        name: "ticus"
                    }
                ]

                $scope.downloadReports = function() {   // we can download our json data in many formats. ex: csv, excel
                   // var filename = "someFileName.xlsx"
                    var filename = "someFileName.csv"
                    //alasql('SELECT id as ID,name as Name INTO XLSX("' + filename + '",{headers:true}) FROM ?', [$scope.OrganizationUsersList]);
                    alasql('SELECT id as ID,name as Name INTO CSV("' + filename + '",{headers:true}) FROM ?', [$scope.data]);

                }

            });
        </script>
    </head>
    <body ng-app="app" ng-controller="downloader">
<table border="1px">
<th>Id</th>
<th>Name</th>
<tr ng-repeat="user in data">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
</tr>
</table>
<h3> Hello , click the below button to export your data to CSV</h1>
<button class="btn  btn-xs btn-white" ng-click="downloadReports()">Download Report</button>
    </body>
</html>
References:
http://alasql.org/
jsfiddle
Posted in angularjs | Tagged , , , , | Leave a comment