Tuesday 29 September 2015

LDAP(Lightweight Directory Access Protocol)

LDAP is mostly used by medium-to-large organi­zations.

"LDAP-aware" client programs can ask LDAP servers to look up entries in a wide variety of ways. LDAP servers index all the data in their entries, and "filters" may be used to select just the person or group you want, and return just the information you want.

LDAP is used to look up encryption certificates, pointers to printers and other services on a network, and provide "single signon" where one password for a user is shared between many services. LDAP is appropriate for any kind of directory-like information, where fast lookups and less-frequent updates are the norm.

As a protocol, LDAP does not define how programs work on either the client or server side. It defines the "language" used for client programs to talk to servers (and servers to servers, too). On the client side, a client may be an email program, a printer browser, or an address book. The server may speak only LDAP, or have other methods of sending and receiving data—LDAP may just be an add-on method.

If you have an email program (as opposed to web-based email), it probably supports LDAP. Most LDAP clients can only read from a server. Search abilities of clients (as seen in email programs) vary widely. A few can write or update information, but LDAP does not include security or encryption, so updates usually requre additional protection such as an encrypted SSL connection to the LDAP server.

If you have OS X and access to an LDAP server, you can enter your LDAP account into System Preferences--Internet Accounts. At bottom of the right pane, click Add Other Account, then choose the LDAP account option. This lets Address Book look up info from your server.

LDAP also defines: Permissions, set by the administrator to allow only certain people to access the LDAP database, and optionally keep certain data private. Schema: a way to describe the format and attributes of data in the server. For example: a schema entered in an LDAP server might define a "groovyPerson" entry type, which has attributes of "instantMessageAddress", and "coffeeRoastPreference". The normal attributes of name, email address, etc., would be inherited from one of the standard schemas, which are rooted in X.500 (see below).

LDAP was designed at the University of Michigan to adapt a complex enterprise directory system (called X.500) to the modern Internet. X.500 is too complex to support on desktops and over the Internet, so LDAP was created to provide this service "for the rest of us."

LDAP servers exist at three levels: There are big public servers, large organizational servers at universities and corporations, and smaller LDAP servers for workgroups. Most public servers from around year 2000 have disappeared, although directory.verisign.com exists for looking up X.509 certificates. The idea of publicly listing your email address for the world to see, of course, has been crushed by spam.

While LDAP didn't bring us the worldwide email address book, it continues to be a popular standard for communicating record-based, directory-like data between programs.

Monday 28 September 2015

Application server Vs Web server



An application server is a machine (an executable process running on some machine, actually) that "listens" (on any channel, using any protocol), for requests from clients for whatever service it provides, and then does something based on those requests. (may or may not involve a respose to the client)

A Web server is process running on a machine that "listens" specifically on TCP/IP Channel using one of the "internet" protocols, (http, https, ftp, etc..) and does whatever it does based on those incoming requests... Generally, (as origianly defined), it fetched/generated and returned an html web page to the client, either fetched from a static html file on the server, or constructed dynamically based on parameters in the incoming client request.

Application servers exposes business logic to a client. So its like application server comprises of a set of methods(not necessarily though, can even be a networked computer allowing many to run software on it) to perform business logic. So it will simply output the desired results, not HTML content. (similar to a method call). So it is not strictly HTTP based.

But web servers passes HTML content to web browsers (Strictly HTTP based). Web servers were capable of handling only the static web resources, but the emergence of server side scripting helped web servers to handle dynamic contents as well. Where web server takes the request and directs it to the script (PHP, JSP, CGI scripts, etc.) to CREATE HTML content to be sent to the client. Then web server knows how to send them back to client. BECAUSE that's what a web server really knows.

Having said that, nowadays developers use both of these together. Where web server takes the

java SE 4 to 8 features

New features in Java SE 8

Lambda Expressions
Pipelines and Streams
Date and Time API
Default Methods
Type Annotations
Nashhorn JavaScript Engine
Concurrent Accumulators
Parallel operations
PermGen Error Removed
TLS SNI

New features in Java SE 7

Strings in switch Statement
Type Inference for Generic Instance Creation
Multiple Exception Handling
Support for Dynamic Languages
Try with Resources
Java nio Package
Binary Literals, underscore in literals
Diamond Syntax
Automatic null Handling

New features in Java SE 6

Scripting Language Support
JDBC 4.0 API
Java Compiler API
Pluggable Annotations
Native PKI, Java GSS, Kerberos and LDAP support.
Integrated Web Services.
Lot more enhancements.

New features in J2SE 5.0

Generics
Enhanced for Loop
Autoboxing/Unboxing
Typesafe Enums
Varargs
Static Import
Metadata (Annotations)
Instrumentation

New features in J2SE 1.4

XML Processing
Java Print Service
Logging API
Java Web Start
JDBC 3.0 API
Assertions
Preferences API
Chained Exception
IPv6 Support
Regular Expressions
Image I/O API

XMl Parsing

There are 3 main parsers for which I have given sample code:
DOM Parser
SAX Parser
StAX Parser

Warning
DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. Please consider SAX parser as solution for it, SAX is faster than DOM and use less memory.


Example on DOM parsing :

my.xml

<?xml version="1.0"?>
<company>
<staff id="1001">
<firstname>nag</firstname>
<lastname>R</lastname>
<nickname>King</nickname>
<salary>100000</salary>
</staff>
<staff id="2001">
<firstname>sang</firstname>
<lastname>lee</lastname>
<nickname>lee</nickname>
<salary>200000</salary>
</staff>
</company>



import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

  public static void main(String argv[]) {

    try {

File fXmlFile = new File("my.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("staff");

System.out.println("----------------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

System.out.println("\nCurrent Element :" + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("id : " + eElement.getAttribute("id"));
System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

}
}
    } catch (Exception e) {
e.printStackTrace();
    }
  }

}

Friday 25 September 2015

String vs StringBuffer vs StringBuilder

String

String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed.

String  demo = " hi " ;

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hi") ;
// The above object stored in heap and its value can be changed .
demo1.Append(" king! ")
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe .


StringBuilder demo2= new StringBuilder("Hi");
// The above object is stored in the heap and its value can be modified
demo2=new StringBuilder("end");
// Above statement is right as it modifies the value which is allowed in the StringBuilder

import java.lang.*;

public class test {

   public static void main(String[] args) {

   StringBuilder str = new StringBuilder("hi ");
   System.out.println("string = " + str);
 
   // appends the string argument to the StringBuilder
   str.append("king!");
   // print the StringBuilder after appending
   System.out.println("After append = " + str);
 
 
   }
}

output :

string = hi
After append = hi king!


Conclusion :

string vs string biffer vs string builder ?

string string immutable ,

Why string objects are immutable in java?

Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.



JSON Parsing

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/** Program to parse data from json file**/


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

JSONParser parser = new JSONParser();

try {

Object obj = parser.parse(new FileReader("<file location>"));

JSONObject jsonObject = (JSONObject) obj;

String name = (String) jsonObject.get("name");
System.out.println(name);

long age = (Long) jsonObject.get("age");
System.out.println(age);

// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}

     }

}

JAXB


jaxb
stands for Java Architecture for XML Binding. It provides mechanism to marshal (write) java objects into XML and unmarshal (read) XML into object. Simply, you can say it is used to convert java object into xml and vice-versa.




@XmlRootElement specifies the root element for the xml document.

@XmlAttribute specifies the attribute for the root element.


@XmlElement specifies the sub element for the root element.

Java pojo:

import javax.xml.bind.annotation.XmlAttribute;  
import javax.xml.bind.annotation.XmlElement;  
import javax.xml.bind.annotation.XmlRootElement;  
  
@XmlRootElement  
public class Profile{  
    private int id;  
    private String name;  
  
public Profile() {}  
public Profile(int id, String name) {  
    super();  
    this.id = id;  
    this.name = name;  
}  
@XmlAttribute  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
@XmlElement  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}    

}  


ObjectToXml.java::


import java.io.FileOutputStream;  
  
import javax.xml.bind.JAXBContext;  
import javax.xml.bind.Marshaller;  
  
  
public class ObjectToXml {  
public static void main(String[] args) throws Exception{  
    JAXBContext contextObj = JAXBContext.newInstance(Profile.class);  
  
    Marshaller marshallerObj = contextObj.createMarshaller();  
    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
  
    Profile p1=new Profile(1,"Vimal Jaiswal");  
      
    marshallerObj.marshal(p1, new FileOutputStream("profile.xml"));  
       
}  
}  


xml to object::

import java.io.File;  
import javax.xml.bind.JAXBContext;  
import javax.xml.bind.JAXBException;  
import javax.xml.bind.Unmarshaller;  
  
public class XMLToObject {  
public static void main(String[] args) {  
     try {    
            File file = new File("profile.xml");    
            JAXBContext jaxbContext = JAXBContext.newInstance(Profile.class);    
         
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();    
            Profile p=(Profile) jaxbUnmarshaller.unmarshal(file);    
            System.out.println(p.getId()+" "+p.getName());  
              
          } catch (JAXBException e) {e.printStackTrace(); }    
         
}  

}  




Thursday 24 September 2015

Exceptions

Exception :
Exception is an abnormal condition.


Types of Exception :
1.Checked Exception
2.Unchecked Exception
3.Error

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Exception Handling Keywords

There are 5 keywords used in java exception handling.

try
catch
finally
throw
throws

Example :
Try {
// logic it may throw exception
}Catch(Exception e){
System.out.println(e.getMessage());
}




Collection:

Collection:

Collection represents a single unit of objects i.e. a group.

framework :

readymade architecture.represents set of classes and interface.


Collection framework :

Collection framework represents a unified architecture for storing and manipulating group of objects. It has:

Interfaces and its implementations i.e. classes,Algorithm


ArrayList class
LinkedList class
ListIterator interface
HashSet class
LinkedHashSet class
TreeSet class
PriorityQueue class
Map interface
HashMap class
LinkedHashMap class
TreeMap class
Hashtable class
Sorting
Comparable interface
Comparator interface
Properties class in Java



Variables and keywords

Variables:

Static Variable
Static variables belong to a class and not to any individual instance. The concept of serialization is concerned with the object’s current state. Only data associated with a specific instance of a class is serialized, therefore static member fields  are ignored during serialization.

Transient Variable
While serialization if you don’t want to save state of a variable. You have to mark that variable as Transient. Environment will know that this variable should be ignored and will not save the value of same.


Final :

Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.

class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}

Finally :

Finally is used to place important code, it will be executed whether exception is handled or not.

class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}


Finalize :

Finalize is used to perform clean up processing just before object is garbage collected.

class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}

JDK vs JRE vs JVM

JDK (Java Development Kit)
It contains everything that will be required to develop and run any Java Application.

JRE (Java Run time Environment)
It contains everything required to run any Java Application which is already compiled. It doesn’t contain library which is required to develope java application.

JVM (Java Virtual Machine)
It is a virtual machine which work over your operating system to provide proper environment for your compiled Java code. JVM only works with bytecode. Hence you need to compile your java application(.java) so that it can be converted to bytecode format (.class file). Which then will be used by JVM to run application. JVM only provide environment it needs other library to run application properly.



java

JAVA :
Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform

Java is:
Object Oriented,Platformindependent,simple,Secure,Robust,Multithreaded,
Dynamic,High Performance

publci class MyfirstProgram{
 public static void main(String arg[]){
   System.out.println("hi King!!");
}
}

To compile: javac  MyfirstProgram.java
To run java program : java MyfirstProgram