News Update :
Powered by Blogger.
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

What is Error and What is Exception ..?

Penulis : Unknown on Monday, October 25, 2010 | 6:28 AM

Monday, October 25, 2010


Difference between Error and Exception, and how do we handle them in which scenarios?

In any programming language there can be three kinds of errors.

1. Syntax Errors

The mistakes done while writing statements. For example, instead of "WRITE", if you type "WIRTE" it is a syntax error.

Compiler can detect these types of errors. You will not be able to run the program till these errors are rectified.
2. Runtime Errors (Exceptions)

Runtime Errors are thrown when the situation occurs during execution of program where the system will not know how to deal with such situation. For example, you have written a program that takes an excel file and reads the data and stores in the database. You have done the program perfectly. No syntax errors. But while executing the program, if the user enters a filename that does not exist, the program will not know what to do next, at that time runtime error occurs. Runtime error terminates the execution of the program abruptly.

Runtime errors mostly occur due to incorrect user entries or improper usage of system resources by program. These runtime errors can be avoided if we catch the exceptions. You can handle every possible exception and throw user defined messages during the execution and avoid abrupt termination of the program.

3. Logical Errors

Logical errors are obviously the mistake done in the logic by programmer.

For example, Value = Rate - Discount is the normal universal calculation. By mistake if you have typed Value = Rate + Discount, it is neither syntax error nor runtime error. Your program is successful but result is wrong.

This can be corrected only through thorough study of the program or worst case debugging.
comments | | Read More...

Hibernate Interview Questions (Part 3)

Penulis : Unknown on Sunday, October 24, 2010 | 10:58 AM

Sunday, October 24, 2010


Hibernate Interview Questions Part 3


Q. How will you configure Hibernate?

Answer:

The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.

" hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.

" Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.


Q. What is a SessionFactory? Is it a thread-safe object?

Answer:

SessionFactory is Hibernate s concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();


Q. What is a Session? Can you share a session object between different theads? Answer:

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.

&
public class HibernateUtil {
&
public static final ThreadLocal local = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session
if(session == null) {
session = sessionFactory.openSession();
local.set(session);
}
return session;
}
}

It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy.


Q. What are the benefits of detached objects? Answer:


Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

Q. What are the pros and cons of detached objects? Answer:

Pros:

" When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.


Cons

" In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.

" Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.
Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects? Answer :

" Hibernate uses the version property, if there is one.
" If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.
" Write your own strategy with Interceptor.isUnsaved().

Q. What is the difference between the session.get() method and the session.load() method?

Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.


Q. What is the difference between the session.update() method and the session.lock() method?
Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.

Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.

Q. How would you reatach detached objects to a session when the same object has already been loaded into the session?

You can use the session.merge() method call.


Q. What are the general considerations or best practices for defining your Hibernate persistent classes?


1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.

2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.


3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.

4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.

5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

What are Collection types in Hibernate?

ArrayType,
Constructor: ArrayType(String role, String propertyRef, Class elementClass, boolean isEmbeddedInXML)
BagType,
Constructor: BagType(String role, String propertyRef, boolean isEmbeddedInXML)
CustomCollectionType, A custom type for mapping user-written classes that implement PersistentCollection
Constructor: CustomCollectionType(Class userTypeClass, String role, String foreignKeyPropertyName, boolean isEmbeddedInXML)
IdentifierBagType,
Constructor: IdentifierBagType(String role, String propertyRef, boolean isEmbeddedInXML)
ListType,
Constructor: ListType(String role, String propertyRef, boolean isEmbeddedInXML)
MapType,
Constructor: MapType(String role, String propertyRef, boolean isEmbeddedInXML)
SetType
Constructor: SetType(String role, String propertyRef, boolean isEmbeddedInXML)
comments | | Read More...

Hibernate Interview Questions (part 2)

Hibernate Interview Questions Part 2.


Q) What are the most common methods of Hibernate configuration?

A) The most common methods of Hibernate configuration are:
* Programmatic configuration
* XML configuration (hibernate.cfg.xml)

Q) What are the important tags of hibernate.cfg.xml?

A) An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.

Q) What are the Core interfaces are of Hibernate framework?

A) People who read this also read:
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
* Session interface
* SessionFactory interface
* Configuration interface
* Transaction interface
* Query and Criteria interfaces

Q) What role does the Session interface play in Hibernate?

A) The Session interface is the primary interface used by Hibernate applications. 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();
Session interface role:
* Wraps a JDBC connection
* Factory for Transaction
* Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

Q) What role does the SessionFactory interface play in Hibernate?

A) The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();

Q) What is the general flow of Hibernate communication with RDBMS?

A) 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

Q) What is Hibernate Query Language (HQL)?

A) Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

Q) How do you map Java Objects with Database tables?

A)
* First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.
* Write hbm.xml, where we map java class to table and database columns to Java class variables.


Q) What Does Hibernate Simplify?

A) Hibernate simplifies:
* Saving and retrieving your domain objects
* Making database column and table name changes
* Centralizing pre save and post retrieve logic
* Complex joins for retrieving related items
* Schema creation from object model

Q) What’s the difference between load() and get()?

A) load() vs. get()
load() :-
Only use the load() method if you are sure that the object exists.
load() method will throw an exception 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():-
If you are not sure that the object exists, then use one of the get() methods.
get() method will return null if the unique id is not found in the database.
get() will hit the database immediately.

Q) What is the difference between and merge and update ?

A)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.

Q) How do you define sequence generated primary key in hibernate?

A) Using tag.
Example:-

SEQUENCE_NAME

Q) Define cascade and inverse option in one-many mapping?

A) cascade – enable operations to cascade to child entities.
cascade=”all|none|save-update|delete|all-delete-orphan”
inverse – mark this collection as the “inverse” end of a bidirectional association.
inverse=”true|false”
Essentially “inverse” indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

Q) What does it mean to be inverse?

A) It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created.

Q) What do you mean by Named – SQL query?

A) 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();

Q) How do you invoke Stored Procedures?

A) { ? = call selectAllEmployees() }

Q) Explain Criteria API?

A) 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();

Q) Define HibernateTemplate?

A) org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

Q) What are the benefits does HibernateTemplate provide?

A) The benefits of HibernateTemplate are :
* HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
* Common functions are simplified to single method calls.
* Sessions are automatically closed.
* Exceptions are automatically caught and converted to runtime exceptions.

Q) How do you switch between relational databases without code changes?

A) Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

Q) If you want to see the Hibernate generated SQL statements on console, what should we do?

A) In Hibernate configuration file set as follows:
true

Q) What are derived properties?

A) The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.
People who read this also read:
Core Java Questions
Spring Questions
SCJP 6.0 Certification
EJB Interview Questions
Servlets Questions

Q) What is component mapping in Hibernate?

A)
* A component is an object saved as a value, not as a reference
* A component can be saved directly without needing to declare interfaces or identifier properties
* Required to define an empty constructor
* Shared references not supported

Q) What is the difference between sorted and ordered collection in hibernate?

A) sorted collection vs. order collection
sorted 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.
If your collection is not large, it will be more efficient way to sort it.
order collection :-
Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is very large, it will be more efficient way to sort it .
comments | | Read More...

Hibernate Interview Questions (Part1)

Hibernate Interview Questions


1) Explain about Hibernate?

Hibernate solves problems such as Object Relational impedance mismatch, etc. It is commonly used for object and query service. It helps data base developers develop classes which include inheritance, association, composition and polymorphism. A developer or user can express queries either in HQL or SQL.

2) Explain about the primary feature of Hibernate?

Primary feature of hibernate is to java classes to database tables. Data query and retrieval is also possible with Hibernate. Application portability is a key feature in Hibernate it allows developers to port applications to almost all SQL databases.

3) Explain about transparent persistence of Hibernate?

Transparent persistence is provided for Plain old Java objects or POJOs. For proper functioning of the applications importance should be given to the methods equals () and hash Code methods (). It has a requirement which should be strictly followed in the applications which is a no-argument constructor.

4) Explain about the dirty checking feature of Hibernate?

Dirty checking feature of the Hibernate allows users or developers to avoid time consuming data base write actions. This feature makes necessary updations and changes to the fields which require a change, remaining fields are left unchanged or untouched.

5) Brief about the Session factory interface?

It creates new hibernate sessions by referencing immutable and thread safe objects. Application using hibernate are usually allowed and desgined to implement single instance of the class using this interface. Only single instance of a class can be used which is using this interface.

6) Explain about session interface?

This represents hibernate session which perform the manipulation on the database entities. Some of the activities performed by session interface are as follows they are managing the persistence state, fetching persisted ones and management of the transaction demarcation.

7) Explain the steps involved in creating database applications with Java using Hibernate?

Creating Database applications with Java is made simpler with Hibernate. First Plain old java object needs to be written, XML mapping file should be created which shows relationship between database and class attributes. Hibernate APIs can be used to store persistent objects.

8) Explain about hibernate.cfg.xml?

Hibernate can be configured with two types of files out of which hibernate.cfg.xml is widely used and popular feature. Hibernate consults hibernate.cfg.xml file for its operating properties such as database dialect, connection string and mapping files. These files are searched on class path.

9) Explain about mapping description file?

Mapping description file is the second file which Hibernate uses to configure its functions. This mapping file has an extension *.hbm which instructs mapping between Java class and database tables. The usage of mapping description file rests entirely upon the business entity.

10) Explain about transaction file?

Transactions denote a work file which can save changes made or revert back the changes. A transaction can be started by session.beginTransaction() and it uses JDBC connection, CORBA or JTA. When this session starts several transactions may occur.

11) Explain about mapping files in Hibernate?

Mapping files forms the core of any database mapping tools. These files contain field to field mapping, usually this mapping occurs between classes and attributes. After mapping files they can be persist to the database. Tags can be used to indicate the presence of a primary key.

12) What is the effect when a transient mapped object is passed onto a Sessions save?

When a Sessions save () is passed to a transient mapped object it makes the method to become more persistent. Garbage collection and termination of the Java virtual machine stays as long as it is deleted explicitly. It may head back to its transient state.

13) Explain about version field?

Application level data integrity constants are important if you are making changes to offline information which is again backed by database. Higher level locking or versioning protocol is required to support them. Version field usage comes at this stage but the design and implementation process is left to the developer.

14) State some advantages of hibernate?

Some of the advantages which a developer can get from Hibernate are as follows: -
Mapping of one POJO table to one table is not required in hibernate.
It supports inheritance relationships and is generally a fast tool. Portability is necessary the greater benefit from hibernate. POJOs can be used in other applications where they are applicable.

15) Explain about addClass function?

This function translates a Java class name into file name. This translated file name is then loaded as an input stream from the Java class loader. This addclass function is important if you want efficient usage of classes in your code.

16) Explain about addjar() and addDirectory() methods?

These methods are the most convenient to use in hibernate. These methods allow you to load all your Hibernate documents at a time. These methods simplify code configuration, refactoring, layout, etc. These functions help you to add your hibernate mapping to Hibernate initialization files.

17) Explain about the id field?

This id field corresponds to the surrogate key which is generated by the database. These fields are handled by the id field. Name attribute is used to specify the names of the field and it should correspond to the method name of getid. This also should correspond to long type and the values should be stored I the database in the long column.
comments | | Read More...

Download WebLogic Portal 10GR3 Software.

Penulis : Unknown on Saturday, October 23, 2010 | 4:32 AM

Saturday, October 23, 2010




Oracle WebLogic Server forms part of Oracle Fusion Middleware portfolio and supports Oracle, DB2, Microsoft SQL Server, MySQL Enterprise and other JDBC-compliant databases. Oracle WebLogic Platform also includes:

* Portal which includes Commerce Server and Personalization Server
* WebLogic Integration
* WebLogic Workshop, an Eclipse IDE for Java, SOA and Rich Internet applications
* JRockit, a custom JVM.

WebLogic Server includes .NET interoperability and supports the following native integration capabilities:

* Native enterprise-grade JMS messaging
* Java EE Connector Architecture
* WebLogic/Tuxedo Connector
* COM+ Connectivity
* CORBA connectivity
* IBM WebSphere MQ connectivity

Oracle WebLogic Server Process Edition also includes Business Process Management and Data Mapping functionality. WebLogic supports security policies managed by security administrators. The Oracle WebLogic Server Security Model includes:

* application business logic separated from security code
* complete scope of security coverage for all Java EE and non-Java EE components


Before downloading you should login in Oracle website.

comments | | Read More...

Deploying WAR File With BEA WebLogic Server

Penulis : Unknown on Monday, October 18, 2010 | 2:32 AM

Monday, October 18, 2010


After you install Directory Server Enterprise Edition, you can deploy theWARfile to access
DSCC. Refer to the following procedure for deployment instructions:

To DeployWAR FileWith BEAWebLogic Server
The following example shows how to install DSCC in BEA WebLogic Server on a Solaris 10
system.

1.Create theWAR file for DSCC.

$ install-path/bin/dsccsetup war-file-create
For native packages installation, theWARfile is created in the /var/opt/SUNWdsee7/ directory.
For zip distribution installation, theWARfile is created in the install-path/var directory.

2.Initialize the DSCC registry.

$ install-path/bin/dsccsetup ads-create
Choose password for Directory Service Manager:
Confirm password for Directory Service Manager:
Creating DSCC registry...
DSCC Registry has been created successfully

3.To create server instances on the same host where DSCC is deployed, register the DSCC agent in CommonAgent Container.

$install-path/bin/dsccsetup cacao-reg
Type the following command to check the location and other statistics of your war file and
DSCC registry:
$ install-path/bin/dsccsetup status

4.Deploy theWAR file.

a. Browse theWebLogic console using http://localhost:7001/console.
b. Goto base_domain/Deployments.
c. Click Lock and Edit.
d. Click Install.
e. Click Upload your file(s).
f. In Deployment Archive, select install-path/var/dscc7.war.
g. Click Next.
h. Select dscc7.war and click Next a few times and Finish.
i. Click Activate Changes in the top left corner.

The dscc7 deployment must be in the active state.


Note – The above steps are an example of how dscc7.war file is deployed into BEA WebLogic
Server. The BEA WebLogic Server documentation is the only trustable source of information
for deployingWARfiles.



5.Use http://hostname:port/dscc7 to connect to DSCC.

The default port number for BEA WebLogic Server is 7001.

The Directory ServiceManager Login page displays.
comments | | Read More...

2.1 Main Features of the Java Language

Penulis : Unknown on Sunday, October 17, 2010 | 10:04 AM

Sunday, October 17, 2010

Java follows C++ to some degree, which carries the benefit of it being familiar
to many programmers. This section describes the essential features of Java and
points out where the language diverges from its ancestors C and C++.

2.1.1 Primitive Data

Other than the primitive data types discussed here, everything in Java is an
object. Even the primitive data types can be encapsulated inside librarysupplied
objects if required. Java follows C and C++ fairly closely in its set of
basic data types, with a couple of minor exceptions. There are only three
groups of primitive data types, namely, numeric types, Boolean types, and
arrays.

Numeric Data Types

Integer numeric types are 8-bit byte, 16-bit short, 32-bit int, and 64-bit long.
The 8-bit byte data type in Java has replaced the old C and C++ char data
type. Java places a different interpretation on the char data type, as discussed
below.

There is no unsigned type specifier for integer data types in Java.
Real numeric types are 32-bit float and 64-bit double. Real numeric types
and their arithmetic operations are as defined by the IEEE 754 specification. A
floating point literal value, like 23.79, is considered double by default; you
must explicitly cast it to float if you wish to assign it to a float variable.

Character Data Types

Java language character data is a departure from traditional C. Java’s char data
type defines a sixteen-bit Unicode character. Unicode characters are unsigned
16-bit values that define character codes in the range 0 through 65,535. If you
write a declaration such as
char myChar = ‘Q’;
you get a Unicode (16-bit unsigned value) type that’s initialized to the Unicode
value of the character Q. By adopting the Unicode character set standard for its
character data type, Java language applications are amenable to
internationalization and localization, greatly expanding the market for worldwide
applications.

Boolean Data Types

Java has added a boolean data type as a primitive type, tacitly ratifying
existing C and C++ programming practice, where developers define keywords
for TRUE and FALSE or YES and NO or similar constructs. A Java boolean
variable assumes the value true or false. A Java boolean is a distinct data
type; unlike common C practice, a Java boolean type can’t be converted to
any numeric type.
comments | | Read More...

1.3 The Java Base System

Penulis : Unknown on Wednesday, October 13, 2010 | 12:21 PM

Wednesday, October 13, 2010


The complete Java system includes a number of libraries of utility classes and
methods of use to developers in creating multi-platform applications.

Very briefly, these libraries are:

java.lang—the collection of base types (language types) that are always
imported into any given compilation unit. This where you’ll find the
declarations of Object (the root of the class hierarchy) and Class, plus
threads, exceptions, wrappers for the primitive data types, and a variety of
other fundamental classes.

java.io—streams and random-access files. This is where you find the rough
equivalent of the Standard I/O Library you’re familiar with on most UNIX
systems. A further library is called java.net, and provides support for
sockets, telnet interfaces, and URLs.

java.util—container and utility classes. Here you’ll find classes such as
Dictionary, HashTable, and Stack, among others, plus encoder and
decoder techniques, and Date and Time classes.

java.awt—an Abstract Windowing Toolkit that provides an abstract layer
enabling you to port Java applications easily from one window system to
another. This library contains classes for basic interface components such as
events, colors, fonts, and controls such as buttons and scrollbars.
comments | | Read More...

1.2 Design Goals of Java


The design requirements of Java are driven by the nature of the computing
environments in which software must be deployed.
The massive growth of the Internet and the World-Wide Web leads us to a
completely new way of looking at development and distribution of software.
To live in the world of electronic commerce and distribution, Java must enable
the development of secure, high performance, and highly robust applications on
multiple platforms in heterogeneous, distributed networks.

Operating on multiple platforms in heterogeneous networks invalidates the
traditional schemes of binary distribution, release, upgrade, patch, and so on.
To survive in this jungle, Java must be architecture neutral, portable, and
dynamically adaptable.
The Java system that emerged to meet these needs is simple, so it can be easily
programmed by most developers; familiar, so that current developers can easily
learn Java; object oriented, to take advantage of modern software development
methodologies and to fit into distributed client-server applications;
multithreaded, for high performance in applications that need to perform
multiple concurrent activities, such as multimedia; and interpreted, for
maximum portability and dynamic capabilities.
Together, the above requirements comprise quite a collection of buzzwords, so
let’s examine some of them and their respective benefits before going on.

1.2.1 Simple, Object Oriented, and Familiar

Primary characteristics of Java include a simple language that can be
programmed without extensive programmer training while being attuned to
current software practices. The fundamental concepts of Java are grasped
quickly; programmers can be productive from the very beginning.
Java is designed to be object oriented from the ground up. Object technology has
finally found its way into the programming mainstream after a gestation
period of thirty years. The needs of distributed, client-server based systems
coincide with the encapsulated, message-passing paradigms of object-based
software. To function within increasingly complex, network-based
environments, programming systems must adopt object-oriented concepts.
Java provides a clean and efficient object-based development environment.
Programmers using Java can access existing libraries of tested objects that
provide functionality ranging from basic data types through I/O and network
interfaces to graphical user interface toolkits. These libraries can be extended
to provide new behavior.

Even though C++ was rejected as an implementation language, keeping Java
looking like C++ as far as possible results in Java being a familiar language,
while removing the unnecessary complexities of C++. Having Java retain many
of the object-oriented features and the “look and feel” of C++ means that
programmers can migrate easily to Java and be productive quickly.
1.2.2 Robust and Secure

Java is designed for creating highly reliable software. It provides extensive
compile-time checking, followed by a second level of run-time checking.
Language features guide programmers towards reliable programming habits.
The memory management model—no pointers or pointer
arithmetic—eliminates entire classes of programming errors that bedevil C and
C++ programmers. You can develop Java language code with confidence that
the system will find many errors quickly and that major problems won’t lay
dormant until after your production code has shipped.

Java is designed to operate in distributed environments, which means that
security is of paramount importance. With security features designed into the
language and run-time system, Java lets you construct applications that can’t
be invaded from outside. In the networked environment, applications written
in Java are secure from intrusion by unauthorized code attempting to get
behind the scenes and create viruses or invade file systems.

1.2.3 Architecture Neutral and Portable

Java is designed to support applications that will be deployed into
heterogeneous networked environments. In such environments, applications
must be capable of executing on a variety of hardware architectures. Within
this variety of hardware platforms, applications must execute atop a variety of
operating systems and interoperate with multiple programming language
interfaces. To accommodate the diversity of operating environments, the Java
compiler generates bytecodes—an architecture neutral intermediate format
designed to transport code efficiently to multiple hardware and software
platforms. The interpreted nature of Java solves both the binary distribution
problem and the version problem; the same Java language byte codes will run
on any platform.

Architecture neutrality is just one part of a truly portable system. Java takes
portability a stage further by being strict in its definition of the basic language.
Java puts a stake in the ground and specifies the sizes of its basic data types
and the behavior of its arithmetic operators. Your programs are the same on
every platform—there are no data type incompatibilities across hardware and
software architectures.

The architecture-neutral and portable language environment of Java is known
as the Java Virtual Machine. It’s the specification of an abstract machine for
which Java language compilers can generate code. Specific implementations of
the Java Virtual Machine for specific hardware and software platforms then
provide the concrete realization of the virtual machine. The Java Virtual
Machine is based primarily on the POSIX interface specification—an industrystandard
definition of a portable system interface. Implementing the Java
Virtual Machine on new architectures is a relatively straightforward task as
long as the target platform meets basic requirements such as support for
multithreading.

1.2.4 High Performance

Performance is always a consideration. Java achieves superior performance by
adopting a scheme by which the interpreter can run at full speed without
needing to check the run-time environment. The automatic garbage collector runs
as a low-priority background thread, ensuring a high probability that memory
is available when required, leading to better performance. Applications
requiring large amounts of compute power can be designed such that
compute-intensive sections can be rewritten in native machine code as required
and interfaced with the Java environment. In general, users perceive that
interactive applications respond quickly even though they’re interpreted.

1.2.5 Interpreted, Threaded, and Dynamic

The Java interpreter can execute Java bytecodes directly on any machine to
which the interpreter and run-time system have been ported. In an interpreted
environment such as Java system, the link phase of a program is simple,
incremental, and lightweight. You benefit from much faster development
cycles—prototyping, experimentation, and rapid development are the normal
case, versus the traditional heavyweight compile, link, and test cycles.
Modern network-based applications, such as the HotJava World-Wide Web
browser, typically need to do several things at the same time. A user working
with HotJava can run several animations concurrently while downloading an
image and scrolling the page. Java’s multithreading capability provides the
means to build applications with many concurrent threads of activity.
Multithreading thus results in a high degree of interactivity for the end user.

Java supports multithreading at the language level with the addition of
sophisticated synchronization primitives: the language library provides the
Thread class, and the run-time system provides monitor and condition lock
primitives. At the library level, moreover, Java’s high-level system libraries
have been written to be thread safe: the functionality provided by the libraries is
available without conflict to multiple concurrent threads of execution.
While the Java compiler is strict in its compile-time static checking, the
language and run-time system are dynamic in their linking stages. Classes are
linked only as needed. New code modules can be linked in on demand from a
variety of sources, even from sources across a network. In the case of the
HotJava browser and similar applications, interactive executable code can be
loaded from anywhere, which enables transparent updating of applications.
The result is on-line services that constantly evolve; they can remain innovative
and fresh, draw more customers, and spur the growth of electronic commerce
on the Internet.
comments | | Read More...

1.1 Beginnings of the Java Language Project




Java is designed to meet the challenges of application development in the
context of heterogeneous, network-wide distributed environments. Paramount
among these challenges is secure delivery of applications that consume the
minimum of system resources, can run on any hardware and software
platform, and can be extended dynamically.

Java originated as part of a research project to develop advanced software for a
wide variety of networked devices and embedded systems. The goal was to
develop a small, reliable, portable, distributed, real-time operating
environment.

When the project started, C++ was the language of choice. But
over time the difficulties encountered with C++ grew to the point where the
problems could best be addressed by creating an entirely new language
environment. Design and architecture decisions drew from a variety of
languages such as Eiffel, SmallTalk, Objective C, and Cedar/Mesa.

The result is a language environment that has proven ideal for developing secure,
distributed, network-based end-user applications in environments ranging
from networked-embedded devices to the World-Wide Web and the desktop.
comments | | Read More...

Introduction to Java


The Software Developer’s Burden

Imagine you’re a software application developer. Your programming language
of choice (or the language that’s been foisted on you) is C or C++ . You’ve been
at this for quite a while and your job doesn’t seem to be getting any easier.
These past few years you’ve seen the growth of multiple incompatible
hardware architectures, each supporting multiple incompatible operating
systems, with each platform operating with one or more incompatible
graphical user interfaces. Now you’re supposed to cope with all this and make
your applications work in a distributed client-server environment. The growth
of the Internet, the World-Wide Web, and “electronic commerce” have
introduced new dimensions of complexity into the development process.


The tools you use to develop applications don’t seem to help you much. You’re
still coping with the same old problems; the fashionable new object-oriented
techniques seem to have added new problems without solving the old ones.
You say to yourself and your friends, “There has to be a better way”!
The Better Way is Here Now
Now there is a better way—it’s the Java™ programming language environment
(“Java” for short) from Sun Microsystems. Imagine, if you will, this
development world…
• Your programming language is object oriented, yet it’s still dead simple.
• Your development cycle is much faster because Java is interpreted. The
compile-link-load-test-crash-debug cycle is obsolete—now you just compile
and run.
• Your applications are portable across multiple platforms. Write your
applications once, and you never need to port them—they will run without
modification on multiple operating systems and hardware architectures.
• Your applications are robust because the Java run-time system manages
memory for you.
• Your interactive graphical applications have high performance because
multiple concurrent threads of activity in your application are supported by
the multithreading built into Java environment.
• Your applications are adaptable to changing environments because you can
dynamically download code modules from anywhere on the network.
• Your end users can trust that your applications are secure, even though
they’re downloading code from all over the Internet; the Java run-time
system has built-in protection against viruses and tampering.
You don’t need to dream about these features. They’re here now. The Java
Programming Language Environment provides a portable, interpreted, highperformance,
simple, object-oriented programming language and supporting runtime
environment. This introductory chapter provides you with a brief look at
the main design goals of the Java system; the remainder of this paper examines
the features of Java in more detail.


At the end of this paper you’ll find a chapter that describes the HotJava™
Browser (“HotJava” for short). HotJava is an innovative World-Wide Web
browser, and the first major applications written using the Java environment.
HotJava is the first browser to dynamically download and execute Java code
fragments from anywhere on the Internet, and to so so in a secure manner.
comments | | Read More...

What is the difference between WebServer and Application Server

The Web server



A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser.

Understand that a Web server's delegation model is fairly simple. When a request comes into the Web server, the Web server simply passes the request to the program best able to handle it. The Web server doesn't provide any functionality beyond simply providing an environment in which the server-side program can execute and pass back the generated responses. The server-side program usually provides for itself such functions as transaction processing, database connectivity, and messaging.

While a Web server may not itself support transactions or database connection pooling, it may employ various strategies for fault tolerance and scalability such as load balancing, caching, and clustering—features oftentimes erroneously assigned as features reserved only for application servers.

The application server




As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on an object (or a function in the procedural world).

Such application server clients can include GUIs (graphical user interface) running on a PC, a Web server, or even other application servers. The information traveling back and forth between an application server and its client is not restricted to simple display markup. Instead, the information is program logic. Since the logic takes the form of data and method calls and not static HTML, the client can employ the exposed business logic however it wants.

In most cases, the server exposes this business logic through a component API, such as the EJB (Enterprise JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers. Moreover, the application server manages its own resources. Such gate-keeping duties include security, transaction processing, resource pooling, and messaging. Like a Web server, an application server may also employ various scalability and fault-tolerance techniques.

An example

As an example, consider an online store that provides real-time pricing and availability information. Most likely, the site will provide a form with which you can choose a product. When you submit your query, the site performs a lookup and returns the results embedded within an HTML page. The site may implement this functionality in numerous ways. I'll show you one scenario that doesn't use an application server and another that does. Seeing how these scenarios differ will help you to see the application server's function.
Scenario 1: Web server without an application server

In the first scenario, a Web server alone provides the online store's functionality. The Web server takes your request, then passes it to a server-side program able to handle the request. The server-side program looks up the pricing information from a database or a flat file. Once retrieved, the server-side program uses the information to formulate the HTML response, then the Web server sends it back to your Web browser.

To summarize, a Web server simply processes HTTP requests by responding with HTML pages.
Scenario 2: Web server with an application server

Scenario 2 resembles Scenario 1 in that the Web server still delegates the response generation to a script. However, you can now put the business logic for the pricing lookup onto an application server. With that change, instead of the script knowing how to look up the data and formulate a response, the script can simply call the application server's lookup service. The script can then use the service's result when the script generates its HTML response.

In this scenario, the application server serves the business logic for looking up a product's pricing information. That functionality doesn't say anything about display or how the client must use the information. Instead, the client and application server send data back and forth. When a client calls the application server's lookup service, the service simply looks up the information and returns it to the client.

By separating the pricing logic from the HTML response-generating code, the pricing logic becomes far more reusable between applications. A second client, such as a cash register, could also call the same service as a clerk checks out a customer. In contrast, in Scenario 1 the pricing lookup service is not reusable because the information is embedded within the HTML page. To summarize, in Scenario 2's model, the Web server handles HTTP requests by replying with an HTML page while the application server serves application logic by processing pricing and availability requests.
Caveats

Recently, XML Web services have blurred the line between application servers and Web servers. By passing an XML payload to a Web server, the Web server can now process the data and respond much as application servers have in the past.

Additionally, most application servers also contain a Web server, meaning you can consider a Web server a subset of an application server. While application servers contain Web server functionality, developers rarely deploy application servers in that capacity. Instead, when needed, they often deploy standalone Web servers in tandem with application servers. Such a separation of functionality aids performance (simple Web requests won't impact application server performance), deployment configuration (dedicated Web servers, clustering, and so on), and allows for best-of-breed product selection.


About the author

Tony Sintes is an independent consultant and founder of First Class Consulting, a consulting firm that specializes in bridging disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer, as well as author of Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).

Source: http://www.javaworld.com
comments | | Read More...
 
Design Template by panjz-online | Support by creating website | Powered by Blogger