Thursday, 21 May 2015

Top 20 ROR Interview Questions

Some of the most important questions asked in Barclays India And TCS for Ruby On Rails Developer Position , but these questions can be asked in any company which is recruiting ROR developers .


• What are Modules in Apache?

• How does HTTP work, and specifically how does a web page appear in my browser?

• How to link your public directory to apache conf to serve assets ?

• How would you assess how “deployable” a software system is?

• What is Tracebility Matrix ?

• What is Resident memory in Ruby ?

• How New Relic works on different components of rails ?

• What are components of Puppet ?

• What is the difference between Puppet. Vagrant and Docker

• How to Load balance servers using Ruby Modules ?

• What is LDAP & AD how to configure them ?

• What is DML, DCL, DDL in SQL ?

• How to Replicate a NoSQL DB ?

• What is Kernel Programming in ruby how to bind and unbind Context in ruby?

• Write a Nagios Plugin in ruby which returns the health on mysql ?

• What is Database Sharding ?

• Which backup is Good when it comes to backing up database and why ?(Hint: Incremental or Differential)

• How would you monitor your Rails Application Performance ?

• What are the Different deployment tools(Automation) available in ruby ?

• What is MVVM in Javascript ?

Post Comments And Suggestions And Answers if you know them .

Thanks Amit for compiling this list .

Monday, 18 May 2015

How to Create Index With MongoDB 3 Java Driver

Sample Java Program to Create Index in MongoDB 3 Java Driver . This snipped also contains older code which was used to create index . You just need to create a BasicDBObject with key as a name on which you want to create a index , and value will be 1 or -1 . if you create it with 1 then it will create a ascending index , and if you create with -1 , then it will create descending index .
package mongoDBExample;

import java.util.Arrays;
import java.util.List;

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoDBTest
{
 public static void main(String[] args)
 {
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  
  /*MongoDatabase database = mongoClient.getDatabase("Test");
  List books = Arrays.asList(1251,2512);
  Document person = new Document("_id", "ABHSIHEK")
                              .append("name", "java roots")
                              .append("address", new BasicDBObject("street", "sad java")
                                                           .append("city", "mongos")
                                                           .append("state", "mongod")
                                                           .append("zip", 5151))
                              .append("books", books);
  
  MongoCollection collection= database.getCollection("people");
     collection.insertOne(person);*/
  
  MongoDatabase database = mongoClient.getDatabase("Test");
  MongoCollection collection= database.getCollection("people");
  //create index on name field 
                //use 1 for ascending index , -1 for descending index 
  BasicDBObject index = new BasicDBObject("name",1);
  
  collection.createIndex(index);
  System.out.println(" index created successfully ");
  ListIndexesIterable indexes = collection.listIndexes(BasicDBObject.class);
  MongoCursor cursor = indexes.iterator();
  while(cursor.hasNext())
  {
   BasicDBObject getCreatedIdx = cursor.next();
   System.out.println("index is : "+ getCreatedIdx.toString());
  }
  
  
  
  mongoClient.close();
  /**
   * Older code which is deprecated in 3.0
   */
  /*
  DB db = mongoClient.getDB("Test");
  List books = Arrays.asList(27464, 747854);
  DBObject obj = new BasicDBObject("_id", "javaroots").append("name", "java roots")
                .append("address", new BasicDBObject("street", "awesome java")
                .append("city", "mongos")
                .append("state", "mongod")
                .append("zip", 5151))
.append("books", books);;
  
  DBCollection col = db.getCollection("people");
  col.insert(obj);
                col.createIndex("name");*/
        
  
 }
}



Post Comments And Suggestions !!




Friday, 15 May 2015

MongoDB 3 With Java

Here is the simple java program to insert data in MongoDB database. version 3.0 API is changed a bit . MongoClient.getDB method is deprecated and MongoClient.getDatabase() is used , which returns an instance of MongoDatabse type .

package mongoDBExample;

import java.util.Arrays;
import java.util.List;

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBTest
{
 public static void main(String[] args)
 {
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  
  MongoDatabase database = mongoClient.getDatabase("Test");
  List books = Arrays.asList(1251,2512);
  Document person = new Document("_id", "ABHSIHEK")
                              .append("name", "java roots")
                              .append("address", new BasicDBObject("street", "sad java")
                                                           .append("city", "mongos")
                                                           .append("state", "mongod")
                                                           .append("zip", 5151))
                              .append("books", books);
  
  MongoCollection collection= database.getCollection("people");
     collection.insertOne(person);
  mongoClient.close();
  /**
   * Older code which is deprecated in 3.0
   */
  /*
  DB db = mongoClient.getDB("Test");
  List books = Arrays.asList(27464, 747854);
  DBObject obj = new BasicDBObject("_id", "javaroots").append("name", "java roots")
                .append("address", new BasicDBObject("street", "awesome java")
                .append("city", "mongos")
                .append("state", "mongod")
                .append("zip", 5151))
.append("books", books);;
  
  DBCollection col = db.getCollection("people");
  col.insert(obj);*/
        
  
 }
}


Also we dont need to use getLastError method , because now exception is thrown if any error occurs .


Post Comments And Suggestions !!

Thursday, 30 April 2015

JRE Not Supported Error DBCP

You might get below error while using Commons DBCP , even if you have correct JDBC driver in your classpath.
java.lang.UnsupportedOperationException: Java Runtime Environment (JRE) version 1.7 is not supported by this driver. Use the sqljdbc4.jar class library, which provides support for JDBC 4.0.
 at com.microsoft.sqlserver.jdbc.SQLServerConnection.(SQLServerConnection.java:238)
 at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
 at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
 at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
 at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
 at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)
 at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
 at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
 at io.estation.services.GoogleServices.downloadWebMasterToolReport(GoogleServices.java:152)
 at io.estation.services.rest.RestServices.testWm(RestServices.java:39)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)

When you run it in standlone java program , you get error like this :
WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path

Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: This driver is not configured for integrated authentication. ClientConnectionId:c4ecd18c-82f8-4e5b-a932-66d840a18532
 at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
 at com.microsoft.sqlserver.jdbc.AuthenticationJNI.(AuthenticationJNI.java:60)
 at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2229)
 at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
 at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
 at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
 at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
 at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
 at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
 at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
 at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
 at java.sql.DriverManager.getConnection(Unknown Source)
 at java.sql.DriverManager.getConnection(Unknown Source)
 at executeCommandTest.JDBCTest.main(JDBCTest.java:14)
Caused by: java.lang.UnsatisfiedLinkError: no sqljdbc_auth in java.library.path
 at java.lang.ClassLoader.loadLibrary(Unknown Source)
 at java.lang.Runtime.loadLibrary0(Unknown Source)
 at java.lang.System.loadLibrary(Unknown Source)
 at com.microsoft.sqlserver.jdbc.AuthenticationJNI.(AuthenticationJNI.java:35)
 ... 12 more
Turns out that in your jdbc string you are using integratedSecurity=true, this causes the Commons DBCP to throw error like this , which is not really actual error .
jdbc:sqlserver://localhost;databaseName=msdb;integratedSecurity=true
Remove this , and you will be fine .



Monday, 27 April 2015

Asynchronous File Uploads in Rails

Today we will be uploading a file to server using ajax call with the help of Iframe method.
There is a Ruby Gem available called remotipart, which handles this kind of situation.
Installation
Installing is easy. Just add it to your Gemfile:
gem "remotipart", "~> 1.2" # Assusming in Rails > 3.2
And run:
bundle install
Then
Make sure to add this line just after //= require jquery //= require jquery_ujs :
//= require jquery.remotipart
Now you're ready to start uploading files.
In your controllers, views, or helpers, you may want to know if the form was submitted with Remotipart (using the iframe-transport) Remotipart makes a method available called remotipart_submitted :
if remotipart_submitted?

  # Upload files

else

  # Perform Simple Ajax Calls

end
Handling the Error:

In most blogs you will find to handle ajax complete and ajax success function when using remoti part bcoz remoti part internally submits your request as Iframe for which your js.erb template is not executed in rails fashion.

To do so , Here is a trick.
If you get your response wrapped in a text area do this.

Open up config/initializers

Create a file named remotipart_override.rb & paste the content.

module Remotipart

 module RenderOverrides

    def render_with_remotipart *args

      render_without_remotipart *args

      if remotipart_submitted?

        textarea_body = response.content_type == 'text/html' ? html_escape(response.body) : response.body

        response.body = textarea_body

        response.content_type = Mime::HTML

      end

      response_body

    end

  end

end
Here we have tweaked the response body which is compatible with rails style.


Thanks to Santosh for writing this post .


Post Comments And Suggestions !!!

Sunday, 26 April 2015

Driver Class Not Found Error In MULE

If you use mule built in C3P0 data connection pool to connect to databse , it throws ClassNotFoundException even if the driver class is present in MULE_HOME/APPS/{YOUR_APP}/lib directory .

com.mchange.v2.c3p0.DriverManagerDataSource - WARN - Could not load driverClass com.microsoft.sqlserver.jdbc.SQLServerDriver
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
 at java.net.URLClassLoader$1.run(Unknown Source)
 at java.net.URLClassLoader$1.run(Unknown Source)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 at java.lang.Class.forName0(Native Method)
 at java.lang.Class.forName(Unknown Source)
 at com.mchange.v2.c3p0.DriverManagerDataSource.ensureDriverLoaded(DriverManagerDataSource.java:100)
 at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:132)
 at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182)
 at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171)
 at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137)
 at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014)
 at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32)
 at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810)
 at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
So if you use database connector configuration or create a separate spring bean for C3P0 datasource , it will not work .This is known bug . If you are using mule 3.5.0 , you might face this error . Solution :

1 ) Put your Driver class Jar file in MULE_HOME/lib folder instead of your app folder .
OR
2 ) Use some other datasource like CommonsDBCP .
Post Comments And Suggestions !!

Tuesday, 7 April 2015

Lambda Expression Example In Java

Java 8 added support for Lambda Expression . So what exactly are Lambda Expressions ?


Lambda Expressions are nothing but Anonymous Functions . Anonymous functions are methods which does not have any names , they make the code more concise and readable ,Suppose you want to sort a list of person based on their age , you can write following code using anonymous class syntax :
Collections.sort(list, new Comparator() {
   @Override
   public int compare(Person p1, Person p2) {
    return (p1.getAge() > p2.getAge()) ? 1 : 0 ; 
   }});

Now with the help of lambda expressions , this code can be reduced to one single line of code :
 Collections.sort(list,(p1,p2 ) -> (p1.getAge() > p2.getAge()) ? 1 : 0 );
its syntax is : (${Parameters}) -> {${method body}}

1 ) If the method takes only one parameter , then we do not need to use parenthesis.
2 ) We do not need to specify the type of parameter , it will be inferred automatically by java . so we do not need to write (Person p1 , Person p2 ) instead of (p1,p2).
3 ) The Interface must be Functional Interface . A functional interface is a kind of interface which contains only one single abstract method .In this example , Collections.sort method takes a Comparator as parameter , Comparator Interface has only one single method , so you can directly implement it without specifying its name using lambda .
4 ) You can write method body with multiple statements also like this :
Collections.sort(list,(p1,p2 ) ->{
   if ( p1.getAge() > p2.getAge())
    return 1 ;
   else 
    return 0 ;
  });
5 ) If you want to use variable declared in the enclosing method , you have to declare that as final .
6 ) You can create a Runnable using Lambda like this :
Runnable r = () -> System.out.println("Hello World !! ");
Hers's the complete java program example for Lamda Expressions in java .
package java8Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LambdaTest {
 
 public static void main(String[] args) {
  
  List<Person> list = generateList();
  //try to sort with age using anonymous classes way 
  Collections.sort(list, new Comparator<Person>() {
   @Override
   public int compare(Person p1, Person p2) {
    return (p1.getAge() > p2.getAge()) ? 1 : 0 ; 
   }
  });
                // method variable must be final to be used in lambda expression 
  final int x = 0 ;
                 //you can create a Runnable like this also using lambda expression
  //Runnable r = () -> System.out.println("thread running ");
  
  //sorting with Age using lambda expression  
  Collections.sort(list,(p1,p2 ) -> (p1.getAge() > p2.getAge()) ? 1 : 0 );
  Collections.sort(list,(p1,p2 ) ->{
   System.out.println(x);
   if ( p1.getAge() > p2.getAge())
    return 1 ;
   else 
    return 0 ;
  });
   
  for(Person p : list)
   System.out.println(p.getName() + " " + p.getAge() + "  " + p.getSalary());
  
  Collections.sort(list,(p1,p2 ) -> (p1.getSalary() > p2.getSalary()) ? 1 : 0 );
  for(Person p : list)
   System.out.println(p.getName() + " " + p.getAge() + "  " + p.getSalary());
  Collections.sort(list,(p1,p2 ) -> p1.getName().compareTo(p2.getName()));
  for(Person p : list)
   System.out.println(p.getName() + " " + p.getAge() + "  " + p.getSalary());
  
 }

 private static List<Person> generateList() {
  List<Person> mylist = new ArrayList<>();
  Person p1 = new Person();
  p1.setAge(25);
  p1.setName("ABHishek");
  p1.setSalary(5250);
  
  Person p2 = new Person();
  p2.setAge(26);
  p2.setName("pqww");
  p2.setSalary(5252);
  
  Person p3 = new Person();
  p3.setAge(29);
  p3.setName("ewewe");
  p3.setSalary(6525);
  
  mylist.add(p1);
  mylist.add(p2);
  mylist.add(p3);
  return mylist;
 }

}

Post Comments And Suggestions !!!