Dec 20, 2009

Twelve rules for developing more secure Java code

Writing security-conscious Java code can help you avoid security surprises
By Gary Mcgraw and Edward Felten, JavaWorld.com, 12/01/98
download PDF format of this article

This article introduces 12 rules for writing security-critical Java code; 12 rules that all Java developers should abide by. If you are charged with managing a gaggle of Java developers, or if your business relies on the security of Java, make sure your developers follow these rules.
These rules haven't been sugar-coated for mass consumption. They get fairly technical and require broad knowledge of Java to understand. Though experienced Java developers will understand all the rules that follow, less experienced Java developers may have a bit of homework to do. Nevertheless, following these rules will make your Java code more secure.
We base these rules on the experience of many people who have generously discussed their experience in building secure Java code.
In creating these 12 rules, we've drawn from much experience in hunting down Java security bugs, and on advice and observations from people who write and review security-critical Java code for a living. Each rule is designed to eliminate an unexpected gotcha that you might face.
Of course, security is an elusive goal. Following these rules certainly won't provide any guarantee that your code is completely secure. It is easy to write insecure code that follows these rules. By following these goals, however, you will minimize or eliminate certain kinds of security attacks that you might not have thought of.
Think of these rules as a first step. If you are writing code that may be linked or run in conjunction with untrusted code, then you should definitely consider following these rules.
Every attempt has been made to keep the rules simple enough that you can treat them as a checklist to be followed in mechanical fashion. That way you can save your brainpower for other security issues.
 
Rule 1: Don't depend on initialization
Most Java developers think there is no way to allocate an object without running a constructor. But this isn't true: there are several ways to allocate non-initialized objects.
The easy way to protect yourself against this problem is to write your classes so that before any object does anything, it verifies that it has been initialized. You can do this as follows:


  • Make all variables private. If you want to allow outside code to access variables in an object, this should be done via get and set methods. (This keeps outside code from accessing noninitialized variables.) If you're following Rule 3, you'll make the get and set methods final.
  • Add a new private boolean variable, initialized, to each object. 

  • Have each constructor set the initialized variable as its last action before returning.

  • Have each nonconstructor method verify that initialized is true before doing anything. (Note that you may have to make exceptions to this rule for methods called by your constructors. If you do this, it's best to make the constructors call only private methods.)

  • If your class has a static initializer, you will need to do the same thing at the class level. Specifically, for any class that has a static initializer, follow these steps:

  • Make all static variables private. If you want to allow outside code to access static variables in the class, this should be done via static get and set methods. This keeps outside code from accessing noninitialized static variables. If you're following Rule 3, you'll make the get and set methods final.

  • Add a new private static boolean variable, classInitialized, to the class.

  • Have the static constructor set the initialized variable as its last action before returning.
  • Before doing anything, have each static method and each constructor verify that classInitialized is true. (Note: constructors are required to call a constructor of the superclass, or another constructor of the same class, as their first action. So you will have to do that before you check classInitialized.) 
Rule 2: Limit access to your classes, methods, and variables
Every class, method, and variable that is not private provides a potential entry point for an attacker. By default, everything should be private. Make something nonprivate only with good reason, and document that reason. 
 
Rule 3: Make everything final (unless there's a good reason not to)

If a class or method isn't final, an attacker could try to extend it in a dangerous and unforeseen way. By default, everything should be final. Make something nonfinal only if there is a good reason, and document that reason.
You might think you can prevent an attacker from extending your class or its methods by declaring the class nonpublic. But if a class isn't public, it must be accessible from within the same package, and as Rule 4 (below) says, you shouldn't to rely on package scope access restrictions for security.
This advice may seem harsh. After all, the rule is asking you to give up extensibility, which is one of the main benefits of using an object-oriented language like Java. But when you're trying to provide security, extensibility is your enemy: it just provides an attacker with more ways to cause trouble. 
 
Rule 4: Don't depend on package scope
Classes, methods, and variables that aren't explicitly labeled as public, private, or protected are accessible within the same package. Don't rely on this for security. Java classes aren't closed, so an attacker could introduce a new class into your package and use this new class to access the things you thought you were hiding. (A few packages, such as java.lang, are closed by default, and a few Java virtual machines (JVMs) let you close your own packages. But you're better off assuming packages aren't closed.)
Package scope makes a lot of sense from a software-engineering standpoint, since it prevents innocent, accidental access to things you want to hide. But don't depend on it for security.
Maybe we'll get sealed classes in the future.

Rule 5: Don't use inner classes
Some Java language books say inner classes can be accessed only by the outer classes that enclose them. But this isn't true. Java bytecode has no concept of inner classes, so inner classes are translated by the compiler into ordinary classes that happen to be accessible to any code in the same package. And Rule 4 says not to depend on package scope for protection.
But wait, it gets worse. An inner class gets access to the fields of the enclosing outer class, even if the these fields are declared private. And the inner class is translated into a separate class. To let this separate class access the fields of the outer class, the compiler silently changes these fields from private to package scope! It's bad enough that the inner class is exposed; but it's even worse that the compiler is silently overruling your decision to make some fields private. Don't use inner classes if you can help it. (Ironically, the new JDK 1.2 PrivilegedAction API requires you to use an inner class to write privileged code. For more details, see our book Securing Java and the developer.com article referenced below.) That's one reason we don't like the PrivilegedAction API.) 
 
Rule 6: Avoid signing your code
Code that isn't signed will run without any special privileges. And code with no special privileges is much less likely to do damage.
Of course, some of your code might have to acquire and use privileges to perform some dangerous operation. Work hard to minimize the amount of privileged code, and audit the privileged code more carefully than the rest. 
 
Rule 7: If you must sign your code, put it all in one archive file
By following this rule, you will help prevent an attacker from carrying out a mix-and-match attack, in which the attacker constructs a new applet or library that links some of your signed classes together with malicious classes, or links together signed classes that you never meant to be used together. By signing a group of classes together, you make such attacks more difficult. Existing code-signing systems do an inadequate job of preventing mix-and-match attacks, so this rule cannot prevent such attacks completely. But using a single archive can't hurt.
Some code-signing systems let you examine other classes to see who signed them. If you're using a code-signing system that allows this, you can put code into the static constructors of your classes to verify that the "surrounding" classes have been signed by the expected person.
This measure doesn't completely prevent mix-and-match attacks, since an adversary can still mix together classes you signed at different times -- for example, by mixing version 1 of Class A with version 2 of Class B. If you're worried about this kind of inter-version mix-and-match attack, you can put each class's "version stamp" in a public final variable, and then have each class check the version stamps of its surrounding classes. 
 
Rule 8: Make your classes noncloneable
Java's object cloning mechanism can allow an attacker to manufacture new instances of classes you define, without executing any of your constructors. If your class isn't cloneable, the attacker can define a subclass of your class, and make the subclass implement java.lang.Cloneable. This lets an attacker create new instances of your class. The new instances are made by copying the memory images of existing objects; though this is sometimes an acceptable way to make a new object, it often is not.
Rather than worry about this, you're better off making your objects noncloneable. You can do this by defining the following method in each of your classes:

public final void clone() throws java.lang.CloneNotSupportedException {
throw new java.lang.CloneNotSupportedException();
}
If you want your class to be cloneable, and you've considered the
consequences of that choice, then you can still protect yourself. If you're
defining a clone method yourself, make it final. If you're relying on a
nonfinal clone method in one of your superclasses, then define this
method:
public final void clone() throws java.lang.CloneNotSupportedException {
super.clone();
}
This prevents an attacker from redefining your clone method.

Rule 9: Make your classes nonserializeable
Serialization is dangerous because it allows adversaries to get their hands on the internal state of your objects. An adversary can serialize one of your objects into a byte array that can be read. This allows the adversary to inspect the full internal state of your object, including any fields you marked private, and including the internal state of any objects you reference.
To prevent this, you can make your object impossible to serialize. To achieve this goal, declare the writeObject method: 
 
private final void writeObject(ObjectOutputStream out)
throws java.io.IOException {
throw new java.io.IOException("Object cannot be serialized");
}




This method is declared final so that a subclass defined by the adversary cannot override it.

Rule 10: Make your classes nondeserializeable

This rule is even more important than the previous one. Even if your class isn't serializeable, it may still be deserializeable. An adversary can create a sequence of bytes that happens to deserialize to an instance of your class. This is dangerous, since you do not have control over what state the deserialized object is in. You can think of deserialization as another kind of public constructor for your object; unfortunately it's a kind of constructor that is difficult for you to control.
You can prevent this kind of attack by making it impossible to deserialize a byte stream into an instance of your class. You can do this by declaring the readObject method:
private final void readObject(ObjectInputStream in)
throws java.io.IOException {
throw new java.io.IOException("Class cannot be deserialized");
}






As above, this method is declared final to prevent the adversary from overriding it.

Rule 11: Don't compare classes by name

Sometimes you want to compare the classes of two objects to see whether they are the same; or you want to see whether an object has a particular class. When you do this, be aware that there can be multiple classes with the same name in a JVM. It is a mistake to compare classes by name since different classes can have the same name. A better method is to compare class objects for equality directly. For example, given two objects, A and B, if you want to see whether they are the same class, use this code:
if(a.getClass() == b.getClass()){
// objects have the same class
}else{
// objects have different classes
}
You should also be on the lookout for cases of less direct by-name
comparisons. Suppose, for example, you want to see whether an object
has the class "Foo." Here is the wrong way to do it:
if(obj.getClass().getName().equals("Foo")) // Wrong!
// objects class is named Foo
}else{
// object's class has some other name
}
Here's a better way to do it:
if(obj.getClass() == this.getClassLoader().loadClass("Foo")){
// object's class is equal to the class that this class calls "Foo"
}else{
// object's class is not equal to the class that
// this class calls "Foo"
}




Do note the legalistic comments in the last example. Whenever you use class names, you open yourself up to mix-and-match attacks, as described in Rule 7. You should also know that the Java language forces you to use class names all the time: in variable declarations, instanceof expressions, and exception-catching blocks. Only the designers of Java can prevent mix-and-match attacks, but you can avoid making the problem worse by avoiding by-name class comparisons. 
Core Security Patterns: Best Practices and Strategies for J2EE(TM), Web Services, and Identity Management 
 
Rule 12: Secrets stored in your code won't protect you
You might be tempted to store secrets such as cryptographic keys in the code for your application or library. Secrets stored in this way are completely accessible to anybody who runs your code. There is nothing to stop a malicious programmer or virtual machine from looking inside your code and learning its secrets.
Code obfuscation is another way of storing a secret in your code; in the case of obfuscation the secret is simply the algorithm used by your code. There's not much harm in using an obfuscator, but you shouldn't believe it will provide strong protection. There is no real evidence that it is possible to obfuscate Java source code or bytecode so that a dedicated adversary with good tools cannot reverse the obfuscation.


Conclusion
Writing secure Java code is very difficult. There is no magic bullet that will solve your security problems; all you can do is think hard (perhaps with help from formal analysis tools) and use prudent engineering practices to minimize risks. Sometimes a pair of objective outside eyes can help. The rules set forth here are intended to describe prudent engineering practices for writing secure Java code. They won't solve your security problems, but they will reduce the number of ways things can go wrong.

Oct 7, 2009

Features of Java

Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a single language is idle to this feature but java is more closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM.

Simple
There are various features that makes the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the
java programs that can crash the system but we can not say about the other programming languages. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and deallocation system.

Object Oriented
To be an Object Oriented language, any language must follow at least the four characteristics.

  • Inheritance : It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding the additional features as needed.
  • Encapsulation: : It is the mechanism of combining the information and providing the abstraction.
  • Polymorphism: : As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the
    functions having the same name based on the signatures of the methods.
  • Dynamic binding : Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way of providing the maximum functionality to a program about the specific type at runtime.

As the languages like Objective C, C++ fulfills the above four characteristics yet they are not fully object oriented languages because they are structured as well as object oriented languages. But in case of java, it is a fully Object Oriented language because object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into object by using the wrapper class.

Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.

Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet
programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.

Portable
The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the processor. These features makes the java as a portable language.

Dynamic
While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet.

Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading.

Performance
Java uses native code usage, and lightweight process called threads. In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance.

Multithreaded
As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be more delighted to know another feature of Java which is Multithreaded.
Java is also a Multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer.
Multithreading
programming is a very interesting concept in Java. In multithreaded programs not even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs. This is how Multithreading works in Java which you will soon come to know in details in later chapters.

Interpreted
We all know that Java is an interpreted language as well. With an interpreted language such as Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.

Architecture Neutral
The term architectural neutral seems to be weird, but yes Java is an architectural neutral language as well. The growing popularity of
networks makes developers think distributed. In the world of network it is essential that the applications must be able to migrate easily to different computer systems. Not only to computer
systems but to a wide variety of hardware architecture and Operating system architectures as well. The Java compiler does this by generating byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly.
The compiler generates an architecture-neutral object file format to enable a Java application to execute anywhere on the network and then the compiled code is executed on many processors, given the presence of the Java runtime system.
Hence Java was designed to support applications on network. This feature of Java has thrived the programming language.

Aug 27, 2009

Microsoft SQL Server Constraints

A constraint is a property assigned to a column or the set of columns in a table that prevents certain types of inconsistent data values from being placed in the column(s). Constraints are used to enforce the data integrity. This ensures the accuracy and reliability of the data in the database. The following categories of the data integrity exist:

  • Entity Integrity
  • Domain Integrity
  • Referential integrity
  • User-Defined Integrity
Entity Integrity

Entity integrity ensures that there are no duplicate rows in a table. You can apply entity integrity to a table by specifying a PRIMARY KEY constraint. For example, the ProductID column of the Products table is a primary key for the table.

Domain Integrity

Domain integrity ensures the data values inside a database follow defined rules for values, range, and format. A database can enforce these rules using a variety of techniques, including CHECK constraints, UNIQUE constraints, and DEFAULT constraints. These are the constraints we will cover in this article, but be aware there are other options available to enforce domain integrity. Even the selection of the data type for a column enforces domain integrity to some extent. For instance, the selection of datetime for a column data type is more restrictive than a free format varchar field.

Referential Integrity

Referential integrity ensures the relationships between tables remain preserved as data is inserted, deleted, and modified. You can apply referential integrity using a FOREIGN KEY constraint. The ProductID column of the Order Details table has a foreign key constraint applied referencing the Orders table. The constraint prevents an Order Detail record from using a ProductID that does not exist in the database. Also, you cannot remove a row from the Products table if an order detail references the ProductID of the row.

Entity and referential integrity together form key integrity.

User-Defined Integrity

User-Defined Integrity enforces some specific business rules that do not fall into entity, domain, or referential integrity categories.

Each of these categories of the data integrity can be enforced by the appropriate constraints. Microsoft SQL Server supports the following constraints:

  • PRIMARY KEY
  • UNIQUE
  • FOREIGN KEY
  • CHECK
  • NOT NULL


A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity.

A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.

From a SQL point of view, there are three methods available to add a unique constraint to a table. The first method is to create the constraint inside of CREATE TABLE as a column constraint. A column constraint applies to only a single column. The following SQL will create a unique constraint on a new table: Products_2.

CREATE TABLE Products_2

(

ProductID int PRIMARY KEY,

ProductName nvarchar (40) Constraint IX_ProductName UNIQUE

)


A FOREIGN KEY constraint prevents any actions that would destroy link between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.

A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity.


Check constraints contain an expression the database will evaluate when you modify or insert a row. If the expression evaluates to false, the database will not save the row. Building a check constraint is similar to building a WHERE clause. You can use many of the same operators (>, <, <=, >=, <>, =) in additional to BETWEEN, IN, LIKE, and NULL. You can also build expressions around AND and OR operators. You can use check constraints to implement business rules, and tighten down the allowed values and formats allowed for a particular column.

CREATE TABLE Products_2

(

ProductID int PRIMARY KEY,

UnitPrice money CHECK(UnitPrice > 0 AND UnitPrice < 100)

)


A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints.

Using SQL you can use NULL or NOT NULL on a column definition to explicitly set the nullability of a column. In the following example table, the FirstName column will accept NULL values while LastName always requires a non NULL value. Primary key columns require a NOT NULL setting, and default to this setting if not specified.

CREATE TABLE Employees_2

(

EmployeeID int PRIMARY KEY,

FirstName varchar(50) NULL,

LastName varchar(50) NOT NULL,

)


Disabling Constraints

Special situations often arise in database development where it is convenient to temporarily relax the rules. For example, it is often easier to load initial values into a database one table at a time, without worrying with foreign key constraints and checks until all of the tables have finished loading. After the import is complete, you can turn constraint checking back on and know the database is once again protecting the integrity of the data.

Note: The only constraints you can disable are the FOREIGN KEY constraint, and the CHECK constraint. PRIMARY KEY, UNIQUE, and DEFAULT constraints are always active.

Disabling a constraint using SQL is done through the ALTER TABLE command. The following statements disable the CHECK constraint on the UnitsOnOrder column, and the FOREIGN KEY constraint on the CategoryID column.

ALTER TABLE Products NOCHECK CONSTRAINT CK_UnitsOnOrder

ALTER TABLE Products NOCHECK CONSTRAINT FK_Products_Categories

If you need to disable all of the constraints on a table, manually navigating through the interface or writing a SQL command for each constraint may prove to be a laborious process. There is an easy alternative using the ALL keyword, as shown below:

ALTER TABLE Products NOCHECK CONSTRAINT ALL

Aug 22, 2009

Joins examples in SQL Server 2005

Joins in SQL Server allows the retrieval of data records from one or more tables having some relation between them. Logical operators can also be used to drill down the number of records to get the desired output from sql join queries.

Inner Join: Inner Join is a default type join of SQL Server. It uses logical operators such as =, >,< to match the records in two tables. Inner Join includes equi join and natural joins.

SQL Inner Join Examples

SELECT C.CATEGORYID, C.CATEGORYNAME, P.PRODUCTID, P.PRODUCTNAME, P.UNITPRICE FROM CATEGORIES C INNER JOINPRODUCTS P ON P.CATEGORYID = C.CATEGORYIDWHERE P.UNITPRICE = 10ORDER BY C.CATEGORYNAME, P.PRODUCTNAME

SQL Inner Natural

This inner join query will return the categoryid, categoryname, productid, productname, unitprice where product unit price = 10

SQL Inner Natural Join Examples

SELECT C.*, P.PRODUCTID, P.PRODUCTNAME FROM CATEGORIES C INNER JOINPRODUCTS P ON P.CATEGORYID = C.CATEGORYID

This natural join query will return all the columns of categories table and prodcutId and productName from products table. You can further modify this natural inner join query as per your requirements to visualize the data by specifying the column names of categories table also.

SQL Inner Equi Join Examples

Inner join is a default type of SQL Join that return the records matching in all the tables joined in sql query satisfying the condition specified in WHERE clause.
Inner join includes 3 types of joins similar to one another.

Self Join: Self join joins a single sql database table to itself. Equi Join: Equi Join returns all the columns from both tables and filters the records satisfying the matching condition specified in Join “ON” statement of sql inner join query.

USE NORTHWIND SELECT * FROM CATEGORIES C INNER JOINPRODUCTS P ON P.CATEGORYID = C.CATEGORYID

Result will display the following columns: CategoryID, CategoryName, Description, Picture, ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued Above equi join sql query will display the categoryId two times in a row because both the tables have categoryId column. You can convert the result into natural join by elimination the identical columns and unnecessary columns.

Outer Join: Outer Join has further 3 sub categories as left, right and full. Outer Join uses these category names as keywords that can be specified in the FROM clause. Left Outer Join: Left Outer Join returns all the rows from the table specified first in the Left Outer Join Clause. If in the left table any row has no matching record in the right side table then that row returns null column values for that particular tuple. Inner joins return only those rows from both sql database tables having matching records in both the tables whereas left outer join returns all the rows from the left table and related matching records from the other one.

SQL Left Outer Join Example:

SELECT A.AU_FNAME, A.AU_LNAME, P.PUB_NAMEFROM AUTHORS A LEFT OUTER JOIN PUBLISHERS PON A.CITY = P.CITYORDER BY A.AU_LNAME, A.AU_FNAME

This left outer join query retrieves the author names and publisher name having same cities. Here all rows retrieved from the left table i.e. authors and publisher name having the similar city other columns of pub_name column are null due to no match found in the right table. Right Outer Join: Right Outer Join is exactly the reverse method of Left Outer Join. It returns all the rows from right table and returns null values for the rows having no match in the left joined table. Just change the left keyword to right outer join in above example; you will get the reverse output of left outer join in the form of right outer join.

SQL Right Outer Join query Example:

SELECT A.AU_FNAME, A.AU_LNAME, P.PUB_NAMEFROM AUTHORS A RIGHT OUTER JOIN PUBLISHERS PON A.CITY = P.CITYORDER BY A.AU_LNAME, A.AU_FNAME

Full Outer Join: Full outer join returns all the rows from both left and right joined tables. If there is any match missing from the left table then it returns null column values for left side table and if there is any match missing from right table then it returns null value columns for the right side table. To retrieve all the records from left as well as right table unless the records have matching relations in each row you can use SQL FULL OUTER JOIN. You can consider the examples of last two articles about left outer join and right outer join, in which left outer join retrieves all records from the left table and as all records of right table in right outer join along with null values for the columns having no matching records in any tuple. To retain all the records of left as well as right table along with null values for non matching rows displaying the combination of results of left outer and right outer join, FULL OUTER JOIN is the best solution.

SQL FULL outer join example:

SELECT A.AU_FNAME, A.AU_LNAME, P.PUB_NAMEFROM AUTHORS A FULL OUTER JOIN PUBLISHERS PON A.CITY = P.CITYORDER BY A.AU_LNAME, A.AU_FNAME

Cross Join: Cross join works as a Cartesian product of rows for both left and right table. It combined each row of left table with all the rows of right table. SQL Cross join returns the output result as a Cartesian product of both database tables. Let left table has 10 rows and right table has 8 rows then SQL CROSS Join will return 180 rows combining each record of left table with all records of right side table.

Consider the following example of CROSS Join:

USE PUBSSELECT AU_FNAME, AU_LNAME, PUB_NAMEFROM AUTHORS CROSS JOIN PUBLISHERS ORDER BY AU_FNAME

Above cross join will return 23 * 8 = 184 results by multiplying each row of authors table with publishers table. SQL CROSS Join with WHERE clause By just adding the where clause with Cross join sql query it turns the output result into inner join.

Aug 5, 2009

Call-by-value Vs Call-by-reference in Java

The terms "Call-by-value" semantics and "Call-by-reference" semantics have very precise definitions, and they're often horribly abused when folks talk about Java. I want to correct that... The following is how I'd describe these

Call-by-value
The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application (which is how Java handles it), but other languages could choose parameter storage differently.

Call-by-reference
The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.

When you call a method by reference, the callee sees the caller’s original variables passed as parameters, not copies. References to the callee’s objects are treated the same way. Thus any changes the callee makes to the caller’s variables affect the caller’s original variables. Java never uses call by reference. Java always uses call by value.

How do you fake call by reference in Java, or more precisely, how can a callee influence the values of it’s caller’s variables?

* Use a holder/wrapper object passed to the callee as a parameter. The callee can change the object’s fields. That object may be as simple as an Object[]. In Java, a callee may change the fields of a caller’s object passed as a parameter, but not the caller’s reference to that object. It can’t make the caller’s variable passed as a parameter point to a different object. It can only make its local copy point to a different object. A holder class is just a class with fields to hold your values. It has no methods other than accessors for the fields.

* Have the callee return the new values, perhaps wrapped in an holder class or Object[], and have the caller store them away somewhere.
* Communicate via a static or instance variable visible to both caller and callee.
* Use a delegate object. The callee calls its methods to save the results for the caller.

Dale King points out that attempts to fake call by reference are usually a sign of poor object-oriented design. A function should not be trying to return more than one thing. He uses the term thing because it is proper to return more than one value (e.g. returning a Point that contains two values). If you are trying to return two values, the test he like to apply is whether you can come up with a logical name for the values as a group. If you can’t, you had better look to see if maybe you what you have is really two functions lumped together.

Java is strictly Call-by-value

Aug 1, 2009

Serializing and Deserializing Objects

Serializing and Deserializing Objects

The serialization mechanism in Java provides the means for persisting objects beyond a single run of a Java program. To serialize an object, make sure that the declaring class implements the java.io.Serializable interface. Then obtain an ObjectOutputStream to write the object to and call the writeObject() method on the ObjectOutputStream. To deserialize an object, obtain an ObjectInputStream to read the object from and call the readObject() method on the ObjectInputStream. The following code excerpts illustrate how an object is stored in the file by Serialize and getting object from file by Deserialize.

private static String fileName = "./objectholder.ser";

public static void serializeObject(Object obj) {
try {
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(fileName));
out.writeObject(obj);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static Object deSerializeObject(){
try {
Object obj = null;
File file = new File(fileName);
if(file.exists()) {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
obj = in.readObject();
in.close();
}
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

how to call these methods?
//serialize the object
MyObject fileObjs = new MyObject();
serializeObject(fileObjs);

// Deserialize the object
MyObject fileObjs = (MyObject)deSerializeObject();

Where MyObject is class with implements of Serializable interface.

Serialize the object myObject of type MyObject. The file output stream is created for the file named myObject.ser. The object is actually persisted in this file on ,and read the object back from the file objectholder.ser. If you list the files in the directory where this code's .class file is stored, you will see a new file called objectholder.ser added to the listing.

Jul 31, 2009

Basic Architecture of Hibernate

Introduction to Hibernate:

Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is a powerful, highperformance object/relational persistence and query service. It allows us to develop persistent classesfollowing object-oriented idiom – including association, inheritance and polymorphism.


Hibernate Architecture

1) itself opens connection to database,

2) converts HQL (Hibernate Query Language) statements to database specific statement,

3) receives result set,

4) then performs mapping of these database specific data to Java objects which are directly used by Java application.

Hibernate uses the database specification from Hibernate Properties file. Automatic mapping is performed on the basis of the properties defined in hbm XML file defined for particular Java object.



JDBC Vs Hibernate

Why is Hibernate better than JDBC

1) Relational Persistence for JAVAWorking with both Object-Oriented software and Relational Database is complicated task withJDBC because there is mismatch between how data is represented in objects versus relationaldatabase. So with JDBC, developer has to write code to map an object model's data representationto a relational data model and its corresponding database schema. Hibernate is flexible andpowerful ORM solution to map Java classes to database tables. Hibernate itself takes care of thismapping using XML files so developer does not need to write code for this.

2) Transparent PersistenceThe automatic mapping of Java objects with database tables and vice versa is called TransparentPersistence. Hibernate provides transparent persistence and developer does not need to write codeexplicitly to map database tables tuples to application objects during interaction with RDBMS.With JDBC this conversion is to be taken care of by the developer manually with lines of code.

3) Support for Query LanguageJDBC supports only native Structured Query Language (SQL). Developer has to find out theefficient way to access database, i.e to select effective query from a number of queries to performsame task. Hibernate provides a powerful query language Hibernate Query Language(independent from type of database) that is expressed in a familiar SQL like syntax and includesfull support for polymorphic queries. Hibernate also supports native SQL statements. It also selectsan effective way to perform a database manipulation task for an application.

4) Database Dependent CodeApplication using JDBC to handle persistent data (database tables) having database specific codein large amount. The code written to map table data to application objects and vice versa isactually to map table fields to object properties. As table changed or database changed then it’sessential to change object structure as well as to change code written to map table-to-object/objectto-table. Hibernate provides this mapping itself. The actual mapping between tables andapplication objects is done in XML files. If there is change in Database or in any table then theonly need to change XML file properties.

5) Maintenance CostWith JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objectsthrough code to use this persistent data in application. So with JDBC, mapping between Javaobjects and database tables is done manually. Hibernate reduces lines of code by maintainingobject-table mapping itself and returns result to application in form of Java objects. It relievesprogrammer from manual handling of persistent data, hence reducing the development time andmaintenance cost.

6) Optimize PerformanceCaching is retention of data, usually in application to reduce disk access. Hibernate, withTransparent Persistence, cache is set to application work space. Relational tuples are moved to thiscache as a result of query. It improves performance if client application reads same data manytimes for same write. Automatic Transparent Persistence allows the developer to concentrate moreon business logic rather than this application code. With JDBC, caching is maintained by handcoding.

7) Automatic Versioning and Time StampingBy database versioning one can be assured that the changes done by one person is not being rollbacked by another one unintentionally. Hibernate enables developer to define version type field toapplication, due to this defined field Hibernate updates version field of database table every timerelational tuple is updated in form of Java class object to that table. So if two users retrieve sametuple and then modify it and one user save this modified tuple to database, version is automaticallyupdated for this tuple by Hibernate. When other user tries to save updated tuple to database then itdoes not allow to save it because this user does not has updated data. In JDBC there is no checkthat always every user has updated data. This check has to be added by the developer.

8) Open-Source, Zero-Cost Product LicenseHibernate is an open source and free to use for both development and production deployments.

9) Enterprise-Class Reliability and ScalabilityHibernate scales well in any environment, no matter if use it in-house Intranet that serves hundredsof users or for mission-critical applications that serve hundreds of thousands. JDBC can not bescaled easily.Hibernate Made Easy: Simplified Data Persistence with Hibernate and JPA (Java Persistence API) Annotations

Disadvantages of Hibernate

1) Steep learning curve.

2) Use of Hibernate is an overhead for the applications which are :• simple and use one database that never change• need to put data to database tables, no further SQL queries• there are no objects which are mapped to two different tablesHibernate increases extra layers and complexity. So for these types of applications JDBC is thebest choice.

3) Support for Hibernate on Internet is not sufficient.

4) Anybody wanting to maintain application using Hibernate will need to know Hibernate.

5) For complex data, mapping from Object-to-tables and vise versa reduces performance andincreases time of conversion.

6) Hibernate does not allow some type of queries which are supported by JDBC. For example It doesnot allow to insert multiple objects (persistent data) to same table using single query. Developerhas to write separate query to insert each object.

Jul 29, 2009

How DB locking system works in Hibernate (In Concurrency operations)

Database locking can apply to any database applications.
There are two common strategies when dealing with updates to database
records, pessimistic locking and optimistic locking.
"Optimistic locking" is more scalable than pessimistic locking when dealing with a
highly concurrent environment. However pessimistic locking is a better solution for situations
where the possibility of simultaneous updates to the same data by multiple sources
(for example, different applications use same database to update) is common, hence making the possibility of "data clobbering" , a
likely scenario. Lets look at a brief explanation of each of these two locking strategies.
Pessimistic locking is when you want to reserve a record for exclusive update by
locking the database record(entire table). Hibernate supports pessimistic locking
(using the underlying database, not in-memory) via one of the following methods:

1. Session.get
2. Session.load
3. Session.lock
4. Session.refresh
5. Query.setLockMode

Although each of the methods accepts different params, the one common parameter
across all is the LockMode class, which provides various locking modes such as NONE,
READ, UPGRADE, UPGRADE_NOWAIT, and WRITE.
For example, to obtain a Timesheet record for updating,
we could use the following code: (assume database supports locking system):

public Timesheet getTimesheetWithLock(int timesheetId)
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Timesheet timesheet = (Timesheet)session.get(Timesheet.class,
new Integer(timesheetId), LockMode.UPGRADE);
session.getTransaction().commit();
session.close();
return timesheet;
}
Optimistic locking means that you will not lock a given database record or table and
instead check a property of some sort (for example, a timestamp column) to
ensure the data has not changed since you read it. Hibernate supports this using a
version property, which can either be checked manually by the application or automatically
by Hibernate for a given session. For example, the following code excerpt is taken
verbatim out of the Hibernate reference documentation and shows how an application
can manually compare the oldVersion with the current version using a getter method
(for example):

// foo is an instance loaded by a previous Session
session = factory.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );

if ( oldVersion!=foo.getVersion )
throw new StaleObjectStateException();


foo.setProperty(“bar”);

session.flush();
session.connection().commit();
session.close();

StaleObjectStateException, is an exception in the org.hibernate package.

Jul 27, 2009

Velocity example with FOR LOOP and Date format

/*Velocity example with Lists, date formate with htmls*/
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.DateTool;

public class VelocityExp {

public static void main(String[] args) throws Exception {
Velocity.init();
Template t = Velocity.getTemplate("./src/test/VelocityExp.html");

VelocityContext ctx = new VelocityContext();
Set names =new HashSet();
Demov d1 = new Demov();
d1.setName("one");
d1.setAge("24");
d1.setKe(new demo2("one"));
Demov d2 = new Demov();
d2.setName("two");
d2.setAge("23");
d2.setKe(new demo2("two"));
Demov d3 = new Demov();
d3.setName("true");
d3.setAge("22");
d3.setKe(new demo2("three"));
Demov d4 = new Demov();
d4.setName("ofour");
d4.setAge("21");
d4.setKe(new demo2("four"));

names.add(d1);
names.add(d2);
names.add(d3);
names.add(d4);
ctx.put("products",names);
ctx.put("date", new DateTool());
ctx.put("dbdate",new Date());
ctx.put("rowCount",new Integer(1));
Writer writer = new StringWriter();
t.merge(ctx, writer);
System.out.println(writer);
}
}


Html file content:
<html>
<head>
<title>velocity test</title>
</head>
<body>
<table>
#foreach($product in $products)
#if ($rowCount % 2 == 0)
#set ($bgcolor = "#0000FF")
Applying BLUE color here
#else
Applying RED color here
#set ($bgcolor = "#FF0000")
#end
<tr>
<td bgcolor="$bgcolor">$product.name</td>
<td bgcolor="$bgcolor">$product.age</td>
<td bgcolor="$bgcolor">$product.ke.k</td>
</tr>
#set ($rowCount = $rowCount + 1)
#end
</table>
Displaying how to use date format here:
$dbdate
$date.get('medium')
$date.format('medium',$dbdate)
</body>
</html>

Jul 25, 2009

Java class with regExp

package com;

public class Name {
public static void main(String[] args) {
System.out.println(Name.class.getName().replaceAll(".", "/") + ".class");
}
}
Output:
////////.class

actually everyone thinks the output will be com/Name.class
In the case of replace '.' will treat as regExp, in regExp '.' means any type of character, here replacing with '/' , and it becomes output like "////////.class "

so, for expected answer, change the code as follows,

Name.class.getName().replaceAll("\\.", "/") + ".class");

then the output will, what you exprected,
Output:
com/Name.class

Jul 21, 2009

Small Answer for Small java pzzule!

/* What declaration turns this loop into infinitive loop.*/

public class GhostOfLooper {

public static void main(String[] args) {

// Place your declaration for i here

while (i != 0)

i >>>= 1;

}

}

Solution:

// Place your declaration for i here

byte i = -1;

Solution for java puzzles(3)

/*What declaration turns this loop into infinitive loop.*/

public class Looper {
public static void main(String[] args) {
// Place your declaration for i here

while (i == i + 1) {
}
}
}

Solution:
// Place your declaration for i here
double i = 1.0/0.0

Solution for java puzzles(2)!

/*Provide declarations for the variables x and i such that*/

public class Tweedledum {
public static void main(String[] args) {
// Put your declarations for x and i here
x += i; // Must be LEGAL
x = x + i; // Must be ILLEGAL
}
}
solution:
// Put your declarations for x and i here
int x=0;
byte i;

Solution for Java puzzles(1).

/*Provide a declaration for Enigma that makes the program print false.*/

public class TestClass{
public static void main(String[] args) {
Enigma e = new Enigma();
System.out.println(e.equals(e));
}
}

final class Enigma {
// Provide body that makes TestClass print false.
// Do n't override equals method in object class.
}
:Solution
final class Enigma {
public Enigma(){
System.out.print("false");
System.exit(0);
}
}
Any other solution will be appreciated ...

Jul 18, 2009

How to read Excel file in Java with jxl.jar?

/*Reading Excel file (with default locale) with jxl.jar file ,you can use file object to read file in workbook settings*/
public void processExcelFile(InputStream fileInput)throws Exception {
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
Workbook workbook = Workbook.getWorkbook(fileInput, ws);
//Workbook workbook = Workbook.getWorkbook(file, ws);
//Cell[] headCells = sheet.getRow(0);
for (row = 1; row < sheet.getRows(); row++) {
String errorStr = "";
Cell[] cells = sheet.getRow(row);
System.out.println("column1 value:"+cells[0].getContents());
System.out.println("column2 value:"+cells[1].getContents());
System.out.println("column3 value:"+cells[2].getContents());
}
}
To download jxl.jar file go through this link
http://www.docjar.com/jar/jxl-2.6.jar

Mar 22, 2009

How to Sort HashMap or Map in java?

/* Sorting Map and return LinkedHashMap, u can send HashMap implemented Object but it should a map like
Map map = new HashMap();
ma p = sortHashMapByValues(map);
*/
public LinkedHashMap sortHashMapByValues(Map passedMap) {
List mapKeys = new ArrayList(passedMap.keySet());
List mapValues = new ArrayList(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);

LinkedHashMap sortedMap =
new LinkedHashMap();

Iterator valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Object val = valueIt.next();
Iterator keyIt = mapKeys.iterator();

while (keyIt.hasNext()) {
Object key = keyIt.next();
String comp1 = passedMap.get(key).toString();
String comp2 = val.toString();

if (comp1.equals(comp2)){
passedMap.remove(key);
mapKeys.remove(key);
sortedMap.put((String)key, val);
break;
}

}

}
return sortedMap;
}