Tuesday, 29 December 2015

SAP ABAP Interview Questions & Answers for Freshers

1)      What is SAP ABAP?
Ans: ABAP (Advanced Whsiness Application Programming) is a high level programming language created by the German software company SAP. It is currently positioned as the language for programming SAP's Web Application Server, part of its NetWeaver platform for building business applications. Its syntax is somewhat similar to COBOL.

2) What is SAP ABAP Data Dictionary?
Ans: To describe the logical structures of the objects that are used in application development ABAP 4 data dictionary is used.  It is also used to show the underlying relational database in tables.

Saturday, 21 November 2015

Configure MongoDB with Kerberos Authentication on Linux

In my previous blog I explained MongoDB functionality, now configure it with Kerberos Authentication on Linux machine.
Make sure authenticationMechanism always be "GSSAPI". In case of without Kerberos authenticationMechanism always be "PLAIN".

Following steps need to follow:

Step1: Start mongod without Kerberos.

For the initial addition of Kerberos users, start mongod without Kerberos support.
If a Kerberos user is already in MongoDB and has the privileges required to create a user, you can start mongod with Kerberos support.

Step2: Connect to mongod.

Connect via the mongo shell to the mongod instance. If mongod has --auth enabled, ensure you connect with the privileges required to create a user.

Step3: Add Kerberos Principal(s) to MongoDB.

Add a Kerberos principal, <username>@<KERBEROS REALM> or <username>/<instance>@<KERBEROS REALM>, to MongoDB in the $external database. Specify the Kerberos realm in all uppercase. The $external database allows mongod to consult an external source (e.g. Kerberos) to authenticate. To specify the user’s privileges, assign roles to the user.
The following example adds the Kerberos principal application/reporting@EXAMPLE.NET with read-only access to the records database:


Example:

use $external
db.createUser(
   {
     user: "application/krishnachourasiya@TECHSPACE.COM",
     roles: [ { role: "read", db: "records" } ]
   }
)

Add additional principals as needed. For every user you want to authenticate using Kerberos, you must create a corresponding user in MongoDB. For more information about creating and managing users, see User Management Commands.

Step4: Start mongod with Kerberos support.

To start mongod with Kerberos support, set the environmental variable KRB5_KTNAME to the path of the keytab file and the mongod parameter authenticationMechanisms to GSSAPI in the following form:
Example:
 
env KRB5_KTNAME=/opt/mongodb/mongod.keytab \
/opt/mongodb/bin/mongod --auth \
--setParameter authenticationMechanisms=GSSAPI \
--dbpath /opt/mongodb/data

The path to your mongod as well as your keytab file may differ. Modify or include additional mongod options as required for your configuration. The keytab file must be only accessible to the owner of the mongod process.

Step5: Connect mongo shell to mongod and authenticate.

Connect the mongo shell client as the Kerberos principal application/krishnachourasiya@TECHSPACE.COM. Before connecting, you must have used Kerberos’s kinit program to get credentials for application/krishnachourasiya@TECHSPACE.COM.


 You can connect and authenticate from the command line.

 mongo --authenticationMechanism=GSSAPI --authenticationDatabase='$external' \ --username application/krishnachourasiya@TECHSPACE.COM

 Or, alternatively, you can first connect mongo to the mongod, and then from the mongo shell, use the db.auth() method to authenticate in the $external database.

use $external
db.auth( { mechanism: "GSSAPI", user: "application/krishnachourasiya@TECHSPACE.COM" } )









Monday, 16 November 2015

Core Java Basics - Interview Questions & Answers for Freshers

Q1. What all OOPs principles available in Java?
Ans: Inheritence, Polymorphism, Incapsulation.
Q2. What is the difference between a constructor and a method?
Ans: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q3. What is an abstract class?
Ans: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie. you may not call its constructor), abstract class may contain static data.
Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Q4.  What is the difference between an Interface and an Abstract class?
Ans: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.
An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q5. Explain different way of using thread?
Ans: The thread could be implemented by using Runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance, the only interface can help.

Q6. Is it possible to overload main() method of a class?
 Ans:Yes, we can overload main() method as well. But every time public static main(String[] args) will be called automatically by JVM. Other methods need to call explicitly. But you can't override main().

Q7. Can we inherit the constructors?
Ans: No, we cannot inherit constructors. We can call super class constructors from subclass constructor by using super() call.

Q8. What is the purpose of garbage collection in Java, and when is it used?
Ans: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused.
A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.


Q9. What is the base class of all classes?
Ans: java.lang.Object

Q10. What is platform?
Ans: A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software and hardware. Java provides software-based platform.
   
Q11. What is method overloading?
Ans: Method overloading is a type of polymorphism that includes two or more methods with the same name in same class but, the condition is that it should have different arguments, otherwise an error might occur. This method overloading is very advantageous, as it allows you to implement many methods with the same syntax and semantics. The Overloaded methods that should follow the criteria are as follows:
  • Overloaded methods can change the return type and access modifier
  • Overloaded methods can declare new or broader checked exceptions
  • A method can be overloaded in the same class or in a subclass
Q12. What is method overriding?
ANS: Method overriding is a type of polymorphism that is different from the overloading method, as it allows you to declare the method with the same arguments. The advantage of using this is that it defines the behavior of the specific subclass. It doesn’t provide very strict restrictive access modifier. The method that marked as public and protected can’t be overridden. You also cannot override a method marked final and static.

Q13. What is super?
Ans: "super" is a keyword used in Java language. This keyword is used to access the method and member variables of the super-class. It can refer the member or the hidden variable of the super-class. It can also invoke the overridden method. "super" should be used to access the hidden variable and it should be the first keyword written in the constructor.

Q14. How static variable work in java? 
Ans: Static keyword/variable in java -
  1. Each class has one copy of each of its static members in memory.
  2. Each instance of the class has access to that single static memory location.
  3. The single member is same for every instance.
  4. Static member does not have access to instance members. 
  5. Static code is loaded before the class is instantiated and stays in memory until the JVM exits as opposed to instance variable which are loaded and unloaded which is called “Dynamic” code.

Q15. What is ClassLoader in Java?
 Ans: When a Java program is converted into .class file by Java Compiler  which is collection of byte code  class loader is responsible to load that class file from file system,network or any other location. This class loader is nothing but also a class from which location they are loading the class according to that class loaders are three types :
  1.Bootstrap
  2.Extension
  3.System class loader.

Q16: What is Contract between hashcode and equal method?
 Ans : It is very important to understand the contract between equals and hashcode. The general contract of hashCode is.
Whenever hashCode method is invoked on the same object more than once during the execution of the application, the hashCode method consistently return same integer value.  
  •  If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object)method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.


MongoDB Interview Questions - Click Here

MongoDB - Interview Questions/Answers - MongoDB


Q1. What do you understand by NoSQL databases? Is MongoDB a NoSQL database? Explain.
Ans: At the present time, the internet is loaded with big data, big users, big complexity etc. and also becoming more complex day by day. NoSQL is answer of all these problems, It is not a traditional database management system, not even a relational database management system (RDBMS). NoSQL stands for "Not Only SQL". NoSQL is a type of database that can handle and sort all type of unstructured, messy and complicated data. It is just a new way to think about the database.
Yes. MongoDB is a NoSQL database.

Q2. Explain - what is MongoDB?
Ans: Mongo-DB is a document database which provides high performance, high availability and easy scalability.

Q3. What is the difference between MongoDB and MySQL?
Ans: Although MongoDB and MySQL both are free and open source databases, there is a lot of difference between them in the term of data representation, relationship, transaction, querying data, schema design and definition, performance speed, normalization and many more. To compare MySQL with MongoDB is like a comparison between Relational and Non-relational databases.

MongoDb is the best NoSQL database because, it is:
  1. Document Oriented
  2. Rich Query language
  3. High Performance
  4. Highly Available
  5. Easily Scalable
Q4. What is a Namespace in MongoDB? Explain.
Ans: MongoDB stores BSON (Binary Interchange and Structure Object Notation) objects in the collection. The concatenation of the collection name and database name is called a namespace.
Namespace is a concatenation of the database name and the collection name. Collection, in which MongoDB stores BSON objects.

Q5. What is sharding in MongoDB?
Ans: The procedure of storing data records across multiple machines is referred as Sharding. It is a MongoDB approach to meet the demands of data growth. It is the horizontal partition of data in a database or search engine. Each partition is referred as shard or database shard.

Q6. Explain what is a replica set? And how it works?
Ans: A replica set is a group of mongo instances that host the same data set. In replica set, one node is primary, and another is secondary. From primary to the secondary node all data replicates. Across multiple servers, the process of synchronizing data is known as replication. It provides redundancy and increase data availability with multiple copies of data on different database server. Replication helps in protecting the database from the loss of a single server. 

Q7. While creating Schema in MongoDB what are the points need to be taken in consideration?
Ans: Points need to be taken in consideration are -

• Design your schema according to user requirements
• Combine objects into one document if you use them together. Otherwise, separate them
• Do joins while write, and not when it is on read
• For most frequent use cases optimize your schema
• Do complex aggregation in the schema
 
Q8. Explain what is the role of profiler in MongoDB?
Ans: MongoDB database profiler shows performance characteristics of each operation against the database. You can find queries using the profiler that are slower than they should be.  

Q9. Explain what are indexes in MongoDB?
Ans: Indexes are special structures in MongoDB, which stores a small portion of the data set in an easy to traverse form. Ordered by the value of the field specified in the index, the index stores the value of a specific field or set of fields.

Q10. Mention what is the basic syntax to use index in MongoDB?
Ans: The basic syntax to use in MongoDB is >db.COLLECTION_NAME.ensureIndex ( {KEY:1} ). In here the key is the name of the file on which you want to create an index, where 1 is for ascending order while you use -1 for descending order.   


Thursday, 12 November 2015

Angular JS - Controllers

Understanding Controllers

A Controller is defined by a JavaScript constructor function that is used to augment the Angular Scope.
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope.

In general, a Controller shouldn't try to do too much. It should contain only the business logic needed for a single view.The most common way to keep Controllers slim is by encapsulating work that doesn't belong to controllers into services and then using these services in Controllers via dependency injection. We can associate Controllers with scope objects implicitly via the ngController directive or $route service.

If the controller has been attached using the controller as syntax then the controller instance will be assigned to a property on the new scope.

Use Controllers TO:
  • Set up the initial state of the $scope object.
  • Add behavior to the $scope object.

Do not use Controllers To: 
  • Manipulate DOM — Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.
  • Format input — Use angular form controls instead.
  • Filter output — Use angular filters instead.
  • Share code or state across controllers — Use angular services instead.
  • Manage the life-cycle of other components (for example, to create service instances).

Initial State of $scope Object - 
The following example demonstrates creating a MessageController, which attaches a message property containing the string 'Hello Krishna!' to the $scope:

var myApp = angular.module('myApp',[]);

myApp.controller('MessageController', ['$scope', function($scope) {
  $scope.message= 'Hello Krishna!';
}]);
 
We create an Angular Module, myApp, for our application. Then we add the controller's constructor function to the module using the .controller() method. This keeps the controller's constructor function out of the global scope.

We attach our controller to the DOM using the ng-controller directive. The message property can now be data-bound to the template:

<div ng-controller="MessageController">
  {{ message}}
</div>

 NOTE: We have used an inline injection annotation to explicitly specify the dependency of the Controller on the $scope service provided by Angular.

Simple Spicy Controller Example

The message in our template contains a binding to the spice model which, by default, is set to the string "very". Depending on which button is clicked, the spice model is set to chili or jalapeño, and the message is automatically updated by data-binding.

Create one HTML page and replace <head> and <body>
Create one js file of named app.js at the same location



HTML
<head>
  <meta charset="UTF-8">
  <title>Example - 1</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
  <script src="app.js"></script>
</head>
<body ng-app="spicyApp1">
  <div ng-controller="SpicyController">
 <button ng-click="chiliSpicy()">Chili</button>
 <button ng-click="jalapenoSpicy()">Jalapeño</button>
 <p>The food is {{spice}} spicy!</p>
</div>
</body>

JS
var myApp = angular.module('spicyApp1', []);
myApp.controller('SpicyController', ['$scope', function($scope) {
    $scope.spice = 'very';

    $scope.chiliSpicy = function() {
        $scope.spice = 'chili';
    };

    $scope.jalapenoSpicy = function() {
        $scope.spice = 'jalapeño';
    };
}]);


Things to notice in the example above:
  • The ng-controller directive is used to (implicitly) create a scope for our template, and the scope is managed by the SpicyController Controller.
  • SpicyController is just a plain JavaScript function. As an (optional) naming convention the name starts with capital letter and ends with "Controller".
  • Assigning a property to $scope creates or updates the model.
  • Controller methods can be created through direct assignment to scope 
  • The Controller methods and properties are available in the template (for both the <div> element and its children).
Spicy Arguments Controller Example -
Controller methods can also take arguments, as demonstrated in below example

HTML
<div ng-controller="SpicyController">
 <input ng-model="customSpice">
 <button ng-click="spicy('chili')">Chili</button>
 <button ng-click="spicy(customSpice)">Custom spice</button>
 <p>The food is {{spice}} spicy!</p>
</div>

JShttps://www.blogger.com/blogger.g?blogID=7975656151796446109#editor/target=post;postID=5935261620062027429;onPublishedMenu=allposts;onClosedMenu=allposts;postNum=0;src=postname
var myApp = angular.module('spicyApp2', []);
myApp.controller('SpicyController', ['$scope', function($scope) {
    $scope.customSpice = "wasabi";
    $scope.spice = 'very';

    $scope.spicy = function(spice) {
        $scope.spice = spice;
    };
}]);

NOTE: SpicyController Controller now defines just one method called spicy, which takes one argument called spice. The template then refers to this Controller method and passes in a string constant 'chili' in the binding for the first button and a model property customSpice (bound to an input box) in the second button.


Scope Inheritance Controller Example 
Since the ng-controller directive creates a new child scope, we get a hierarchy of scopes that inherit from each other. The $scope that each Controller receives will have access to properties and methods defined by Controllers higher up the hierarchy. See Understanding Scopes for more information about scope inheritance.


 HTML
<div class="spicy">
  <div ng-controller="MainController">
    <p>Good {{timeOfDay}}, {{name}}!</p>

    <div ng-controller="ChildController">
      <p>Good {{timeOfDay}}, {{name}}!</p>

      <div ng-controller="GrandChildController">
        <p>Good {{timeOfDay}}, {{name}}!</p>
      </div>
    </div>
  </div>
</div>


JS
var myApp = angular.module('scopeInheritance', []);
myApp.controller('MainController', ['$scope', function($scope) {
  $scope.timeOfDay = 'morning';
  $scope.name = 'Nikki';
}]);
myApp.controller('ChildController', ['$scope', function($scope) {
  $scope.name = 'Mattie';
}]);
myApp.controller('GrandChildController', ['$scope', function($scope) {
  $scope.timeOfDay = 'evening';
  $scope.name = 'Gingerbread Baby';
}]);


 CSS
div.spicy div {
  padding: 10px;
  border: solid 2px blue;
}

Notice how we nested three ng-controller directives in our template. This will result in four scopes being created for our view:
  • The root scope
  • The MainController scope, which contains timeOfDay and name properties
  • The ChildController scope, which inherits the timeOfDay property but overrides (hides) the name property from the previous
  • The GrandChildController scope, which overrides (hides) both the timeOfDay property defined in MainController and the name property defined in ChildController
Inheritance works with methods in the same way as it does with properties. So in our previous examples, all of the properties could be replaced with methods that return string values.

Angular JS - Data Binding

One of the main power of Angular JS is Data Binding. Data-binding in Angular apps is the automatic synchronization of data between the model and view components. The way that Angular implements data-binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. When the model changes, the view reflects the change, and vice versa.

Types of Data Binding -
One Way -
Most of the systems bind data in only one direction: They merge template and model components together into a view. After the merge occurs, changes to the model or related sections of the view are NOT automatically reflected in the view. Worse, any changes that the user makes to the view are not reflected in the model. This means that the developer has to write code that constantly syncs the view with the model and the model with the view.
 


Two Way - 
Angular templates work differently. First the template (which is the uncompiled HTML along with any additional markup or directives) is compiled on the browser. The compilation step produces a live view. Any changes to the view are immediately reflected in the model, and any changes in the model are propagated to the view. The model is the single-source-of-truth for the application state, greatly simplifying the programming model for the developer. You can think of the view as simply an instant projection of your model.
Because the view is just a projection of the model, the controller is completely separated from the view and unaware of it. 

Angular JS Tutorial

AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0. It is an open source web application framework maintained by google.
Sample Code:

<!doctype html>
<html ng-app>
   
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/
1.3.3/angular.min.js"></script>
   </head>
   
   <body>
      <div>
         <label>Name:</label>
         <input type = "text" ng-model = "yourName" placeholder = "Enter a name here">
         <hr />
         
         <h1>Hello {{yourName}}!</h1>
      </div>
      
   </body>
</html>

 
Advantages -
  • AngularJS provides capability to create Single Page Application in a very clean and maintainable way.
  • AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience
  • AngularJS code is unit testable.
  • AngularJS uses dependency injection and make use of separation of concerns.
  • AngularJS provides reusable components.
  • With AngularJS, developer write less code and get more functionality.
  • In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing.
Disadvantages - 
  • Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure.
  • Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more.
 Components -
  • ng-app − This directive defines and links an AngularJS application to HTML.
  • ng-model − This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind − This directive binds the AngularJS Application data to HTML tags.
  
Core Features - 
  • Data-binding − It is the automatic synchronization of data between model and view components.
  • Scope − These are objects that refer to the model. They act as a glue between controller and view.
  • Controller − These are JavaScript functions that are bound to a particular scope.
  • Services − AngularJS come with several built-in services for example $http to make a XMLHttpRequests. These are singleton objects which are instantiated only once in app.
  • Filters − These select a subset of items from an array and returns a new array.
  • Directives − Directives are markers on DOM elements (such as elements, attributes, css, and more). These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ngBind, ngModel...)
  • Templates − These are the rendered view with information from the controller and model. These can be a single file (like index.html) or multiple views in one page using "partials".
  • Routing − It is concept of switching views.
  • Model View Whatever − MVC is a design pattern for dividing an application into different parts (called Model, View and Controller), each with distinct responsibilities. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel). The Angular JS team refers it humorously as Model View Whatever.
  • Deep Linking − Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.
    Dependency Injection − AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test. 

Wednesday, 11 November 2015

ClassLoader in Java

Class loaders in Java used to load class. It works on 3 principles -
  1. Delegation - Delegation principle forward request of class loading to parent class loader and only loads the class, if parent is not able to find or load class.
  2. Visibility - It allows child class loader to see all the classes loaded by parent ClassLoader, but parent class loader can not see classes loaded by child.
  3. Uniqueness - Uniqueness principle allows to load a class exactly once, which is basically achieved by delegation and ensures that child ClassLoader doesn't reload the class already loaded by parent.
What is ClassLoader in Java?
ClassLoader in Java is a class which is used to load class files in Java. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file. ClassLoader is responsible for loading class files from file system, network or any other source. There are three default class loader used in Java, Bootstrap , Extension and System or Application class loader.

1) Bootstrap ClassLoader - JRE/lib/rt.jar
2) Extension ClassLoader - JRE/lib/ext or any directory denoted by java.ext.dirs
3) Application ClassLoader - CLASSPATH environment variable, -classpath or -cp option, Class-Path attribute of Manifest inside JAR file.


How ClassLoader in Java?
Please refer below diagram - It mainly work on above listed 3 principles -
 
Delegation principles
 When a class is loaded and initialized in Java, a class is loaded in Java, when its needed. Suppose you have an application specific class called Krishna.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader. Primordial will look for that class in rt.jar and since that class is not there, request comes to Extension class loader which looks on jre/lib/ext directory and tries to locate this class there, if class is found there than Extension class loader will load that class and Application class loader will never load that class but if its not loaded by extension class-loader than Application class loader loads it from Classpath in Java. Remember Classpath is used to load class files while PATH is used to locate executable like javac or java command.
Visibility Principle
According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true. Which mean if class Abc is loaded by Application class loader than trying to load class ABC explicitly using extension ClassLoader will throw either java.lang.ClassNotFoundException. as shown in below Example
Example:
package krishna;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to demonstrate How ClassLoader works in Java,
 * in particular about visibility principle of ClassLoader.
 *
 * @author Krishna Kumar Chourasiya
 */


public class ClassLoaderTestKrishna {
 
    public static void main(String args[]) {
        try {         
            //printing ClassLoader of this class
            System.out.println("ClassLoaderTestKrishna.getClass().getClassLoader() : "

                                 + ClassLoaderTestKrishna.class.getClassLoader());

         
            //trying to explicitly load this class again using Extension class loader
            Class.forName("krishna.ClassLoaderTest", true 

                            ,  ClassLoaderTestKrishna.class.getClassLoader().getParent());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ClassLoaderTestKrishna.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Output:
ClassLoaderTestKrishna.getClass().getClassLoader() : sun.misc.Launcher$AppClassLoader@601bb1
11/11/2015 2:43:48 AM krishna.ClassLoaderTestKrishna main
SEVERE: null
java.lang.ClassNotFoundException: krishna.ClassLoaderTestKrishna
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:247)
        at test.ClassLoaderTest.main(ClassLoaderTestKrishna.java:29)

Uniqueness Principle
According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again. Though its completely possible to write class loader which violates Delegation and Uniqueness principles and loads class by itself, its not something which is beneficial. You should follow all  class loader principle while writing your own ClassLoader.

MongoDB - Connection from Remote Database

MongoDB - Connection from  Remote Database

There are multiple ways of doing this things, but I found this one is most suitable.

1. From Standalone
2. From Web Application

Make sure you have added correct maven dependency in your pom.xml like below -
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
 

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

 

Web Application - 

Before to use below code, please add property file having credentials and all other required details in it. Read that property file in spring-config.xml. You can use below code to read the property file -
<context:property-placeholder location='classpath:/config/configTest.properties'/>
configTest.properties
mongodb.dbname=
mongodb.host=
mongodb.port=
mongodb.username=
mongodb.password=
mongodb.authenticationdatabase=

Now below code will take the responsibility to get connected from mongodb host.

@Configuration
public class MongoConfiguration extends AbstractMongoConfiguration{
@Value("${mongodb.dbname}")
private String  dbName;

@Value("${mongodb.host}")
private String  host;

@Value("${mongodb.port}")
private Integer port;

@Value("${mongodb.username}")
private String  userName;

@Value("${mongodb.password}")
private String  password;

@Value("${mongodb.authenticationdatabase}")
private String  authenticationDatabase;

@Override
protected String getDatabaseName()  {
    return this.dbName;
}

@Override
public MongoClient mongo() throws Exception {
    List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
    ServerAddress address = new ServerAddress(host, port);
    serverAddresses.add(address);
    List<MongoCredential> credentials = new ArrayList<MongoCredential>();
    MongoCredential credential = MongoCredential.createPlainCredential(userName, authenticationDatabase, password.toCharArray());
    credentials.add(credential);
    return new MongoClient(serverAddresses, credentials);
}

@Override
@Bean
public SimpleMongoDbFactory mongoDbFactory() throws Exception {
    return new SimpleMongoDbFactory(mongo(), getDatabaseName());
}

@Override
@Bean
public MongoTemplate mongoTemplate() throws Exception {

    final MongoTemplate mongoTemplate = new MongoTemplate(mongo(), getDatabaseName());
    mongoTemplate.setWriteConcern(WriteConcern.SAFE);
    return mongoTemplate;
}


Standalone Java Program -

A standalone Java Program which tells about how to connect with remote MongoDB server from Java Code.

    String database = "TestDev";
    String username = "user@test.COM";
    String pass = "XXXXX";
    char[] password = pass.toChogram arArray();

    try {
        List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
        ServerAddress address = new ServerAddress("hostname", portnumber);
        serverAddresses.add(address);
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        MongoCredential credential = MongoCredential.createPlainCredential(username, "$external", password);
        credentials.add(credential);
        MongoClient mongoClient1 = new MongoClient(serverAddresses, credentials);
        DB db = mongoClient1.getDB(database);
        System.out.println(db.getCollectionNames());
        System.out.println("Done");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }



Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...