Create MongoDb Connection Java Code





Our application has a 30 min auto-expiring session - the session is renewed on server communication.
What is the best way to communicate an expiring session to the user? My initial thought is a to display a modal warning shortly before expiration with "your session is about to expire [continue]" (better wording?) which allows the user to continue (communicating in the background to renew the session).
• Is it ever appropriate to display a session timer to the user?
• Is it ever appropriate to expire a session without the user having an opportunity to extend it?
• Do users need to be aware of when the session will expire as long as they will have the option to extend it?

For more understanding : click


<dependencies>
  <dependency>
   <groupId>org.mongodb</groupId>
   <artifactId>mongo-java-driver</artifactId>
   <version>${mongodb.version}</version>
  </dependency>
  <dependency>
   <groupId>com.jayway.restassured</groupId>
   <artifactId>rest-assured</artifactId>
   <version>2.2.0</version>
  </dependency>
  <dependency>
   <groupId>bcprov</groupId>
   <artifactId>bcprov-jdk16</artifactId>
   <version>${bouncycastle.version}</version>
  </dependency>
  <dependency>
   <groupId>commons-codec</groupId>
   <artifactId>commons-codec</artifactId>
   <version>1.9</version>
  </dependency>
  <dependency>
   <groupId>net.sf.json-lib</groupId>
   <artifactId>json-lib</artifactId>
   <version>2.4</version>
   <classifier>jdk15</classifier>
  </dependency>
  <dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.2.4</version>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>cltool4j</groupId>
   <artifactId>cltool4j</artifactId>
   <version>1.0.1</version>
  </dependency>



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.bson.BsonDateTime;
import org.bson.BsonDocument;
import org.bson.Document;

import cltool4j.BaseCommandlineTool;
import cltool4j.args4j.Option;

import com.google.gson.GsonBuilder;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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.CreateCollectionOptions;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.UpdateOptions;

public class MongoDBInstaller extends BaseCommandlineTool {

 @Option(name = "-componentName", required = true, metaVar = "componentName", usage = "Component name(Tandem/Mongoservice/Pricefeed)")
 private String componentName;
 
 @Option(name = "-keyStorePasswd", required = false, metaVar = "keyStorePassword", usage = "Key Store Password")
 private String keyStorePasswd;
 
 @Option(name = "-user", required = true, metaVar = "user", usage = "Mongo db username")
 private String user;

 @Option(name = "-pwd", required = true, metaVar = "password", usage = "Mongo db password")
 private String password;

 @Option(name = "-db", required = true, metaVar = "db", usage = "Mongo db name")
 private String db;

 @Option(name = "-host", required = true, metaVar = "host", usage = "Mongo db host or replica set primary node details")
 private String host;

 @Option(name = "-port", required = true, metaVar = "port", usage = "Mongo db port or replica set primary node port")
 private int port;
 
 @Option(name = "-auth", required = false, metaVar = "auth", usage = "Mongo db authMechanism Example:SCRAM-SHA-256,SCRAM-SHA-1,PLAIN,GSSAPI,MONGO-X509")
 private String auth;
 
 @Option(name = "-replicaSetName", required = false, metaVar = "replicaSetName", usage = "Replica Set name if you are working on replica set mongo db")
 private String replicaSetName;
 
 @Option(name = "-connectTimeoutMS", required = false, metaVar = "connectTimeoutMS", usage = "connection time in MiliSecond of mongo db")
 private int connectTimeoutMS;
 
 private ConfigEncryptor encryptor;
 //https://examples.javacodegeeks.com/software-development/mongodb/java-mongodb-authentication-example/
 @Override
 protected void run() throws Exception {
  //Find out user id and password are encrypted or not
  boolean userflag=Encryptor.isEncryptedValue(user);
  if(userflag){
   //if it encrypted then do the decrypt of user name
   user = Encryptor.decrypt(Encryptor.getInnerEncryptedValue(user));
  }
  boolean passflag=Encryptor.isEncryptedValue(password);
  if(passflag){
   //if it encrypted then do the decrypt of password
   password = Encryptor.decrypt(Encryptor.getInnerEncryptedValue(password)); 
  }
  /* Imp. Note - 
         *      1.  Developers will need to encode the 'auth_user' or the 'auth_pwd' string if it contains the <code>:</code> or 
         *      the <code>@</code> symbol. If not, the code will throw the <code>java.lang.IllegalArgumentException</code>.
         *      2.  If the 'auth_user' or the 'auth_pwd' string does not contain the <code>:</code> or the 
         *      <code>@</code> symbol, we can skip the encoding step.
         */

  try {
   user = URLEncoder.encode(user, "UTF-8");
   password = URLEncoder.encode(password, "UTF-8");
  } catch (UnsupportedEncodingException ex) {
   ex.printStackTrace();
  }
  String clientUrl = null;
  clientUrl = "mongodb://" + user + ":" + password + "@" + host + ":"+ port +"/"
    + db+"?";
  if (auth != null) {
   clientUrl=clientUrl+ "authMechanism=" + auth+"&";
  } 
  if (replicaSetName != null) {
   clientUrl=clientUrl+ "replicaSet=" + replicaSetName+"&";
  }
  if (connectTimeoutMS >0) {
   clientUrl=clientUrl+ "connectTimeoutMS=" + connectTimeoutMS+"&";
  }else{
   clientUrl=clientUrl+ "connectTimeoutMS=300000";
  }
  // Mongodb connection string.
  MongoClientURI uri = new MongoClientURI(clientUrl);
  // Connecting to the mongodb server using the given client uri.
  MongoClient mongoClient = new MongoClient(uri);

  MongoDatabase mongoDB = null;
  
  //Initialize Encryptor
  encryptor = new ConfigEncryptor(keyStorePasswd);
  
  InputStream in = this.getClass().getResourceAsStream("/component/"+componentName+"/collections.js");
  BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  GsonBuilder gsonBuilder = new GsonBuilder();
  gsonBuilder.disableHtmlEscaping();
  gsonBuilder.setPrettyPrinting();
  Collections content = gsonBuilder.create().fromJson(reader,
    Collections.class);
  List<Collection> collections = content.getCollections();
  for (Collection collection : collections) {
   String dbName = db;
   if(dbName == null || dbName.length() <= 0) {
    dbName = collection.getSchema();
   }
   mongoDB = mongoClient.getDatabase(dbName);
   
   System.out.println(String.format("Processing collection:%s schema :%s", collection.getName(),dbName));

   MongoCollection<Document> dbCollection =  null;

   if(collectionExists(collection.getName(),mongoDB)){
    dbCollection = mongoDB.getCollection(collection.getName());
   } else{
    if(collection.isCapped()){
     CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions();
     createCollectionOptions.capped(true);
     if(collection.getMaxDocument()!=0)
      createCollectionOptions.maxDocuments(collection.getMaxDocument());
     if(collection.getMaxSize()!=0)
      createCollectionOptions.sizeInBytes(collection.getMaxSize());
     mongoDB.createCollection(collection.getName(),createCollectionOptions);
    }else {
     mongoDB.createCollection(collection.getName());
    }
    dbCollection = mongoDB.getCollection(collection.getName());
   }
   
   Index[] indexes = collection.getIndexes();
   if (indexes != null && indexes.length > 0) {
    for (Index index : indexes) {
     BasicDBObject keys = new BasicDBObject();
     IndexColumn[] indexColumns = index.getKeys();
     for (IndexColumn indexColumn : indexColumns) {
      keys.append(indexColumn.getColumn(),
        indexColumn.isAscending() ? 1 : -1);
      System.out.println("Index --> "+indexColumn.getColumn()+" is unique "+index.isUnique());
     }
     IndexOptions indexOptions = new IndexOptions();
     indexOptions.sparse(index.isSparse());
     indexOptions.background(true);
     indexOptions.unique(index.isUnique());

     if(index.getName()!=null) {
      indexOptions.name(index.getName());
     }

     System.out.println("Index unique "+index.isUnique()+" --> meta data --> "+indexOptions.toString());
     System.out.println("Index keys "+keys);
     if(index.isSparse() || index.isUnique()){
      dbCollection.createIndex(keys, indexOptions);
     } else {
      System.out.println("ensuring index ... "+dbCollection.toString());
      IndexOptions options = new IndexOptions();
      options.background(true);
      if(index.getName()!=null) {
       options.name(index.getName());
      }
      if(index.getExpiryInSeconds() > 0) {
       options.expireAfter(index.getExpiryInSeconds(), TimeUnit.SECONDS);
      }
      dbCollection.createIndex(keys, options);
     }
    }
   }
   if (collection.isMetaData()) {
    String[] uniqueCols = collection.getUnique();
    JSONArray data = getCollectionData(collection.getName());
    if (data != null && data.size() > 0) {
     System.out.println("\t Metadata table: Trying to insert/update the data");
     for (Object obj : data.toArray()) {
      JSONObject record = (JSONObject) obj;
      DBObject object = new BasicDBObject(record);
      BsonDocument bsonDocument1 = BsonDocument.parse(record.toString());
      BsonDocument bsonDocument = new BsonDocument("$set",bsonDocument1);
      
      //To populate created and last_updated on insertion
      if(collection.isPopulateCreatedDate()){
       BsonDocument insertDate = new BsonDocument("created", new BsonDateTime(System.currentTimeMillis())).append("last_updated", new BsonDateTime(System.currentTimeMillis()));
       bsonDocument.append("$setOnInsert", insertDate);
      }
      
      BasicDBObject basicDBObject = new BasicDBObject();
      for (String col : uniqueCols) {
       basicDBObject.append(col, object.get(col));
      }
      if(collection.isPartial()){
       long count = dbCollection.countDocuments(basicDBObject);//count(basicDBObject);
       if(count == 0){
        UpdateOptions updateOptions = new UpdateOptions();
        updateOptions.upsert(true);
        dbCollection.updateOne(basicDBObject, bsonDocument, updateOptions);
        System.out.println(String.format("\tAdded/updated record %s", obj));
       } else {
        if(collection.getName().equals("cobrand")){
         object = updateCobrandRecord(record);
         bsonDocument = new BsonDocument("$set",BsonDocument.parse(object.toString()));
         UpdateOptions updateOptions = new UpdateOptions();
         updateOptions.upsert(true);
         dbCollection.updateOne(basicDBObject, new BsonDocument("$set",bsonDocument),updateOptions);
         System.out.println(String.format("\tEntry already found, Updated it. %s", obj));
        } else if(collection.getName().equals("exchange_quote_feed") || collection.getName().equals("data_import_feed")){ //Price feed component changes
         dbCollection.updateOne(basicDBObject, bsonDocument);
         System.out.println(String.format("\tEntry already found, Updated it. %s", obj));
        } else {
         System.out.println(String.format("\tEntry already found, so skipping it. %s", obj));
        }
       }
      } else {

       if(collection.isInsertOnlyOnce()){
        long count = dbCollection.countDocuments();//count();
        if(count== 0){
         UpdateOptions updateOptions = new UpdateOptions();
         updateOptions.upsert(true);
         dbCollection.updateOne(basicDBObject, bsonDocument,updateOptions);
        }
       }
       else {
        if (collection.isInsertNewData()) {
         long count = dbCollection.countDocuments(basicDBObject);//count(basicDBObject);
         if (count == 0) {
          UpdateOptions updateOptions = new UpdateOptions();
          updateOptions.upsert(true);
          dbCollection.updateOne(basicDBObject, bsonDocument,updateOptions);
          System.out.println(String.format("\tAdded/updated record %s", obj));
         }
        } else {
         UpdateOptions updateOptions = new UpdateOptions();
         updateOptions.upsert(true);
         dbCollection.updateOne(basicDBObject, bsonDocument,updateOptions);
         System.out.println(String.format("\tAdded/updated record %s", obj));
        }
       }
      }
     }
    }
   }
  }
  mongoClient.close();
 }

 private DBObject updateCobrandRecord(JSONObject cobrand){
  JSONObject user = cobrand.getJSONObject("cobrandUser");
  JSONObject finapp = cobrand.getJSONObject("finapp");
  JSONObject fastLink = cobrand.getJSONObject("fastlink");
  JSONObject adminCredentials = cobrand.getJSONObject("admin");
  BasicDBObject update = new BasicDBObject()
   .append("cobrandUser.loginName", encryptor.encrypt(user.getString("loginName")))
   .append("cobrandUser.password", encryptor.encrypt(user.getString("password")))
   .append("fastlink.consumerKey", encryptor.encrypt(fastLink.getString("consumerKey")))
   .append("fastlink.consumerSecret", encryptor.encrypt(fastLink.getString("consumerSecret")))
   .append("finapp.consumerKey", encryptor.encrypt(finapp.getString("consumerKey")))
   .append("finapp.consumerSecret", encryptor.encrypt(finapp.getString("consumerSecret")))
   .append("admin.consumerKey", encryptor.encrypt(adminCredentials.getString("consumerKey")))
   .append("admin.consumerSecret", encryptor.encrypt(adminCredentials.getString("consumerSecret")))
   .append("admin.accessToken", encryptor.encrypt(adminCredentials.getString("accessToken")))
   .append("admin.accessTokenSecret", encryptor.encrypt(adminCredentials.getString("accessTokenSecret")));
  return new BasicDBObject("$set",update).append("$unset", new BasicDBObject("adminUser",""));
 }
 
 private JSONArray getCollectionData(String collectionName) {
  InputStream in = this.getClass().getResourceAsStream("/component/"+componentName+
    "/data/" + collectionName + ".js");
  StringBuilder sb = new StringBuilder();
  if (in != null) {
   BufferedReader br = new BufferedReader(new InputStreamReader(in));
   try {
    String line = br.readLine();

    while (line != null) {
     sb.append(line);
     line = br.readLine();
    }
   } catch (IOException e) {

   } finally {
    try {
     br.close();
    } catch (IOException e) {
    }
   }
  }
  JSONArray json = null;
  if (sb.length() > 0) {
   json = JSONArray.fromObject(sb.toString());
   if(collectionName.equals("config")){
    for(Object object:json){
     JSONObject config = (JSONObject)object;
     boolean hasEncryptedKey = config.containsKey("encrypted");
     if(hasEncryptedKey){
      boolean encrypted = config.getBoolean("encrypted");
      if(encrypted){
       String value = config.getString("value");
       config.put("value", encryptor.encrypt(value));
      }
     }
    }
   }
  }
  return json;
 }
 
 public boolean collectionExists(final String collectionName, MongoDatabase mongoDatabase) {
  MongoCursor<String> collectionNames = mongoDatabase.listCollectionNames().iterator();
  while (collectionNames.hasNext()) {
   if (collectionNames.next().equalsIgnoreCase(collectionName)) {
    return true;
   }
  }
  return false;
 }

 public void updateCobrandCollection(){
  
 }

 public void updateConfigCollection(){
  
 }

 
 public static void main(String[] args) {
  run(args);
 }
}







           




Previous
Next Post »