Friday, December 14, 2012

Android FAQ


Android application on startup
******************************
Also, in
your manifest, define your service and listen for the boot-completed action:




android:name=".receiver.StartMyServiceAtBootReceiver"
android:enabled="true"
android:exported="true"
android:label="StartMyServiceAtBootReceiver">




Then you need to define the receiver that will get the BOOT_COMPLETED action andstart your service.
public class StartMyServiceAtBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent("com.myapp.MySystemService");
context.startService(serviceIntent);
}
}
}
Intent Filters:
******************
Android components like activities can also serve implicit intents. but to do so they have to filter all
implicit intents in order to serve only the intents they desire to serve. this is done using intent filters.
Suppose you want to create an activity that acts as the default dialer activity. You must associate an
intent filter with this activity in order to that this activity serve the dial intents only.
Let’s demonstrate a simple example which is creating an application with one activity that we want to
make it a dialer activity.
Create a new android project, create an activity and name it Dialer.
In the AndroidManifest.xml file of this application add the following to the Dialer activity:





to become:android:label="@string/app_name">










Now what we have done is adding an intent filter to that activity. this intent filter hasthe following properties:
A.Action: the type of implicit intents that this activity responds to. in our case it is the dial action.
higher numbers represent higher priority.
B.Priority: about the priority of that activity over other activities that respond to the same type of
intents.
C.Category: Implicit intents have built-in categories. in order that an implicit intent be captured by our
activity, the implicit intent category must match our activity category.
D.Data: adds data specification scheme to the intent filter.
So if any other application has the following module to launch the dialer:
Intent in=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:000"));
startActivity(in);The user will see the following dialog offering him/her the choice between the
default dialer and our custom dialer.
Layouts in Android
****************
1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View
In a linear layout, like the name suggests, all the elements are displayed in a linear fashion(below is an
example of the linear layouts), either Horizontally or Vertically and this behavior is set in
android:orientation which is an attribute of the node LinearLayout.
In a relative layout every element arranges itself relative to other elements or a parent element.
Android Components :
******************
Indent
Services
Broadcast Receiver
Content Provider
Widget
Intents are asynchronous messages which allow the application to request functionality from other
components of the Android system,
Services perform background tasks without providing a user interface
A ContentProvider provides a structured interface to application data. Via a ContentProvider your
application can share data with other applications. Android contains an SQLite database which is
frequently used in conjunction with a ContentProvider. The SQLite database would store the data,
which would be accessed via the ContentProvider.
BroadcastReceiver can be registered to receive system messages and Intents. A BroadcastReceiver
will get notified by the Android system, if the specified situation happens. For example a
BroadcastReceiver could get called once the Android system completed
the boot process or if a phone call is received.
Widgets are interactive components which are primarily used on the Android homescreen. ex: Weather
Widget
Application shared preferences allows you to save and retrieve key, value pair data. Before getting
into tutorial, I am giving basic information needed to work with shared preferences.
Initialization
Application shared preferences can be fetched using getSharedPreferences() method.You also need an
editor to edit and save the changes in shared preferences. The following code can be used to get
application shared preferences.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private
mode
Editor editor = pref.edit();
Storing Data
You can save data into shared preferences using editor. All the primitive data types like booleans,
floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared
preferences.
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
Data can be retrived from saved preferences by calling getString() (For string) method. Remember this
method should be called on Shared Preferences not on Editor.
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing / Deleting Data
If you want to delete from shared preferences you can call remove(“key_name”) to delete that
particular value. If you want to delete all the data, call clear()
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Following will clear all the data from shared preferences
editor.clear();
editor.commit(); // commit changes
Calling Webservice in android
*****************************
public class WebserviceActivity extends Activity {
private static final String NAMESPACE = "https://api.authorize.net/soap/v1/";
private static final String URL ="https://apitest.authorize.net/soap/v1/Service.asmx?wsdl";
private static final String SOAP_ACTION = "https://api.authorize.net/soap/v1/AuthenticateTest";
private static final String METHOD_NAME = "AuthenticateTest";
private TextView lblResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lblResult = (TextView) findViewById(R.id.tv);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("name","44vmMAYrhjfhj66fhJN");
request.addProperty("transactionKey","9MDQ7fghjghjh53H48k7e7n");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
//SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
// SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
lblResult.setText(resultsRequestSOAP.toString());
System.out.println("Response::"+resultsRequestSOAP.toString());
} catch (Exception e) {
System.out.println("Error"+e);
}
}
}
Calling HTTPPOST
****************
ArrayList nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
nameValuePairs.add(new BasicNameValuePair("email", email));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
TextView lbl = (TextView) findViewById(R.id.lbl);
lbl.setText(result);
} catch (Exception e) {
TextView tv = (TextView) findViewById(R.id.err);
tv.setText("Error parsing data " + e.toString());
System.out.println("Error parsing data " + e.toString());
}
Calling HTTPGET
***************
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.google.com";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
// do something with the response
String response = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", response);
}
} catch (Exception e) {
e.printStackTrace();
}

Thursday, November 8, 2012

Thursday, December 29, 2011

SOAP vs. REST









SOAP vs. REST







Developers new to web services are often intimidated by parade of technologies and concepts required to understand it: REST, SOAP, WSDL, XML Schema, Relax NG, UDDI, MTOM, XOP, WS-I, WS-Security, WS-Addressing, WS-Policy, and a host of other WS-* specifications that seem to multiply like rabbits. Add to that the Java specifications, such as JAX-WS, JAX-RPC, SAAJ, etc. and the conceptual weight begins to become heavy indeed. In this series of articles I hope to shed some light on the dark corners of web services and help navigate the sea of alphabet soup (1). Along the way I'll also cover some tools for developing web services, and create a simple Web Service as an example. In this article I will give a high-level overview of both SOAP and REST.

Introduction

There are currently two schools of thought in developing web services: the traditional, standards-based approach (SOAP) and conceptually simpler and the trendier new kid on the block (REST). The decision between the two will be your first choice in designing a web service, so it is important to understand the pros and cons of the two. It is also important, in the sometimes heated debate between the two philosophies, to separate reality from rhetoric.

SOAP


In the beginning there was...SOAP. Developed at Microsoft in 1998, the inappropriately-named "Simple Object Access Protocol" was designed to be a platform and language-neutral alternative to previous middleware techologies like CORBA and DCOM. Its first public appearance was an Internet public draft (submitted to the IETF) in 1999; shortly thereafter, in December of 1999, SOAP 1.0 was released. In May of 2000 the 1.1 version was submitted to the W3C where it formed the heart of the emerging Web Services technologies. The current version is 1.2, finalized in 2005. The examples given in this article will all be SOAP 1.2.

Together with WSDL and XML Schema, SOAP has become the standard for exchanging XML-based messages. SOAP was also designed from the ground up to be extensible, so that other standards could be integrated into it--and there have been many, often collectively referred to as WS-*: WS-Addressing, WS-Policy, WS-Security, WS-Federation, WS-ReliableMessaging, WS-Coordination, WS-AtomicTransaction, WS-RemotePortlets, and the list goes on. Hence much of the perceived complexity of SOAP, as in Java, comes from the multitude of standards which have evolved around it. This should not be reason to be too concerned: as with other things, you only have to use what you actually need.

The basic structure of SOAP is like any other message format (including HTML itself): header and body. In SOAP 1.2 this would look something like










Note that the
element is optional here, but the is mandatory.

The SOAP


SOAP uses special attributes in the standard "soap-envelope" namespace to handle the extensibility elements that can be defined in the header. The most important of these is the mustUnderstand attribute. By default, any element in the header can be safely ignored by the SOAP message recipient unless the the mustUnderstand attribute on the element is set to "true" (or "1", which is the only value recognized in SOAP 1.1). A good example of this would be a security token element that authenticates the sender/requestor of the message. If for some reason the recipient is not able to process these elements, a fault should be delivered back to the sender with a fault code of MustUnderstand.

Because SOAP is designed to be used in a network environment with multiple intermediaries (SOAP "nodes" as identified by the element), it also defines the special XML attributes role to manage which intermediary should process a given header element and relay, which is used to indicate that this element should be passed to the next node if not processed in the current one.

The SOAP

The SOAP body contains the "payload" of the message, which is defined by the WSDL's part. If there is an error that needs to be transmitted back to the sender, a single element is used as a child of the .

The SOAP

The is the standard element for error handling. When present, it is the only child element of the SOAP . The structure of a fault looks like:



env:Sender

m:MessageTimeout



Sender Timeout


P5M



Here, only the and child elements are required, and the child of is also optional. The body of the Code/Value element is a fixed enumeration with the values:

VersionMismatch: this indicates that the node that "threw" the fault found an invalid element in the SOAP envelope, either an incorrect namespace, incorrect local name, or both.
MustUnderstand: as discussed above, this code indicates that a header element with the attribute mustUnderstand="true" could not be processed by the node throwing the fault. A NotUnderstood header block should be provided to detail all of the elements in the original message which were not understood.
DataEncodingUnknown: the data encoding specified in the envelope's encodingSytle attribute is not supported by the node throwing the fault.
Sender: This is a "catch-all" code indicating that the message sent was not correctly formed or did not have the appropriate information to succeed.
Receiver: Another "catch-all" code indicating that the message could not be processed for reasons attributable to the processing of the message rather than to the contents of the message itself.

Subcodes, however, are not restricted and are application-defined; these will commonly be defined when the fault code is Sender or Receiver. The element is there to provide a human-readable explanation of the fault. The optional element is there to provide additional information about the fault, such as (in the example above) the timeout value. also has optional children and , indicating which node threw the fault and the role that the node was operating in (see role attribute above) respectively.

SOAP Encoding

Section 5 of the SOAP 1.1 specification describes SOAP encoding, which was originally developed as a convenience for serializing and de-serializing data types to and from other sources, such as databases and programming languages. Problems, however, soon arose with complications in reconciling SOAP encoding and XML Schema, as well as with performance. The WS-I organization finally put the nail in the coffin of SOAP encoding in 2004 when it released the first version of the WS-I Basic Profile, declaring that only literal XML messages should be used (R2706). With the wide acceptance of WS-I, some of the more recent web service toolkits do not provide any support for (the previously ubiquitous) SOAP encoding at all.

A Simple SOAP Example

Putting it all together, below is an example of a simple request-response in SOAP for a stock quote. Here the transport binding is HTTP.

The request:

GET /StockPrice HTTP/1.1
Host: example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn


xmlns:s="http://www.example.org/stock-service">


IBM




The response:

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn


xmlns:s="http://www.example.org/stock-service">


45.25




If you play your cards right, you may never have to actually see a SOAP message in action; every SOAP engine out there will do its best to hide it from you unless you really want to see it. If something goes wrong in your web service, however, it may be useful to know what one looks like for debugging purposes.

REST

Much in the way that Ruby on Rails was a reaction to more complex web application architectures, the emergence of the RESTful style of web services was a reaction to the more heavy-weight SOAP-based standards. In RESTful web services, the emphasis is on simple point-to-point communication over HTTP using plain old XML (POX).

The origin of the term "REST" comes from the famous thesis from Roy Fielding describing the concept of Representative State Transfer (REST). REST is an architectural style that can be summed up as four verbs (GET, POST, PUT, and DELETE from HTTP 1.1) and the nouns, which are the resources available on the network (referenced in the URI). The verbs have the following operational equivalents:

HTTP CRUD Equivalent
==============================
GET read
POST create,update,delete
PUT create,update
DELETE delete

A service to get the details of a user called 'dsmith', for example, would be handled using an HTTP GET to http://example.org/users/dsmith. Deleting the user would use an HTTP DELETE, and creating a new one would mostly likely be done with a POST. The need to reference other resources would be handled using hyperlinks (the XML equivalent of HTTP's href, which is XLinks' xlink:href) and separate HTTP request-responses.

A Simple RESTful Service

Re-writing the stock quote service above as a RESTful web service provides a nice illustration of the differences between SOAP and REST web services.

The request:

GET /StockPrice/IBM HTTP/1.1
Host: example.org
Accept: text/xml
Accept-Charset: utf-8

The response:

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: nnn



IBM
45.25


Though slightly modified (to include the ticker symbol in the response), the RESTful version is still simpler and more concise than the RPC-style SOAP version. In a sense, as well, RESTful web services are much closer in design and philosophy to the Web itself.

Defining the Contract

Traditionally, the big drawback of REST vis-a-vis SOAP was the lack of any way of specifying a description/contract for the web service. This, however, has changed since WSDL 2.0 defines a full compliment of non-SOAP bindings (all the HTTP methods, not just GET and POST) and the emergence of WADL as an alternative to WSDL. This will be discussed in more detail in coming articles.

Summary and Pros/Cons

SOAP and RESTful web services have a very different philosophy from each other. SOAP is really a protocol for XML-based distributed computing, whereas REST adheres much more closely to a bare metal, web-based design. SOAP by itself is not that complex; it can get complex, however, when it is used with its numerous extensions (guilt by association).

To summarize their strengths and weaknesses:

*** SOAP ***

Pros:

Langauge, platform, and transport agnostic
Designed to handle distributed computing environments
Is the prevailing standard for web services, and hence has better support from other standards (WSDL, WS-*) and tooling from vendors
Built-in error handling (faults)
Extensibility

Cons:

Conceptually more difficult, more "heavy-weight" than REST
More verbose
Harder to develop, requires tools

*** REST ***

Pros:

Language and platform agnostic
Much simpler to develop than SOAP
Small learning curve, less reliance on tools
Concise, no need for additional messaging layer
Closer in design and philosophy to the Web

Cons:

Assumes a point-to-point communication model--not usable for distributed computing environment where message may go through one or more intermediaries
Lack of standards support for security, policy, reliable messaging, etc., so services that have more sophisticated requirements are harder to develop ("roll your own")
Tied to the HTTP transport model

WebService

Web Service is a collection of protocols and standards used for exchanging data between applications

Three types of Web Services

1) XML-RPC (Remote Procedure Call)
2) SOAP (Simple Object Access Protocol)
3) REST (Representative State Transfer)

XML-RPC

XML-RPC is a simple, portable way to make remote procedure calls over HTTP


SOAP

"Simple Object Access Protocol" was designed to be a platform and language-neutral alternative to previous middleware techologies like CORBA and DCOM.

REST

RESTful web services, the emphasis is on simple point-to-point communication over HTTP using plain old XML (POX).


SOAP


As communications protocols and message formats are standardized in the web community, it becomes increasingly possible and important to be able to describe the communications in some structured way. WSDL addresses this need by defining an XML grammar for describing network services as collections of communication endpoints capable of exchanging messages. WSDL service definitions provide documentation for distributed systems and serve as a recipe for automating the details involved in applications communication.
A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions:messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections ofoperations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:
  • Types– a container for data type definitions using some type system (such as XSD).
  • Message– an abstract, typed definition of the data being communicated.
  • Operation– an abstract description of an action supported by the service.
  • Port Type–an abstract set of operations supported by one or more endpoints.
  • Binding– a concrete protocol and data format specification for a particular port type.
  • Port– a single endpoint defined as a combination of a binding and a network address.
  • Service– a collection of related endpoints.

Saturday, July 23, 2011

JNDI Example

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class Test {
public static void main(String a[]) throws SQLException {
// System.out.println("test java ");
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");

try {
ctx = new InitialContext(ht);
DataSource ds = (DataSource)ctx.lookup("myjndi");
Connection con = ds.getConnection();
Statement st =con.createStatement();
ResultSet rs =st.executeQuery("select * from user");

while (rs.next()) {
System.out.println("user name : "+rs.getString("userid"));
System.out.println("pwd : "+rs.getString("pwd"));
}

// Use the context in your program
} catch (NamingException e) {
e.printStackTrace();
// a failure occurred
} finally {
try {
ctx.close();
} catch (Exception e) {
e.printStackTrace();
// a failure occurred
}
}

}
}

Friday, December 25, 2009

J2ME

What is J2ME ?
Java 2, Micro Edition is a group of specifications and technologies that pertain to Java on small devices. The J2ME moniker covers a wide range of devices, from pagers and mobile telephones through set-top boxes and car navigation systems. The J2ME world is divided into configurations and profiles, specifications that describe a Java environment for a specific class of device.

What is J2ME WTK ?
The J2ME Wireless Toolkit is a set of tools that provides developers with an emulation environment, documentation and examples for developing Java applications for small devices. The J2ME WTK is based on the Connected Limited Device Configuration (CLDC) and Mobile Information Device Profile (MIDP) reference implementations, and can be tightly integrated with Forte for Java

What is 802.11 ?
802.11 is a group of specifications for wireless networks developed by the Institute of Electrical and Electronics Engineers (IEEE). 802.11 uses the Ethernet protocol and CSMA/CA (carrier sense multiple access with collision avoidance) for path sharing.

What is API ?
An Application Programming Interface (API) is a set of classes that you can use in your own application. Sometimes called libraries or modules, APIs enable you to write an application without reinventing common pieces of code. For example, a networking API is something your application can use to make network connections, without your ever having to understand the underlying code. 5. What is AMPS

Advanced Mobile Phone Service (AMPS) is a first-generation analog, circuit-switched cellular phone network. Originally operating in the 800 MHz band, service was later expanded to include transmissions in the 1900 MHz band, the VHF range in which most wireless carriers operate. Because AMPS uses analog signals, it cannot transmit digital signals and cannot transport data packets without assistance from newer technologies such as TDMA and CDMA.

What is CDC ?
The Connected Device Configuration (CDC) is a specification for a J2ME configuration. Conceptually, CDC deals with devices with more memory and processing power than CLDC; it is for devices with an always-on network connection and a minimum of 2 MB of memory available for the Java system.

What is CDMA ?
Code-Division Multiple Access (CDMA) is a cellular technology widely used in North America. There are currently three CDMA standards: CDMA One, CDMA2000 and W-CDMA. CDMA technology uses UHF 800Mhz-1.9Ghz frequencies and bandwidth ranges from 115Kbs to 2Mbps.

What is CDMA One ?
Also know as IS-95, CDMA One is a 2nd generation wireless technology. Supports speeds from 14.4Kbps to 115K bps.

What is CDMA2000 ?
Also known as IS-136, CDMA2000 is a 3rd generation wireless technology. Supports speeds ranging from 144Kbps to 2Mbps.

What is CDPD ?
Developed by Nortel Networks, Cellular Digital Packet Data (CDPD) is an open standard for supporting wireless Internet access from cellular devices. CDPD also supports Multicast, which allows content providers to efficiently broadcast information to many devices at the same time.

What is cHTML ?
Compact HTML (cHTML) is a subset of HTML which is designed for small devices. The major features of HTML that are excluded from cHTML are: JPEG image, Table, Image map, Multiple character fonts and styles, Background color and image, Frame and Style sheet.

What is CLDC ?
The Connected, Limited Device Configuration (CLDC) is a specification for a J2ME configuration. The CLDC is for devices with less than 512 KB or RAM available for the Java system and an intermittent (limited) network connection. It specifies a stripped-down Java virtual machine1 called the KVM as well as several APIs for fundamental application services. Three packages are minimalist versions of the J2SE java.lang, java.io, and java.util packages. A fourth package, javax.microedition.io, implements the Generic Connection Framework, a generalized API for making network connections.

What is configuration ?
In J2ME, a configuration defines the minimum Java runtime environment for a family of devices: the combination of a Java virtual machine (either the standard J2SE virtual machine or a much more limited version called the CLDC VM) and a core set of APIs. CDC and CLDC are configurations. See also profile, optional package.

What is CVM ?
The Compact Virtual Machine (CVM) is an optimized Java virtual machine1 (JVM) that is used by the CDC.

What is Deck ?
A deck is a collection of one or more WML cards that can be downloaded, to a mobile phone, as a single entity.

What is EDGE ?
Enhanced Data GSM Environment (EDGE) is a new, faster version of GSM. EDGE is designed to support transfer rates up to 384Kbps and enable the delivery of video and other high-bandwidth applications. EDGE is the result of a joint effort between TDMA operators, vendors and carriers and the GSM Alliance.

What is ETSI ?
The European Telecommunications Standards Institute (ETSI) is a non-profit organization that establishes telecommunications standards for Europe.

What is FDMA ?
Frequency-division multiple-access (FDMA) is a mechanism for sharing a radio frequency band among multiple users by dividing it into a number of smaller bands.

What is Foundation Profile ?
The Foundation Profile is a J2ME profile specification that builds on CDC. It adds additional classes and interfaces to the CDC APIs but does not go so far as to specify user interface APIs, persistent storage, or application life cycle. Other J2ME profiles build on the CDC/Foundation combination: for example, the Personal Profile and the RMI Profile both build on the Foundation Profile.

What is Generic Connection Framework ?
The Generic Connection Framework (GCF) makes it easy for wireless devices to make network connections. It is part of CLDC and CDC and resides in the javax.microedition.io package.

What is GPRS ?
The General Packet Radio System (GPRS) is the next generation of GSM. It will be the basis of 3G networks in Europe and elsewhere.

What is GSM ?
The Global System for Mobile Communications (GSM) is a wireless network system that is widely used in Europe, Asia, and Australia. GSM is used at three different frequencies: GSM900 and GSM1800 are used in Europe, Asia, and Australia, while GSM1900 is deployed in North America and other parts of the world.

What is HLR ?
The Home Location Register (HLR) is a database for permanent storage of subscriber data and service profiles.

What is HTTPS ?
Hyper Text Transfer Protocol Secure sockets (HTTPS) is a protocol for transmission of encrypted hypertext over Secure Sockets Layer.

What is i-appli ?
Sometimes called "Java for i-mode", i-appli is a Java environment based on CLDC. It is used on handsets in NTT DoCoMo's i-mode service. While i-appli is similar to MIDP, it was developed before the MIDP specification was finished and the two APIs are incompatible.

What is IDE ?
An Integrated Development Environment (IDE) provides a programming environment as a single application. IDEs typically bundle a compiler, debugger, and GUI builder tog ether. Forte for Java is Sun's Java IDE.

What is iDEN ?
The Integrated Dispatch Enhanced Network (iDEN) is a wireless network system developed by Motorola. Various carriers support iDEN networks around the world: Nextel is one of the largest carriers, with networks covering North and South America.

What is i-mode ?
A standard used by Japanese wireless devices to access cHTML (compact HTML) Web sites and display animated GIFs and other multimedia content.

What is 3G ?
Third generation (3G) wireless networks will offer faster data transfer rates than current networks. The first generation of wireless (1G) was analog cellular. The second generation (2G) is digital cellular, featuring integrated voice and data communications. So-called 2.5G networks offer incremental speed increases. 3G networks will offer dramatically improved data transfer rates, enabling new wireless applications such as streaming media.

What is 3GPP ?
The 3rd Generation Partnership Project (3GPP) is a global collaboration between 6 partners: ARIB, CWTS, ETSI, T1, TTA, and TTC. The group aims to develop a globally accepted 3rd-generation mobile system based on GSM.

What is Java Card ?
The Java Card specification allows Java technology to run on smart cards and other small devices. The Java Card API is compatible with formal international standards, such as, ISO7816, and industry-specific standards, such as, Europay/Master Card/Visa (EMV).

What is JavaHQ ?
JavaHQ is the Java platform control center on your Palm OS device.

What is JCP ?
The Java Community Process (JCP) an open organization of international Java developers and licensees who develop and revise Java technology specifications, reference implementations, and technology compatibility kits through a formal process.

What is JDBC for CDC/FP ?
The JDBC Optional Package for CDC/Foundation Profile (JDBCOP for CDC/FP) is an API that enables mobile Java applications to communicate with relational database servers using a subset of J2SE's Java Database Connectivity. This optional package is a strict subset of JDBC 3.0 that excludes some of JDBC's advanced and server-oriented features, such as pooled connections and array types. It's meant for use with the Foundation Profile or its supersets.

What is JSR
Java Specification Request (JSR) is the actual description of proposed and final specifications for the Java platform. JSRs are reviewed by the JCP and the public before a final release of a specification is made.

What is KittyHawk
KittyHawk is a set of APIs used by LG Telecom on its IBook and p520 devices. KittyHawk is based on CLDC. It is conceptually similar to MIDP but the two APIs are incompatible.

What is KJava
KJava is an outdated term for J2ME. It comes from an early package of Java software for PalmOS, released at the 2000 JavaOne show. The classes for that release were packaged in the com.sun.kjava package.

What is kSOAP
kSOAP is a SOAP API suitable for the J2ME, based on kXML.

What is kXML
The kXML project provides a small footprint XML parser that can be used with J2ME.

What is KVM
The KVM is a compact Java virtual machine (JVM) that is designed for small devices. It supports a subset of the features of the JVM. For example, the KVM does not support floating-point operations and object finalization. The CLDC specifies use of the KVM. According to folklore, the 'K' in KVM stands for kilobyte, signifying that the KVM runs in kilobytes of memory as opposed to megabytes.


What is LAN

A Local Area Network (LAN) is a group of devices connected with various communications technologies in a small geographic area. Ethernet is the most widely-used LAN technology. Communication on a LAN can either be with Peer-to-Peer devices or Client-Server devices.

What is LCDUI
LCDUI is a shorthand way of referring to the MIDP user interface APIs, contained in the javax.microedition.lcdui package. Strictly speaking, LCDUI stands for Liquid Crystal Display User Interface. It's a user interface toolkit for small device screens which are commonly LCD screens.

What is MExE
The Mobile Execution Environment (MExE) is a specification created by the 3GPP which details an applicatio n environment for next generation mobile devices. MExE consists of a variety of technologies including WAP, J2ME, CLDC and MIDP.

What is MIDlet
A MIDlet is an application written for MIDP. MIDlet applications are subclasses of the javax.microedition.midlet.MIDlet class that is defined by MIDP.

What is MIDlet suite
MIDlets are packaged and distributed as MIDlet suites. A MIDlet suite can contain one or more MIDlets. The MIDlet suite consists of two files, an application descriptor file with a .jad extension and an archive file with a .jar file. The descriptor lists the archive file name, the names and class names for each MIDlet in the suite, and other information. The archive file contains the MIDlet classes and resource files.

What is MIDP
The Mobile Information Device Profile (MIDP) is a specification for a J2ME profile. It is layered on top of CLDC and adds APIs for application life cycle, user interface, networking, and persistent storage.

What is MIDP-NG
The Next Generation MIDP specification is currently under development by the Java Community Process. Planned improvements include XML parsing and cryptographic support.

What is Mobitex
Mobitex is a packet-switched, narrowband PCS network, designed for wide-area wireless data communications. It was developed in 1984 by Eritel, an Ericsson subsidiary, a nd there are now over 30 Mobitex networks in operation worldwide.

What is Modulation ?
Modulation is the method by which a high-frequency digital signal is grafted onto a lower-frequency analog wave, so that digital packets are able to ride piggyback on the analog airwave.

What is MSC ?
A Mobile Switching Center (MSC) is a unit within a cellular phone network that automatically coordinates and switches calls in a given cell. It monitors each caller's signal strength, and when a signal begins to fade, it hands off the call to another MSC that's better positioned to manage the call.

What is Obfuscation
Obfuscation is a technique used to complicate code. Obfuscation makes code harder to understand when it is de-compiled, but it typically has no affect on the functionality of the code. Obfuscation programs can be used to protect Java programs by making them harder to reverse-engineer.

What is optional package
An optional package is a set of J2ME APIs providing services in a specific area, such as database access or multimedia. Unlike a profile, it does not define a complete application environment, but rather is used in conjunction with a configuration or a profile. It extends the runtime environment to support device capabilities that are not universal enough to be defined as part of a profile or that need to be shared by different profiles. J2ME RMI and the Mobile Media RMI are examples of optional packages.

What is OTA
Over The Air (OTA) refers to any wireless networking technology.

What is PCS
Personal Communications Service (PCS) is a suite of second-generation, digitally modulated mobile-communications interfaces that includes TDMA, CDMA, and GSM. PCS serves as an umbrella term for second-generation wireless technologies operating in the 1900MHz range

What is PDAP
The Personal Digital Assistant Profile (PDAP) is a J2ME profile specification designed for small platforms such as PalmOS devices. You can think of PDAs as being larger than mobile phones but smaller than set-top boxes. PDAP is built on top of CLDC and will specify user interface and persistent storage APIs. PDAP is currently being developed using the Java Community Process (JCP).

What is PDC
Personal Digital Cellular (PDC) is a Japanese standard for wireless communications.

What is PDCP
Parallel and Distributed Computing Practices (PDCP) are often used to describe computer systems that are spread over many devices on a network (wired or wireless) where many nodes process data simultaneously.

What is Personal Profile
The Personal Profile is a J2ME profile specification. Layered on the Foundation Profile and CDC, the Personal Profile will be the next generation of PersonalJava technology. The specification is currently in development under the Java Community
Process (JCP).

What is PersonalJava

PersonalJava is a Java environment based on the Java virtual machine1 (JVM) and a set of APIs similar to a JDK 1.1 environment. It includes the Touchable Look and Feel (also called Truffle), a graphic toolkit that is optimized for consumer devices with a touch sensitive screen. PersonalJava will be included in J2ME in the upcoming Personal Profile, which is built on CDC.

What is PNG
Portable Network Graphics (PNG) is an image format offering lossless compression and storage flexibility. The MIDP specification requires implementations to recognize certain types of PNG images.

What is POSE
Palm OS Emulator (POSE).

What is PRC
Palm Resource Code (PRC) is the file format for Palm OS applications.

What is preverification
Due to memory and processing power available on a device, the verification process of classes are split into two processes. The first process is the preverification which is off-device and done using the preverify tool. The second process is verification
which is done on-device.

What is profile
A profile is a set of APIs added to a configuration to support specific uses of a mobile device. Along with its underlying configuration, a profile defines a complete, and usually self-contained, general-purpose application environment. Profiles often, but not always, define APIs for user interface and persistence; the MIDP profile, based on the CLDC configuration, fits this pattern. Profiles may be supersets or subsets of other profiles; the Personal Basis Profile is a subset of the Personal Profile and a superset of the Foundation Profile. See also configuration, optional package.

What is Provisioning ?
In telecommunications terms, provisioning means to provide telecommunications services to a user. This includes providing all necessary hardware, software, and wiring or transmission devices.

What is PSTN ?
The public service telephone network (PSTN) is the traditional, land-line based system for exchanging phone calls.

What is RMI
Remote method invocation (RMI) is a feature of J2SE that enables Java objects running in one virtual machine to invoke methods of Java objects running in another virtual machine, seamlessly.

What is RMI OP
The RMI Optional Package (RMI OP) is a subset of J2SE 1.3's RMI functionality used in CDC-based profiles that incorporate the Foundation Profile, such as the Personal Basis Profile and the Personal Profile. The RMIOP cannot be used with CLDC-based profiles because they lack object serialization and other important features found only in CDC-based profiles. RMIOP supports most of the J2SE RMI functionality, including the Java Remote Method Protocol, marshalled objects, distributed garbage collection, registry-based object lookup, and network class loading, but not HTTP tunneling or the Java 1.1 stub protocol.

What is RMI Profile
The RMI Profile is a J2ME profile specification designed to support Java's Remote Method Invocation (RMI) distributed object system. Devices implementing the RMI Profile will be able to interoperate via RMI with other Java devices, including Java 2, Standard Edition. The RMI Profile is based on the Foundation Profile, which in turn is based on CDC.

What is RMS
The Record Management System (RMS) is a simple record-oriented database that allows a MIDlet to persistently store information and retrieve it later. Different MIDlets can also use the RMS to share data.

What is SDK
A Software Development Kit (SDK) is a set of tools used to develop applications for a particular platform. An SDK typically contains a compiler, linker, and debugger. It may also contain libraries and documentation for APIs.

What is SIM
A Subscriber Identity Module (SIM) is a stripped-down smart card containing information about the identity of a cell-phone subscriber, and subscriber authentication and service information. Because the SIM uniquely identifies the subscriber and is portable among handsets, the user can move it from one kind of phone to another, facilitating international roaming.

What is SMS
Short Message Service (SMS) is a point-to-point service similar to paging for sending text messages of up to 160 characters to mobile phones.

What is SOAP
The Simple Object Access Protocol (SOAP) is an XML- based protocol that allows objects of any type to communicated in a distributed environment. SOAP is used in developing Web Services.

What is SSL
Secure Sockets Layer (SSL) is a socket protocol that encrypts data sent over the network and provides authentication for the socket endpoints.

What is T9
T9 is a text input method for mobile phones and other small devices. It replaces the "multi-tap" input method by guessing the word that you are trying to enter. T9 may be embedded in a device by the manufacturer. Note that even if the device supports T9, the Java implementation may or may not use it. Check your documentation for details.

What is TDMA
Time Division Multiple Access (TDMA) is a second-generation modulation standard using bandwidth allocated in the 800 MHz, 900 MHz, and 1900MHz ranges.

What is Telematics
Telematics is a location-based service that routes event notification and control data over wireless networks to and from mobile devices installed in automobiles. Telematics makes use of GPS technology to track vehicle latitude and longitude, and displays maps in LED consoles mounted in dashboards. It connects to remote processing centers that turn provide server-side Internet and voice services, as well as access to database resources.

What is Tomcat ?
Tomcat is a reference implementation of the Java servlet and JavaServer Pages (JSP) specifications. It is intended as a platform for developing and testing servlets.

What is UDDI ?
Universal Description, Discovery, and Integration (UDDI) is an XML-based standard for describing, publishing, and finding Web services. UDDI is a specification for a distributed registry of Web services.

What is UMTS
Developed by Nortel Networks, Universal Mobile Telecommunications Service (UMTS) is a standard that will provide cellular users a consistent set of technologies no matter where they are located worldwide. UMTS utilizes W-CDMA technology.

What is VLR
The Visitor Location Register (VLR) is a database that contains temporary information about subscribers.

What is WAE
The Wireless Application Environment (WAE) provides a application framework for small devices. WAE leverages other technologies such as WAP, WTP, and WSP.

What is WAP
Wireless Application Protocol (WAP) is a protocol for transmitting data between servers and clients (usually small wireless devices like mobile phones). WAP is analogous to HTTP in the World Wide Web. Many mobile phones include WAP browser software to allow users access to Internet WAP sites.

What is WAP Gateway
A WAP Gateway acts as a bridge allowing WAP devices to communicate with other networks (namely the Internet).

What is W-CDMA
Wideband Code-Division Multiple Access (W-CDMA), also known as IMT-2000, is a 3rd generation wireless technology. Supports speeds up to 384Kbps on a wide-area network, or 2Mbps locally.

What is WDP
Wireless Datagram Protocol (WDP) works as the transport layer of WAP. WDP processes datagrams from upper layers to formats required by different physical datapaths, bearers, that may be for example GSM SMS or CDMA Packet Data. WDP is adapted to the bearers available in the device so upper layers don't need to care about the physical level.

What is WMA
The Wireless Messaging API (WMA) is a set of classes for sending and receiving Short Message Service messages. See also SMS.

What is WML
The Wireless Markup Language (WML) is a simple language used to create applications for small wireless devices like mobile phones. WML is analogous to HTML in the World Wide Web.

What is WMLScript
WMLScript is a subset of the JavaScript scripting language designed as part of the WAP standard to provide a convenient mechanism to access mobile phone's peripheral functions.

What is WSP
Wireless Session Protocol (WSP) implements session services of WAP. Sessions can be connection-oriented and connectionless and they may be suspended and resumed at will.

What is WTLS
Wireless Transport Layer Security protocal (WTLS) does all cryptography oriented features of WAP. WTLS handles encryption/decryption, user authentication and data integrity. WTLS is based on the fixed network Transport Layer Security protocal (TLS), formerly known as Secure Sockets Layer (SSL).

What is WTP
Wireless Transaction Protocol (WTP) is WAP's transaction protocol that works between the session protocol WSP and security protocol WTLS. WTP chops data packets into lower level datagrams and concatenates received datagrams into useful data. WTP also keeps track of received and sent packets and does re-transmissions and acknowledgment sending when needed.

What is TDMA
Time Division Multiple Access (TDMA) is a second-generation modulation standard using bandwidth allocated in the 800 MHz, 900
MHz, and 1900MHz ranges
.Seven profiles have been defined as of this writing. These are the Foundation Profile, Game Profile, Mobile Information Device Profile, PDA Profile,Personal Profile, Personal Basis Profile, and RMI Profile.
■ The Foundation Profile is used with the CDC configuration and is the core for nearly all other profiles used with the CDC configuration because the Foundation Profile contains core Java classes.

■ The Game Profile is also used with the CDC configuration and contains the necessary classes for developing game applications for any small computing device that uses the CDC configuration.

■ The Mobile Information Device Profile (MIDP) is used with the CLDC configuration and contains classes that provide local storage, a user interface, and networking capabilities to an application that runs on a mobile computing device such as Palm OS devices. MIDP is used with wireless Java applications.

■ The PDAProfile (PDAP) is used with the CLDC configuration and contains classes that utilize sophisticated resources found on personal digital assistants. These features include better displays and larger memory than similar resources found on MIDP mobile devices (such as cell phones).

■ The Personal Profile is used with the CDC configuration and the Foundation Profile and contains classes to implement a complex user interface. The Foundation Profile provides core classes, and the Personal Profiles provide classes to implement a sophisticated user interface, which is a user interface that is capable of displaying multiple windows at a time.

■ The Personal Basis Profile is similar to the Personal Profile in that it is used with the CDC configuration and the Foundation Profile. However, the Personal Basis Profile provides classes to implement a simple user interface, which is a user interface that is capable of displaying one window at a time.

■ The RMI Profile is used with the CDC configuration and the Foundation Profile to provide Remote Method Invocation classes to the core classes contained in the Foundation Profile.

J2ME Architecture
The modular design of the J2ME architecture enables an application to be scaled based on constraints of a small computing device. J2ME architecture doesn’t replace the operating system of a small computing device. Instead, J2ME architecture consists of layers located above the native operating system, collectively referred to as the Connected Limited Device Configuration (CLDC). The CLDC, which is installed on top of the operating system, forms the run-time environment for small computing devices. The J2ME architecture comprises three software layers (Figure 3-1). The first layer is the configuration layer that includes the Java Virtual Machine (JVM), which directly interacts with the native operating system. The configuration layer also handles interactions between the profile and the JVM. The second layer is the profile layer, which consists of the minimum set of application programming interfaces (APIs) for the small computing device. The third layer is the Mobile Information Device Profile (MIDP). The MIDP layer contains Java APIs for user network connections, persistence storage, and the user interface. It also has access to CLDC libraries and MIDP libraries.

Hibernate

The ORM levels are:
• Pure relational (stored procedure.)
• Light objects mapping (JDBC)
• Medium object mapping
• Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration file

Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:


Core interfaces are of Hibernate framework
Session interface
SessionFactory interface
Configuration interface
Transaction interface
Query and Criteria interfaces

Session interface play in Hibernate?

It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession()

SessionFactory interface play in Hibernate?
The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization.

SessionFactory sessionFactory = configuration.buildSessionFactory();

The general flow of Hibernate communication with RDBMS is :
• Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
• Create session factory from configuration object
• Get one session from this session factory
• Create HQL Query
• Execute query to get list containing Java objects
HQL?
The Hibernate query Language (HQL), is an object-oriented extension to SQL.

Following are the important tags of hibernate.cfg.xml:


How do you map Java Objects with Database tables?
• First we need to write Java domain objects (beans with setter and getter).
• Write hbm.xml, where we map java class to table and database columns to Java class variables.
Example :


name="userName" not-null="true" type="java.lang.String"/>
name="userPassword" not-null="true" type="java.lang.String"/>



load() vs. get() :-
load() get()
Only use the load() method if you are sure that the object exists. If you are not sure that the object exists, then use one of the get() methods.
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database.
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. get() will hit the database immediately.




What is the difference between and merge and update ?
Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

What do you mean by Named – SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:


SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name


Invoke Named Query :
List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();

How do you invoke Stored Procedures?







{ ? = call selectAllEmployees() }


What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
o HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
o Common functions are simplified to single method calls.
o Sessions are automatically closed.
o Exceptions are automatically caught and converted to runtime exceptions.








Explain Criteria API
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();

sorted collection vs. order collection :-
sorted collection order collection
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .

What are the types of Hibernate instance states ?
Three types of instance states:
• Transient -The instance is not associated with any persistence context
• Persistent -The instance is associated with a persistence context
• Detached -The instance was associated with a persistence context which has been closed – currently not associated
Configuration conf=new Configuration();
conf.addFile(“hibernate.cfg.xml”);
SessionFactory factory=conf.configure().buildSessionFactory();
Customer cus=new Customer();
Session ses=factory.openSession();
Transaction tx=ses.begintransaction();
ses.save(cus);
tx,commit();













Usually update() or saveOrUpdate() are used in the following scenario:
o the application loads an object in the first session
o the object is passed up to the UI tier
o some modifications are made to the object
o the object is passed back down to the business logic tier
o the application persists these modifications by calling update() in a second session
saveOrUpdate() does the following:
o if the object is already persistent in this session, do nothing
o if another object associated with the session has the same identifier, throw an exception
o if the object has no identifier property, save() it
o if the object's identifier has the value assigned to a newly instantiated object, save() it
o if the object is versioned by a or , and the version property value is the same value assigned to a newly instantiated object, save() it
o otherwise update() the object
and merge() is very different:
o if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
o if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
o the persistent instance is returned
o the given instance does not become associated with the session, it remains detached





























Core interfaces are of hibernate framework:
i. Session Interface – This is the primary interface used by hibernate applications. The instances of thisinterface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
ii. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all theapplication threads.
iii. Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of thisinterface is used by the application in order to specify the location of hibernate specific mapping documents.
iv. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
v. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.
Criteria queries
HQL is extremely powerful, but some developers prefer to build queries dynamically using an object-oriented API, rather than building query strings. Hibernate provides an intuitive Criteria query API for these cases:
Criteria crit = session.createCriteria(Cat.class);
crit.add( Restrictions.eq( "color", eg.Color.BLACK ) );
crit.setMaxResults(10);
List cats = crit.list();
Connection pools are a common way to improve application performance. Rather than opening a separate connection to the database for each request, the connection pool maintains a collection of open database
connections that are reused

How to Config c3p0 connection pool?
hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc: postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50

First-level cache:
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
Second-level cache:
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.

Cache Implementations.
• EHCache.
• OSCache.
• SwarmCache.
• JBoss TreeCache.
Caching Strategies:
• Read-only.
• Read-Write.
• Nonstriict read-write.
• Transactional.
Cache Read-only Nonstrict Read/write Read/write Transactional
EHCache Yes Yes Yes No
OSCache Yes Yes Yes No
SwarmCache Yes Yes No No
JBoss TreeCache Yes No No Yes

Four levels defined for ORM quality:
i. Pure relational
ii. Light object mapping
iii. Medium object mapping
iv. Full object mapping
Pure Relational ORM:
The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

Light Object Mapping:
The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

Medium Object Mapping:
The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

Full Object Mapping:
Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application

Benefits of ORM and Hibernate:
i. Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
ii. Maintainability – As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.
iii. Performance – Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing theperformance. If it is automated persistence then it still increases the performance.
iv. Vendor independence – Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application
Method chaining:
Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code
SessionFactory sessions = new Configuration()
.addResource("myinstance/MyConfig.hbm.xml")
.setProperties( System.getProperties() )
.buildSessionFactory();

Extension Interfaces
Hibernate offers a range of optional extension interfaces you can implement to customize the behavior of your persistence layer
Extension interfaces that are there in hibernate:
• ProxyFactory interface - used to create proxies
• ConnectionProvider interface – used for JDBC connection management
• TransactionFactory interface – Used for transaction management
• Transaction interface – Used for transaction management
• TransactionManagementLookup interface – Used in transaction management.
• Cahce interface – provides caching techniques and strategies
• CacheProvider interface – same as Cache interface
• ClassPersister interface – provides ORM strategies
• IdentifierGenerator interface – used for primary key generation
Fetching Strategy?
● A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the
application needs to navigate the association.
● Fetching strategy will have performance impact
● Fetch strategies may be declared in the mapping files, or over-ridden by a particular
HQL or Criteria query.

How fetching is done
– Join
– Select (default)
– Subselect
– Batch

● When fetching is done
– immediate
– lazy (default)

Hibernate retrieves the associated instance or collection in the same SELECT, using an
OUTER JOIN

Join Fetching in HQL:
String hql = "from Product p join fetch p.supplier as s";
Query query = session.createQuery(hql);
List results = query.list();

Join Fetching in Criteria API:
Criteria crit = session.createCriteria(Product.class);
crit.setFetchMode("supplier", FetchMode.JOIN);
List results = crit.list();

Generator class:
The optional child element names a Java class used to generate unique identifiers for instances of the persistent class.
Ex;increment ,identity, sequence, hilo, seqhilo, uuid, guid, Native,Assigned, select, foreign, sequence-identity
Three basic inheritance mapping strategies:
o table per class hierarchy
o table per subclass
o table per concrete class

Pagination
If you need to specify bounds upon your result set, that is, the maximum number of rows you want to retrieve and/or the first row you want to retrieve, you can use methods of the Query interface:
Query q = sess.createQuery("from DomesticCat cat");
q.setFirstResult(20);
q.setMaxResults(10);
List cats = q.list();


Many-to-one associations use foreign keys to maintain
the association between two persistent classes

Cascade
cascade="none", the default, tells Hibernate to ignore the association.
all—All operations are passed to child entities: save, update, and delete.
save-update—Save and update (INSERT and UPDATE, respectively) are passed to child entities.
delete—Deletion operations are passed to child entities.
delete-orphan—All operations are passed to child entities, and objects no longer associated with the parent object are deleted.
all-delete-orphan" means the same as cascade="all" but, in addition, Hibernate deletes any persistent entity instance that has been removed (dereferenced) from the association

Transactions group many operations into a single unit of work. If any operation in the batch fails, all of the previous operations are rolled back, and the unit of work stops.

Components allow you to take several columns and group them into a single object

























EHCache (Easy Hibernate Cache) (org.hibernate.cache.EhCacheProvider)
• It is fast.
• lightweight.
• Easy-to-use.
• Supports read-only and read/write caching.
• Supports memory-based and disk-based caching.
• Does not support clustering.
OSCache (Open Symphony Cache) (org.hibernate.cache.OSCacheProvider)
• It is a powerful .
• flexible package
• supports read-only and read/write caching.
• Supports memory- based and disk-based caching.
• Provides basic support for clustering via either JavaGroups or JMS.
SwarmCache (org.hibernate.cache.SwarmCacheProvider)
• is a cluster-based caching.
• supports read-only or nonstrict read/write caching .
• appropriate for applications those have more read operations than write operations.
JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)
• is a powerful replicated and transactional cache.
• useful when we need a true transaction-capable caching architecture .
Caching Stringategies
Important thing to remembered while studying this one is none of the cache providers support all of the cache concurrency strategies.
3.1) Read-only
• Useful for data that is read frequently but never updated.
• It is Simple .
• Best performer among the all.
Advantage if this one is, It is safe for using in a cluster. Here is an example for using the read-only cache strategy.



....

3.2) Read-Write
• Used when our data needs to be updated.
• It’s having more overhead than read-only caches.
• When Session.close() or Session.disconnect() is called the transaction should be completed in an environment where JTA is no used.
• It is never used if serializable transaction isolation level is required.
• In a JTA environment, for obtaining the JTA TransactionManager we must specify the propertyhibernate.transaction.manager_lookup_class.
• To use it in a cluster the cache implementation must support locking.
Here is an example for using the read-write cache stringategy.



….


….


3.3) Nonstrict read-write
• Needed if the application needs to update data rarely.
• we must specify hibernate.transaction.manager_lookup_class to use this in a JTA environment .
• The transaction is completed when Session.close() or Session.disconnect() is called In other environments (except JTA) .
Here is an example for using the nonstrict read-write cache stringategy.



….

3.4) Transactional
• It supports only transactional cache providers such as JBoss TreeCache.
• only used in JTA environment.