Friday, October 25, 2013

HIBERNATE


What is Hibernate:

Hibernate is the ORM tool given to transfer the data between a java (object) application and a database (Relational) in the form of the objects.  Hibernate is the open source light weight tool given by Gavin King, actually JBoss server is also created by this person only.
Hibernate is a non-invasive framework,  means it wont forces the programmers to extend/implement any class/interface, and in hibernate we have all POJO classes so its light weight.
Hibernate can runs with in or with out server, i mean it will suitable for all types of java applications (stand alone or desktop or any servlets bla bla.)
Hibernate is purely for persistence (to store/retrieve data from Database).

Advantages of hibernates:

  • Hibernate supports InheritanceAssociationsCollections
  • In hibernate if we save the derived class object,  then its base class object will also be stored into the database, it means hibernate supporting inheritance
  • Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One
  • This will also supports collections like List,Set,Map (Only new collections)
  • In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in hibernate we only have Un-checked exceptions, so no need to write try, catch, or no need to write throws.  Actually in hibernate we have the translator which converts checked to Un-checked ;)
  • Hibernate has capability to generate primary keys automatically while we are storing the records into database
  • Hibernate has its own query language, i.e hibernate query language which is database independent
  • So if we change the database, then also our application will works as HQL is database independent
  • HQL contains database independent commands
  • While we are inserting any record, if we don’t have any particular table in the database, JDBC will rises an error like “View not exist”, and throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us ;)
  • Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.
  • Hibernate supports annotations, apart from XML
  • Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods provided by that API.
  • Getting pagination in hibernate is quite simple.

Disadvantages of hibernates:

  • I don’t think there are disadvantages in hibernate
  • You know some thing.., Its saying hibernate is little slower than pure JDBC, actually the reason being hibernate used to generate many SQL statements in run time, but i guess this is not the disadvantage :-)
  • But there is one major disadvantage, which was boilerplate code issue, actually we need to writesame code in several files in the same application, but spring eliminated this.

Configuration:

Configuration is the file loaded into an hibernate application when working with hibernate, this configuration file contains 3 types of information..
  • Connection Properties
  • Hibernate Properties
  • Mapping file name(s)
We must create one configuration file for each database we are going to use, suppose if we want to connect with 2 databases, like OracleMySql, then we must create 2 configuration files.

Syntax Of Configuration xml:



Steps To Use Hibernate In Any Java Application


Whether the java application will run in the server or without server, and the application may be desktop or stand alone, swing, awt, servlet…what ever, but the steps are common to all.

In order to work with hibernate we don’t required any server as mandatory but we need hibernate software (.jar(s) files).

Follow The Steps:


1. Import the hibernate API, they are many more, but these 2 are more than enough…

import org.hibernate.*;
import org.hibernate.cfg.*;

2. Among ConfigurationMapping xml files, first we need to load configuration xml, because once we load the configuration file, automatically mapping file will be loaded as we registered this mapping xml in the configuration file.

So to load configuration xml, we need to create object of Configuration class, which is given inorg.hibernate.cfg.*;  and we need to call configure() method in that class, by passing xml configuration file name as parameter.
Eg:
Configuration cf = new Configuration();
cf.configure(“hibernate.cfg.xml”);
Hear our configuration file name is your choice, but by default am have been given hibernate.cfg.xml,  so once this configuration file is loaded in our java app, then we can say that hibernate environment isstarted in our program.
So once we write the line_ cf.configure(“hibernate.cfg.xml”), configuration object cf will reads this xml file hibernate.cfg.xml, actually internally cf will uses DOM parsers to read the file.
Finally…
  • cf will reads data from hibernate.cfg.xml
  • Stores the data in different variables
  • And finally all these variables are grouped and create one high level hibernate object we can call as SessionFactory object.
  • So Configuration class only can create this SessionFactory object
likeSessionFactory sf =  cf.buildSessionFactory();
Actually SessionFactory is an interface not a class, and SessionFactoryImpl is the implimented class for SessionFactory, so we are internally creating object of SessionFactoryImpl class and storing in the interface reference, so this SessionFactory object sf contains all the data regarding the configuation file so we can call sf as heavy weight object.
3. Creating an object of session,
  • Session is an interface and SessionImpl is implemented class, both are given in org.hibernate.*;
  • When ever session is opened then internally a database connection will be opened, in order to get a session or open a session we need to call openSession() method in SessionFactory, it means SessionFactory produces sessions.
Session session = sf.openSession();
sf = SessfionFactory object
4. Create a logical transaction
While working with insertupdatedelete, operations from an hibernate application onto the database then hibernate needs a logical Transaction, if we are selecting an object from the database then we donot require any logical transaction in hibernate.  In order to begin a logical transaction in hibernate then we need to call a method beginTransaction() given by Session Interface.
Transaction tx = session.beginTransaction();
session is the object of Session Interface
5. Use the methods given by Session Interface,  to move the objects from application to database and  from database to application
session .save(s)-Inserting object ‘s’ into database
session.update(s)-Updating object ‘s’ in the database
session.load(s)-Selecting objcet ‘s’ object
session.delete(s)-Deletig object ‘s’ from database
  • So finally we need to call commit() in Transaction, like tx.commit();
  • As i told earlier,  when we open session a connection to the database will be created right, so we must close that connection as session. close().
  • And finally close the SessionFactory as sf.close()
  • That’s it.., we are done.
Final flow will be______________
Configuration
SessionFactory
Session
Transaction
Close Statements


Transient, Persistent, Detaiched States

1.Transient State:
A New instance of  a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate:


UserDetail user = new UserDetail();
user.setUserName("Dinesh Rajput");
// user is in a transient state


2. Persistent State:

A persistent instance has a representation in the database , an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session:

Long id = (Long) session.save(user);
// user is now in a persistent state



3. Detached State:

Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn’t attached to a Session anymore (but can still be modified and reattached to a new Session later though).

session.close();
//user in detached state




Hibernate Caching Mechanism, Hibernate Cache


Every fresh session having its own cache memory, Caching is a mechanism for storing the loaded objects into a cache memory.  The advantage of cache mechanism is, whenever again we want to load the same object from the database then instead of hitting the database once again, it loads from the local cache memory only, so that the no. of round trips between an application and a database server got decreased.  It means caching mechanism increases the performance of the application.
Caching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance for performance critical applications
In hibernate we have two levels of caching
·         First Level Cache [ or ] Session Cache
·         Second Level Cache [ or ] Session Factory Cache [ or  ] JVM Level Cache


Refer: Hibernate Caching Mecanishm




One-To-One 






Mapping


<many-to-one name="studentAddress"class="com.vaannila.student.Address" column="STUDENT_ADDRESS" not-null="true" cascade="all" unique="true" />

using Annotations 
@Entity
@Table(name = "STUDENT")
public class Student {
   @OneToOne(cascade = CascadeType.ALL)
   public Address getStudentAddress() {
      return this.studentAddress;
   }
   public void setStudentAddress(Address studentAddress) {
      this.studentAddress = studentAddress;
   }
}


 One-To-Many


 



Mapping


<set name="studentPhoneNumbers" table="STUDENT_PHONE" cascade="all">
<key column="STUDENT_ID" />
<many-to-many column="PHONE_ID" unique="true"class="com.vaannila.student.Phone" />
</set>

using Annotations 
@Entity
@Table(name = "STUDENT")
public class Student {

private Set<Phone> studentPhoneNumbers = new HashSet<Phone>(0);
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_PHONE", joinColumns = { @JoinColumn(name ="STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name ="PHONE_ID") })

   public Set<Phone> getStudentPhoneNumbers() {
      return this.studentPhoneNumbers;
   }
   public void setStudentPhoneNumbers(Set<Phone> studentPhoneNumbers) {
      this.studentPhoneNumbers = studentPhoneNumbers;
   }


}

Many-To-One 















Mapping

<many-to-one name="studentAddress"class="com.vaannila.student.Address" column="STUDENT_ADDRESS"cascade="all" not-null="true" />

using Annotations
@Entity
@Table(name = "STUDENT")
public class Student {

private Set<Phone> studentPhoneNumbers = new HashSet<Phone>(0);
@ManyToOne(cascade = CascadeType.ALL)

   public Address getStudentAddress() {
      return this.studentAddress;
   }
   public void setStudentAddress(Address studentAddress) {
      this.studentAddress = studentAddress;
   }


}


Many-To-Many 



Mapping

<set name="courses" table="STUDENT_COURSE" cascade="all">
<key column="STUDENT_ID" />
<many-to-many column="COURSE_ID" class="com.vaannila.student.Course" />
</set>

using Annotations 

@Entity
@Table(name = "STUDENT")
public class Student {
private Set<Course> courses = new HashSet<Course>(0);
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_COURSE", joinColumns = { @JoinColumn(name ="STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name ="COURSE_ID") })

   public Set<Course> getCourses() {
      return this.courses;
   }
   public void setCourses(Set<Course> courses) {
      this.courses = courses;
   }
}




Tuesday, October 22, 2013

Angular JS

ANGULAR JS


  • It is a very good and fully-featured SPA framework.
  • Cool separation of code that I’ll show you and data binding
  • AngularJS is one core library.
  • We have Model-View-Controller concept
  • We have two-way data binding.
  • Built-in routing support
  • If you want to use more advanced stuff you can even use jQuery and they play really nice together: Angular and jQuery.
  • When it comes to data binding we have full support for templates. History’s built in. We can share
  • code through factories and services and other things.
  • We have the concept of data-binding with View Models.

  • Developed by google.
  • Supports static and angular templates
  • Can add custom directives
  • Support RESTful webservices
  • Predefined form validations
  • Supports both client server communication
  • Supports dependency injection
  • Supports animations
  • Event Handlers

key features:

  • scope
  • model
  • view
  • controller
  • service
  • directives
  • filters
  • data binding
  • Routes
  • Factories

Ref:AngularJsPDF


Saturday, October 19, 2013

CXF




<!-- schema location -->

 xmlns:jaxws="http://cxf.apache.org/jaxws" 
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="


http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"


<!-- If we use Cxf, we need to import below files -->
     <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<!-- for soap, we need to import cxf-extension-soap.xml, 
for rest, no need to import any file-->
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>

 
 <!--  Soap calls Endpoint-- >
    <bean id="contactEndPoint" class="Endpoint.ContactEndPointImpl"/>
<jaxws:endpoint id="contactWorld" implementor="#contactEndPoint" address="/ContactEndPoint" />

 <!--  Rest calls Endpoint-- >
<jaxrs:server id="contactRestfulWebService" address="/ContactRestController/">
  <jaxrs:serviceBeans>
    <ref bean="contactController" />
  </jaxrs:serviceBeans>
  </jaxrs:server>




In EndPoint:

@WebService(endpointInterface = "Endpoint.ContactEndPoint",
targetNamespace = "Endpoint",
       serviceName = "ContactEndPointImpl")

JMS


The Java Message Service is a Java API that allows applications to create, send, receive, and read messages.
The JMS API defines a common set of interfaces and associated semantics that allow programs written in the Java programming language to communicate with other messaging implementations.
The JMS API enables communication that is not only loosely coupled but also,
  • Asynchronous: A JMS provider can deliver messages to a client as they arrive; a client does not have to request messages in order to receive them.
  • Reliable: The JMS API can ensure that a message is delivered once and only once. Lower levels of reliability are available for applications that can afford to miss messages or to receive duplicate messages.


import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import javax.jms.Session;

public class AsyncMessageServiceImpl implements MessageService {

private JmsTemplate jmsTemplate;
private Destination destination;

public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}

public void setDestination(Destination destination) {
this.destination = destination;
}

@Override
public void postMessage(final Map<String, Object> aMap) {
jmsTemplate.send(destination, new MessageCreator() {
@SuppressWarnings("unchecked")
public Message createMessage(Session session) throws JMSException {
ObjectMessage objectMessage = session.createObjectMessage();
objectMessage.setObject((HashMap) aMap);
return objectMessage;

}
});
}

}


public class MessageMDB implements MessageListener {
@Override
public void onMessage(Message message) {
Map msg = null;
if (!(message instanceof ObjectMessage)) {
return;
}
ObjectMessage objectMessage = (ObjectMessage) message;
Map<String,String> map=new HashMap<String, String>();
try {
map=(Map<String, String>) objectMessage.getObject();
} catch (JMSException e) {
e.printStackTrace();
}
mailService.sendMail(map);

}
}

//=================================================
java.security.Security
.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

Properties props = new Properties();

// Set the host smtp address
props.put("mail.smtp.host", hostName);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");

Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, passWord);
}
};

javax.mail.Session sess = javax.mail.Session.getInstance(props,
auth);

// boolean debug = false;
// sess.setDebug(debug);

// create a message

MimeMessage msg = new MimeMessage(sess);

  • ConnectionFactory – This is the object a client uses to create a connection with a provider.
  • Destination – This is the object a client uses to specify the destination of messages it is sending and the source of messages it receives.








JMS API Programming









Reference doc

Cairngorm Architecture


Cairngorm Architecture
·         What is cairngorm?
The methology  for breaking up your application code by logical functions.
This is rotune reffered to MVC.

Pieces of Cairngorm:
Model  Locator
View
Front Controller
Command
Delegate
Service

·         Model  Locator:
Stores all of your application’s Value Objects (data) and shared variables,  in one place. Similar to an HTTP Session object, except that its stored client side in the Flex interface instead of server side within a middle tier application server.

·         View:
One or more Flex components (button, panel, combo box, Tile, etc) bundled together as a named unit, bound to data in the Model Locator, and generating custom Cairngorm Events based on user interaction (clicks, rollovers, drag & drop.)

·         Front Controller:
Receives Cairngorm Events and maps them to Cairngorm Commands.

·         Command:
Handles business logic, calls Cairngorm Delegates and/or other Commands, and updates the Value Objects and variables stored in the Model Locator.

·         Delegate:
Created by a Command, they instantiate remote procedure calls (HTTP, Web Services, etc) and hand the results back to that Command.

·         Service:
Defines the remote procedure calls (HTTP, Web Services, etc) to connect to remote data stores.


INPUT  FLOW       View àEvents àControlà CommandàBusiness.
OUTPUT  FLOW   Business à Command àModel.

Security Certificates

  1. Cryptography Basics Understand Key Concepts : Encryption, decryption, hashing, and digital signatures. Key terms: confidentiality, inte...