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.

Spring

What is Spring?
Spring is a lightweight inversion of control and aspect-oriented container framework.

Explain Spring?
• Lightweight : Spring is lightweight when it comes to size and transparency. The basic version of springframework is around 1MB. And the processing overhead is also very negligible.
• Inversion of control (IoC) : Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
• Aspect oriented (AOP) : Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
• Container : Spring contains and manages the life cycle and configuration of application objects.
• Framework : Spring provides most of the intra functionality leaving rest of the coding to the developer.
What are the different modules in Spring framework?
• The Core container module
• Application context module
• AOP module (Aspect Oriented Programming)
• JDBC abstraction and DAO module
• O/R mapping integration module (Object/Relational)
• Web module
• MVC framework module
What is the Core container module?
This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container.
What is Application context module?
The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.

What is AOP module?
The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring. Using Spring’s metadata support, we will be able to add annotations to our source code that instruct Spring on where and how to apply aspects.

What is JDBC abstraction and DAO module?
Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a Spring application.

What are object/relational mapping integration module?
Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.

What is web module?
This module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.


Bean lifecycle in Spring framework?
1. The spring container finds the bean’s definition from the XML file and instantiates the bean.
2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.
3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their
post- ProcessBeforeInitialization()methods will be called.
6. If an init-method is specified for the bean, it will be called.
7. Finally, if there are any BeanPostProcessors associated with the bean, theirpostProcessAfterInitialization() methods will be called.
What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

What are the different types of IOC (dependency injection) ?
• Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
• Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
• Interface Injection (e.g. Avalon): Injection is done through an interface.
What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
• A means for resolving text messages, including support for internationalization.
• A generic way to load file resources.
• Events to beans that are registered as listeners.
The three commonly used implementation of 'Application Context' are
• ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code .
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

• FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");

• XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
What are singleton beans and how can you create prototype beans?
Beans defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.



What are the important beans lifecycle methods?
There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.
How can you override beans default lifecycle methods?
The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods. Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.
What do you mean by Bean wiring ?
The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring. Or
Combining together beans within the Spring container is known as bean wiring or wiring. When wiring beans, you should tell the container what beans are needed and how the container should use dependency injection to tie them together.
What do you mean by Auto Wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. Or
You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together. All you have to do is just set the autowire attribute of bean tag to an autowire type.
The autowiring functionality has five modes.
• no
• byName
• byType
• constructor
• autodetect

Different types of events related to Listeners?
There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses oforg.springframework.context.Application-Event. They are
• ContextClosedEvent – This is fired when the context is closed.
• ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
• RequestHandledEvent – This is fired when the web context handles any request.
What is an Aspect?
An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, you can create a logging aspect and apply it throughout your application using AOP.

What is a Jointpoint?
A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

What is an Advice?
Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints.

What is a Pointcut?
A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied.

What is an Introduction in AOP?
An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing class without having to change the structure of the class, but give them the new behavior and state.
What is a Target?
A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is being applied.
What is a Proxy?
A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.
What is meant by Weaving?
The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into the target object at the specified joinpoints.
What are the different points where weaving can be applied?
Compile Time
Classload Time
Runtime
What are the different advice types in spring?
Around : Intercepts the calls to the target method
Before : This is called before the target method is invoked
After : This is called after the target method is returned
Throws : This is called when the target method throws and exception

Around : org.aopalliance.intercept.MethodInterceptor
Before : org.springframework.aop.BeforeAdvice
After : org.springframework.aop.AfterReturningAdvice
Throws : org.springframework.aop.ThrowsAdvice
What are the different types of AutoProxying?
BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator
Metadata autoproxying
What is the Exception class related to all the exceptions that are thrown in spring applications?
DataAccessException - org.springframework.dao.DataAccessException
How can you configure a bean to get DataSource from JNDI?



java:comp/env/jdbc/myDatasource


44) How can you create a DataSource connection pool?



${db.driver}


${db.url}


${db.username}


${db.password}



What are the ways to access Hibernate using Spring ?
• Inversion of Control with a HibernateTemplate and Callback
• Extending HibernateDaoSupport and Applying an AOP Interceptor
What are Bean scopes in Spring Framework ?
The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext). The scopes supported are listed below:
Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware SpringApplicationContext.

What are the types of Advice?
Types of advice:
• Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
• After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
• After throwing advice: Advice to be executed if a method exits by throwing an exception.
• After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
• Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception
What is SQLExceptionTranslator ?
SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own data-access-strategy-agnostic org.springframework.dao.DataAccessException.

Transaction Isolation Levels

1. ISOLATION_DEFAULT
2. ISOLATION_READ_UNCOMMITTED
- Dirty reads, non-repeatable reads and phantom reads can occur.
3. ISOLATION_READ_COMMITTED
– Dirty reads are prevented; non-repeatable reads and phantom reads can occur.
4. ISOLATION_REPEATABLE_READ
– Dirty reads and non-repeatable reads are prevented; phantom reads can occur.
5. ISOLATION_SERIALIZABLE
– Dirty reads, non-repeatable reads and phantom reads are prevented


Transaction Propagation
1.PROPAGATION_REQUIRED
– Support a current transaction, create a new one if none exists.
2.PROPAGATION_SUPPORTS
– Support a current transaction, execute non-transactionally if none exists.
3. PROPAGATION_MANDATORY
– Support a current transaction, throw an exception if none exists.
4. PROPAGATION_REQUIRES_NEW
– Create a new transaction, suspend the current transaction if one exists.
5.PROPAGATION_NOT_SUPPORTED
–Always Executes non-transactionally, suspend the current transaction if active transaction exists.
6. PROPAGATION_NEVER
–Always Executes non-transactionally, Exception thrown if active transaction exists.
7. PROPAGATION_NESTED
– Runs Nested transaction if one exists. Otherwise Executes PROPAGATION_REQUIRED.


Anomaly Example
Dirty Reads
A dirty read happens when a transaction reads data that is being modified by another transaction that has not yet committed. Transaction A begins.
UPDATE employee SET salary = 31650
WHERE empno = '000090'
Transaction B begins.
SELECT * FROM employee
(Transaction B sees data updated by transaction A. Those updates have not yet been committed.)
Non-Repeatable Reads
Non-repeatable reads happen when a query returns data that would be different if the query were repeated within the same transaction. Non-repeatable reads can occur when other transactions are modifying data that a transaction is reading. Transaction A begins.
SELECT * FROM employee
WHERE empno = '000090'
Transaction B begins.
UPDATE employee SET salary = 30100
WHERE empno = '000090'
(Transaction B updates rows viewed by transaction A before transaction A commits.) If Transaction A issues the same SELECT statement, the results will be different.
Phantom Reads
Records that appear in a set being read by another transaction. Phantom reads can occur when other transactions insert rows that would satisfy the WHERE clause of another transaction's statement. Transaction A begins.
SELECT * FROM employee
WHERE salary > 30000
Transaction B begins.
INSERT INTO employee
(empno, firstnme, midinit,
lastname, job,
salary) VALUES ('000350', 'NICK',
'A','GREEN','LEGAL COUNSEL',35000)
Transaction B inserts a row that would satisfy the query in Transaction A if it were issued again.

Struts

Struts is the open source MVC FrameWork.It is Flexible control layer based on standard technologies like java servlet,Java beans,Resourcebundle and XML.Structs privodes own controller component and integrates with other technologies to provide model and view.
For model structs integrate with standard data access like JDBC or EJB and other third party package like hibernate and ibatis. Or Other Object relation bridge.For View , Struts works well Jsp,JSTL or Other Presentation Layer System.

ActionServlet Class: It is the FrontEnd Controller of Struct Framework.It receive the requests from browser and make decision where to send the request based on struts-config.xml. Controller is responsible for handling all the requests

Action class: is Part of Model and wrapper around the business layer.
The purpose of action class is translate httprequest to business logic.
To use the action we need to subclass it and overwrite the execute method.

Action Form: represents the HTTP input data. They carry data over the one request to another.it maintance the state of an application.It is the Abstract class,which is subclassed for every input form model.the struts-config.xml file controls,which HTML Form request maps to which Action Form.

ActionMapping: means the action which is mapped to particular request.its configured in Struts-config.xml through action-tag.in which mention type of action form name action name and input formdetails.

ActionForward: means class which takes of forwarding the actions which are found through the action mapping class to their respective File.


1.Forward Action
2.Dispatch Action
3.include Action
4.LookUpDispatch Action
5.MappingDispatch Action
6.switch Action
7.LocaleDispatch Action

1.ForwardActionclass enables a user to forward request to the specified URL. ForwardAction is an utility classs that is used in cases where a user simply needs to forward the control to an another JSP page. Linking directly a JSP to an another, violates the MVC principles.

2.DispatchAction is specialized child of Struts Action class. It combines or group the methods that can further access the bussiness logic at a single place. The method can be anyone from CRUD. method also can have user-defined methods

3.IncludeAction is much like ForwardAction except that the resulting resource is included in the HTTP response instead of being forwarded to. It is rarely used. Its only significant use is to integrate legacy applications with Struts transparently

4.LookupDispatchAction: This type of aggregation is useful in situations where in you have multiple submit buttons in a single form. The class must extend LookupDispatchAction

5. MappingDispatchAction class is much like the DispatchAction class except that it uses a unique action corresponding to a new request , to dispatch the methods

6. SwitchAction class is used to support switching from module to module. Let's say you have an action that wants to forward to an action in another module.


Controller class ActionServlet is he request Dispatcher.
where as Action classes are request processer.



DispatchAction and LookupDispatchAction both are used to combine related operations into a single class, so that they can share common resources like helper methods without exposing them to other classes.

DispatchAction selects the method to execute depending on the request parameter value which is configured in the xml file. This will be problematic for internationalized applications since the values will be different for different locales. So, LookupDispatchAction looks into the resource bundle file and find out the corresponding key name. We can map this key name to a method name by overriding the getKeyMethodMap() method.

RequestDispatcher class is mainly used to 'pass on' the current request to another program (servlet) and therefore allows 'chaining' of the programs. A RequestDispatcher primarily contains two methods include() and forward().include() method includes the response of another program while forward() method forwards the request of the current program to another one.

RequestDispatcher vs sendRedirect:

1) forward() is a server-side redirect. url on the browser doesn't change. This method is normally used for sending a request and response object to resources (servlets or JSP's) which are in the same ServletContext.
RequestDispatcher rd = request.getRequestDispatcher("/forms/search");
rd.forward(request, response);

2) sendRedirect() happens on the client-side i.e server sends a redirect url to a client status of http 301 and the url on the browser changes to the redirected value. RequestDispatcher in ServletContext can be used to dispatch the request to a different context.
Response.sendRedirect();


<span style="font-weight:bold;">ForwardAction Ex:</span>

<action
path="/success"
type="org.apache.struts.actions.ForwardAction"
parameter="/pages/Success.jsp"
input="/pages/ForwardAction.jsp"
scope="request"
validate="false">
</action>

<span style="font-weight:bold;">DispatchAction EX:</span>

<action path="/user" parameter="parameter"
type="net.viralpatel.struts.helloworld.action.UserManagementAction">
<forward name="success" path="/UserSuccess.jsp" />
<forward name="failure" path="/UserSuccess.jsp" />
</action>

<span style="font-weight:bold;">.IncludeAction</span>
<action path=”/legacyA”
parameter=”/xoom/LegacyServletA”
type=”org.apache.struts.actions.IncludeAction” />

<span style="font-weight:bold;">LookupDispatchAction EX:</span>

<html:submit property="submit"><bean:message key="button.create"/></html: submit >
<html:submit property="submit"><bean:message key="button.read"/></html: submit >
...
The example Action class will be as follows

public class CRUDLookUpDispatchAction extends LookupDispatchAction {

protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("button.create", "create");

return map;
}
public ActionForward create(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
return (mapping.findForward("success"));
}

SwitchAction Ex:

1. First, map a SwitchAction into the default module as shown here:
<action
path="/switch"
type="org.apache.struts.actions.SwitchAction"
>
</action>
2. Now, you can set up a forward in the action that edits the users as follows:
<action
path="/userSubmit"
attribute="userForm"
input="/form/userForm.jsp"
name="userForm"
scope="request"
type="action.UserAction">
<forward
name="success"
path="/switch.do?page=/listUsers.do&prefix=/admin"
/>
</action>

<span style="font-weight:bold;">MappingDispatchAction Ex:</span>
<action path="/MappingDispatchAction"
type="roseindia.net.MappingDispatch_Action"
parameter="edit"
input="/pages/MappingDispatchAction.jsp"
scope="request"
validate="false">
<forward name="edit" path="/pages/MappingDispatchActionEdit.jsp" />
</action>

Internationalization
Internationalization is a complex and involved subject. In brief, it refers to the automatic rendering of an application in the user's chosen language. It relates not only to the text itself, but also to numbers, date format, and currency values. Special symbols and alphabetical sorting in different languages bring interesting and unexpected problems with them.

Introduction to Validator Framework
Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server sidevalidation of the form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

WEB.XML
----------------------------------------------

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>

<!-- Standard Action Servlet Configuration (with debugging) -->
<servlet>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationController.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>application</param-name>
<param-value>ApplicationResources</param-value>
</init-param>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>validate</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>


<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>


<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>

</web-app>


struts-config.xml
----------------------------------------------------------
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
Form bean Definitions

<form-beans>
<form-bean name="CustomerForm" type="mybank.example.CustomerForm">
<form-property name=”username” tpe=”java.lang.String”>
<form-property name=”password” tpe=”java.lang.String”>
</form-bean>
<form-bean name="LogonForm" type="mybank.example.LogonForm"/>
</form-beans>
Global Forward Definitions
<global-forwards>
<forward name="logon" path="/logon.jsp"/>
<forward name="logoff" path="/logoff.do"/>
</global-forwards>
Action Mappings
<action-mappings>
<action path=”/welcome” type=”org.apache.struts.actions.ForwordAction” parameter=”.mainLayout”/>

<action path="/submitDetailForm" type="mybank.example.CustomerAction" name="CustomerForm" scope="request"
validate="true" input="/CustomerDetailForm.jsp">
<forward name="success" path="/ThankYou.jsp" redirect=”true” />
<forward name="failure" path="/Failure.jsp" />
</action>

<action path=”/logoff” parameter=”/logoff.jsp” type=”org.apache.struts.action.ForwardAction” />
</action-mappings>
Controller Configuration
<controller processorClass="org.apache.struts.tiles.Tiles.RequestProcessor" />
Message Resource Definition
<message-resources parameter="mybank.ApplicationResources"/>
PlugIn Definition
<plugin className=”org.apache.struts.tiles.TilesPlugIn”>
<set-property name=”definations-config” value=”/WEB-INF/tiles-defs.xml”/>
<set-property name=”moduleWare” value=”truel”/>
</plugin>

<plugin className=”org.apache.struts.validator.ValidatorPlugIn”>
<set-property name=”pathnames” value=”/WEB-INF/validation.xml,/WEB-INF/validation-rules.xml”/>
</plugin>

<plugin className=”org.springframework.web.struts.ContextLoaderPlugIn”>
<set-property name=”contextConfigLocation” value=”/WEB-INF/applicationContext.xml”/>
</plugin>
</struts-config>

applicationContext.xml
-------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="myHibernateProperties" class="org.springframework.bean.factory.PropertyFactoryBean" destroy-method="close">
<property name="hibernateProperties"><value>classpath:Hibernate.properties</value></property>
</bean>

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>(jdbc.oracle.driver.OracleDriver)
<property name="url"><value>jdbc:mysql://localhost:3306/techfaq</value></property>(jdbc:oracle:thin:@localhost1521:dbname)
<property name="username"><value>techfaq</value></property>
<property name="password"><value>techfaq</value></property>
</bean>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref bean="myDataSource"/></property>
<property name="mappingResources">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<value><ref local=”myHibernateProperties”></value>
</property>
</bean>

<bean id=”myTransactionManager” class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
<property name="sessionfactory"><ref bean="mySessionFactory"/></property>
</bean>

<bean id=”baseTransactionProxy” class=”org.springframework.transaction.interceptor.TransactionProxyFactoryBean”>
<property name=”transactionManager” ><ref local=”myTransactionManager”/></property>
<property name=”transactionAttributes” >
<props>
<prop key=”get*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop>
<prop key=”load*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop>
<prop key=”find*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop>
<prop key=”save*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
<prop key=”update*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
<prop key=”delete*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
<prop key=”clean*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
<prop key=”*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
</props>
</property>
</bean>

<bean id="userdao” parent=”baseTransactionProxy”>
<property name="target">
<bean id=”targetUserDAO” class=”org.spb.UserHibernateDAO”>
<property name=”sessionFactory”> <ref local=”mySessionFactory”>
</property>
</bean>
<bean id="userservice" class="com.UserServiceImplementation" autowire=”autodetect”/>


<bean id="userservice" class="com.UserService">
<property name="userdao"><ref bean="userdao"/></property>
</bean>
</beans>

Tuesday, August 11, 2009

Status Ur Site

Tuesday, July 21, 2009

java

Difference between abstract class and interface

1) Abstract class defines few or none of the methods, but
interface defines all the methods..
2) Abstract classes should have subclasses else that will
be useless..
Interfaces must have implementations by other classes else
that will be useless
3)only an interface can extend another interface, but any
class can extend an abstract class..
4)All variable in interfaces are final by default

struts

Load Multiple struts-config Files


Open web.xml file and edit


configname>
/WEB-INF/struts-config.xml,/WEB-INF/struts-one-config.xml,/WEB-INF/struts-two-config.xml,/WEB-INF/struts-three-config.xmlparam-value>

spring

spring