Wednesday, April 08, 2009

Eleven IT horror stories

Automatic updates
BrilliantCompany.com was growing at dot-com bubble rates. With departments popping up like daisies in spring, the IT staff was ceding desktop control to department heads because most everyone was technical anyway.

Shortly after a batch of 75 new Dell desktops arrived to populate a new product division, the network suddenly died in the middle of the day. All lights were green in infrastructure land, but performance had slowed to such a crawl that the LAN was effectively paralyzed. Some diligent sniffing and log file snooping revealed the culprit.
Turns out Windows XP’s Automatic Update had defaulted to high noon on a weekday, and all 75 machines attempted to download several hundred megs of Service Pack 2 simultaneously and individually. Instant network clog.
Solution:  Centralize IT control so one somebody can be responsible for all the details. This was done in short order after I released a sprightly memo to the appropriate folks. Then, I did what I should have done earlier and set up SUS (Software Update Services), now WSUS (Windows Server Update Services), to download updates and distribute at an appropriate time and after appropriate testing against departmental OS images.
Moral:  Just because your users are technical doesn’t mean they’ll behave with any more attention to detail than the average Joe. If network uptime is your responsibility, then take responsibility and manage what needs managing.

Client protection
InfoWorld reader SEnright relates a tearful tale: A mobile user called to say that his laptop was no longer functioning. After a lengthy phone conversation, during which the user initially denied anything unusual had happened, he disclosed that he had spilled an entire can of Coke on the keyboard. “He continued by telling me that he had tried to dry it with a hair dryer, but that it still would not boot. I asked him to send it back to me, and that I would have it repaired.”

But when SEnright opened the laptop’s shipping box the very next day, he had a bit of a shock. “The gentleman had not used a ‘hair dryer,’ but must have borrowed a heat gun at one of our locations, because all that was left of the keyboard was a cooled pool of molten black plastic.” Ouch.
Solution:  The laptop was insured for “accidental” damage only. Since the incident, maintaining full coverage of mobile equipment has been a matter of course for SEnright.
Moral:  Cover your mobile warriors. That means not only insuring their hardware, but giving them training and clear policy documents on what can and can’t be done with company hardware on the road. Further, make sure their data is backed up religiously, both when they’re at the home office and when they’re on the road.

Executive clout
Here, we’re concerned with that senior executive who just has to have full administrative rights to every machine on the network. Even though he’s about as technical as my cat--and my cat is dead.
Senior users can be dangers even without special access rights. John Schoonover, who worked for the Department of Defense on one of the largest network deployments in history during Operation Enduring Freedom was “witness to a huge lack of IQ points” in a senior manager.
According to Schoonover, military infosec installations generally follow a concept termed “the separation of red and black.” Red is simply data that has not been encrypted yet. (Danger, the world and sniffers can see you!) Black is the same data after it has been encrypted and is now ready to traverse the world. “These areas [red and black] are required to be separated by a six foot physical gap,” Schoonover says.
Our hero proceeds to follow these guidelines and deploys the network, but comes back from lunch one day to find the firewall down. Investigation shows that a senior manager “had taken the cabling from the inside router and connected to the Internet for connectivity, thus bypassing all firewall services, encryption, and -- oh yeah, that’s right -- the entire secure network with a jump straight to the Internet!”
Solution:  John says they “removed the culprit’s thumbs, because if you can’t grip the cable, you can’t unplug it.” I didn’t ask for any more details.
Moral:  Managing rogue senior users is an art in itself that requires diplomacy and even outright deception. In several installations I’ve renamed the Administration account something like “IT” and made “Administrator” a functionally limited account with simply more read/write access to data directories, while still blocking access to things like the Windows system directory or Unix root directories. Most times they never notice; and if they do, I’m pretty good at making up excuses why those directories remain closed off. (“Oh, that’s something Microsoft did in the last service pack. Gosh darn that Bill Gates.”)

Legal eagles hunting IT mice
Lawyers ruin everything -- including smoothly running networks. But IT managers who ignore the ever-changing legal landscape’s impact on technology do so at their peril.

I was once called in as referee among in-house counsel, senior management, and IT staff after the company was informed that child pornography had been tracked to its servers. The company didn’t know whether to aid the investigation by figuring out which employee was responsible or to just delete all the offending files immediately and most likely incur a fine but protect the firm from getting shut down.
In the end, the lawyers managed to make a deal with investigators. The company’s IT network stayed active and we tracked the lowlife down and had him arrested. Quietly.
Solution:
 Talk to senior management and corporate counsel about legal issues, such as corporate response to third-party audits or company responsibility for data it’s holding concerning third-parties, before they happen.
This discussion goes beyond IT-centric solutions. Management must decide whether it wants to retain all pertinent data (the best course of action for those third-party audits) or automatically delete offending data (such as whatever’s found in porn filters).
IT and management must see eye to eye on how the company will respond to law enforcement inquiries, investigations, or even raids. If Homeland Security agents believe a terrorist is masquerading as an employee and storing data on corporate servers, they can come in and pretty much take anything they want. That could put a real crimp in the style of, say, an e-business.
Developing the best course of action should involve senior management, corporate counsel, and law enforcement. The FBI is usually pretty helpful in these discussions -- and so, sometimes, is the local computer crimes department, such as the large Computer Investigation and Technology Unit division of the NYPD.
Moral:
 The higher you are on the IT food chain, the more such liability can spell serious trouble. If you make sure to discuss at least general legal eventualities with senior management, you’re much more likely to do yourself and your employer some real service in specific situations. If they refuse to discuss the matter, archive everything you can.

Disasters in disaster recovery
Gary Crispens reports an incident he encountered after questioning an IT director about the company’s preparedness for disaster recovery. The director responded huffily that the hot site was ready for any disaster, including the necessary space and equipment all backed by a diesel-powered generator with “plenty of fuel.”

After about a year, the company had a hurricane-related power outage that forced it to roll over to the hot site. “Sure enough, the IT Director had critical functions up and running and I could hear that generator running out back. But after about eight hours the power went out for good and all systems crashed when the generator stopped.”
It turned out that “plenty of fuel” was one 55 gallon barrel that was already half empty from the monthly testing.
Solution:
 A disaster recovery plan that called for fuel checks in addition to generator testing.
Moral:
 Disaster recovery isn’t a static issue. One plan or one policy is never perfect out of the gate. Ever. Pass such concepts by as many experienced eyes as you can and then revisit them annually or even bi-annually for refinement.

 

Rogue peripherals
CompUSA and the Dummies books are teaching users just enough of the tech alphabet to spell trouble.

One of my favorite stories was the network that was severely hacked by someone who came in from the outside and deleted the main Exchange message store. Firewall logs had gotten the local IT admin nowhere, so we were called in to do a little snooping around. I wish I’d thought of it, but another guy on the team had the sense to run AirSnort. He found a wide open Linksys wireless access point in about six seconds.
The internal admin insisted there was no wireless running anywhere on the network. It took some sneaker netting, but we found the rogue AP in a senior exec’s office about 20 minutes later. Seemed he saw how cheap they were at the local CompUSA and decided to plug one into the secondary network port in his office so he could use his notebook’s wireless instead of the wired connection because no wires “looks better.”
Another problem in this vein is USB. Being able to plug in a peripheral and achieve working status without the need to install drivers has rapidly spread the popularity of personal peripherals. You don’t want to get yourself get sucked into supporting things such as printers that aren’t on your official purchase list -- or external hard disks, DVD drives, sound systems, and even monitors.
Nor do you want the security risk of an employee plugging in a gig or two of empty space into any workstation’s USB port and copying important corporate information. Source code, accounting data, and historical records all can be copied quickly and then walk out in somebody’s hip pocket.
Solution:
 Let employees know what is and isn’t acceptable as corporate peripherals. Keep an accurate asset record of what belongs to the IT department so you can more easily find or ignore the stuff that doesn’t. And if data theft is a problem, think about protecting yourself by disabling USB drives, uninstalling CD-RW drives, or similar measures. The work you do now can save your bacon later.
Moral:
 Asset management isn’t just for the anal. Knowing exactly what’s supposed to be on your network is a key step to solving a wide variety of IT mysteries.

Security silliness
Security should be everyone’s job, from CTO to administrative assistant. It’s surprising how few organizations recognize this.

I think back to a time right after a fairly large network upgrade. All weekend, day and night, had been spent migrating a nightmare network from a hodgepodge of Windows 95/98/ME and even OS/2 clients with NetWare and Windows NT servers to a clean, homogenous utopia of redundant Windows 2000 Servers on the back and Windows XP Professional desktops on the front. Things hadn’t gone quite as smoothly as we’d hoped, so instead of finishing up on Sunday afternoon, we were still putting final tweaks in place on Monday morning.
After we did our last test (making sure all local tape backups were working properly) it was about noon. (Most users by now had logged in, been informed that they needed to choose a new password in accordance with our medium-strong password guidelines, and had chosen a new password.) I stumbled bleary-eyed into the lunchroom for my umpteenth caffeine fix. Chugging my Coke, I almost missed it while mincing out of the lunchroom. But it grabbed my attention from the corner of my eye and caused Coca-Cola to shoot from my schnoz like some enraged soda dragon.
“Password List.” Yes, every user’s new password along with IT and even some specific switch passwords had been printed out by a well-meaning secretary and posted in the lunchroom. After they pried my hands from her throat, she explained that she just figured it’d be easier to post them there than to answer all the phone calls when users inevitably forgot them. So she went around and collected them (in my name), built her list, and posted it.
Solution:
 User training. Passwords should not be regarded as obstacles but as keys for very important locks. Users must be made aware of such concepts, not simply dropped into new environments. If the secretary had been given a clue, she never would have done it, but the only training this company ever gave her was how to use Word.
Moral:
 Preaching may be a pain, but it can sure stop a lot of FUBAR stupidity before it gets very far.

Curiosity killed the kilobyte
These situations can vary, but have the common denominator of a user experimenting with something he knows is dangerous … and not watching what he’s doing. P. A. Dunkin relates a situation that, surprisingly, I’ve encountered myself. (Mr. Dunkin declined his family’s donut fortune in favor of becoming a sys admin for a software engineering firm.)

After a recent virus outbreak, a curious engineer decided to crack open a sample of the virus to “see what made it tick.” But instead of doing this on a PC that wasn’t connected to the LAN or even one using an operating system immune to the virus, he did neither and promptly reinfected the network.
Dunkin’s user had the good sense to come forward immediately -- the guy I had experience with didn’t even realize what he’d done so we didn’t detect the new infection until anti-virus software caught it.
Solution:
 For me, it was multiple areas of virus detection, both server and client. Nowadays you can even get this at the infrastructure layer and I highly recommend it. Just because a virus is killed once doesn’t mean it can’t get resurrected.
Moral:
 Dunkin says his users learned from the experience -- the advantage of having geek users. For many of us, however, his subsequent strategy is applicable: “I maintain an open-door anti-virus policy: No question about viruses is stupid, ever; and any time I have to send out a warning about an especially dangerous threat, I include an offer to help set up whatever measures are required, reminding them that it takes much less time to prevent an infection than to clean up after one.”

Server abuse
You can clean your server till it sparkles, but users can still find ways to abuse them -- especially on the storage front, as reader Yan Fortin relates. Fortin was having such a boring day, he was actually browsing his firewall logs simply for something to do (I hit Playboy.com in that situation, but to each his own). Suddenly, he received a user call that network file access was being denied. Another call prompted him to put down his fascinating log reading and do a little investigating.
“Lo and behold, I had five e-mails warning me that the free space on the F: network share was getting dangerously low. Unfortunately for me, I had turned off the Windows Messenger Service on my workstation, so I couldn’t receive any warning that way. Shame on me.” Indeed.
Fortin searched the drive for every file bigger than 50MB and stumbled upon a marketing user who was copying approximately 30 150MB TIFF files from a DVD to the network. “I called her to inform her that I would delete all her [expletive deleted] files, and did so right after.” Crisis over.
Solution:  Fortin purchased additional hard disk space for the server right after this incident and also had a firm talk with the user about the relatively finite nature of server disk space.
Moral:  Explaining things to inexperienced or even tech-phobic users may be a pain in the posterior, but it sure can save you time, trouble, and screaming managers in the long run.

Telecommuting terrors
Always remember that even telecommuters eventually come to the office. One reader relates the experience of a remote user visiting the home office and immediately killing the entire network. A little laptop investigation showed that the user had decided to configure his laptop as a DHCP server for his home network, which “suddenly made his machine the default gateway for that segment.”

Other examples include mamas and papas who genially allow their kids to play high-end games on the corporate hardware, or (worse) to surf the Internet in all those dark and fringelike nooks that teenagers like to explore on the Web. While the adults are out having dinner, the kids are home infecting the workstation, which promptly begins to spew out viruses the next time daddy either logs in or visits the office.
Solution:
 Perimeter defense. End-point security technologies such as Cisco’s NAC or Microsoft’s NAP are specifically designed to minimize this risk by scanning outside machines the moment they’re connected to the network. Failure to meet with specific criteria, including everything from minimal patch levels to scheduled virus scans, means the PC is dumped into a quarantine area of the network where it can be scanned, updated, and fixed without risk of harm to other nodes.
Moral:
 Talk to your telecommuters. Fair use policies with a little bit of disciplining oomph behind them can go a long way toward having mommy buy her precious offspring their own PC to infect rather than risking her job by letting them use hers.

Ultimate weirdness
This one won our Deepest Chuckle Award. Dave Schultz related an incident in which he tagged a note to a network laser printer informing users that if print quality suffered enough to warrant a toner cartridge replacement, they should first “shake a few times to yield a few additional copies.”

Schultz was later berated because a user suffered a work-related back injury by reading the note, then picking up the entire HP LaserJet 4000 and trying to shake the printer back and forth.
Solution:
Shoot the user, he’s lame now, anyway.
Moral:
Never let your blood pressure get too far into the dangerous numbers and keep a bottle of Advil handy.

(http://www.infoworld.com/print/21822)

Wednesday, March 11, 2009

How to be assertive

  • Assertions were introduced in J2SE 1.4
  • Rather than introducing it as a class library it was built into the language itself using the keyword assert
  • Assertions can be used to test the following three roles:
    • Precondition - a condition that the caller of a method agrees to satisfy
    • Postcondition - a condition that the method itself promises to achieve
    • Invariant - a condition that should always be true for a specified segment or at a specified point of a program
  • An assertion has a boolean expression that if evaluated as false indicates a bug in the code
    assert a !=b  : "Not Equal!!"
  • The message part after the : is optional, if given it is passed to the stack trace which is printed
  • When an assertion fails, it means that the application has entered an incorrect state
  • When the expression evaluates to false an AssertionError is thrown
  • A good practice is to terminate the application when the error is thrown, because the application may start functioning inappropriately after a failure
  • Assertions are disabled by default - to run an application with assertions enabled we have to give the option "-ea" or "-enableassertion"
    java -ea AssertionTest
  • The above command enables assertion for all classes except for the system classes
  • To turn on assertion in system classes we have to use "-esa" or "-enablesystemassertions"
  • To disable assertions we have to use "-da" or "-disableassertion", which is the default
  • Also, we can enable or disable assertions for specific classes or packages
    java -ea:com.test.ui.UIClass MainClass
    java -ea:com.javacourses.tests... -da:com.javacourses.ui.phone MyClass
  • The ellipsis ... is part of the syntax
  • Following is a sample class that uses assertion to check for invalid user input
    import java.io.*;

    public class AssertionTest {
    public static void main(String[] args) throws IOException {
    System.out.print("Enter your marital status: ");
    int c = System.in.read();
    switch((char)c) {
    case 's': case 'S':
    System.out.println("Single");
    break;
    case 'm': case 'M':
    System.out.println("Married");
    break;
    case 'd': case 'D':
    System.out.println("Divorced");
    break;
    default:
    assert !true : "Invalid Option";
    }
    }
    }

Friday, February 27, 2009

Thursday, January 22, 2009

Compiling Programmatically

Following example uses the JavaCompiler interface in Java 6 to programmatically compile a Java class:

public class CompilerExample {
public static void main(String[] args) {
String fileToCompile = "test.java"
javax.tools.JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if (compilationResult == 0) {
System.out.println("Compilation is successful");
} else {
System.out.println("Compilation Failed");
}
}
}

Dive Into Java

Dive into Java
View more presentations or upload your own. (tags: java programming)

Tuesday, January 06, 2009

Reversing a String in Java

The following code shows different methods of reversing a String in Java. The simplest being using the reverse() method of StringBuffer, while the other methods use char array and recursion:

public class StringReverse {<br />	public static void main(String[] args) {<br />		String s = "zyxwvutsrqponmlkjihgfedcba";<br />		System.out.println(charReverse(s));<br />		System.out.println(recursiveReverse(s , new StringBuffer()));<br />		System.out.println(recursiveReverse2(s, new StringBuffer()));<br />		System.out.println(bufferReverse(s));<br />	}<br />	<br />	public static String charReverse(String s) {<br />		char[] cArr = s.toCharArray();<br />		StringBuffer reversed = new StringBuffer();<br />		for(int i=cArr.length-1; i>=0; i--) reversed.append(cArr[i]);<br />		return reversed.toString();<br />	}<br />	<br />	public static String recursiveReverse(String s, StringBuffer t) {<br />		if(s.length() > 0) {<br />			t.append(s.substring(s.length()-1));<br />			recursiveReverse(s.substring(0, s.length()-1), t);<br />		}<br />		return t.toString();<br />	}<br />	<br />	public static String recursiveReverse2(String s, StringBuffer sb) {<br />		if (s.length() == 1){<br />			sb.append(s);<br />		}<br />		else{<br />			recursiveReverse2(s.substring(1, s.length()), sb);  <br />			sb.append(s.substring(0,1));<br />		}<br />		return sb.toString();<br />	}<br />	<br />	public static String bufferReverse(String s) {<br />		StringBuffer sb = new StringBuffer(s);<br />		return sb.reverse().toString();<br />	}<br />}

Monday, January 05, 2009

HSQLDB

HSQLDB is a 100% Java database which is embeddable. It has a small footprint and can be used for self-contained applications. The source files, the JAR file and support documents can be downloaded from hsqldb.org. It also provides a JDBC driver. HSQLDB is perfect for quick implementation and testing.

Following is a sample program which uses the JDBC driver for creating a table, inserting some data in the table and listing the rows from the table:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.PreparedStatement;

public class HSQLTest {
Connection conn;
Statement stmt;
PreparedStatement add_stmt, get_stmt;

static {
try{
Class.forName("org.hsqldb.jdbcDriver").newInstance();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(InstantiationException e) {
e.printStackTrace();
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
}

HSQLTest() {
try {
initializeDB();
createTable();
populateTable();
displayRows();
}
catch(SQLException e) {
e.printStackTrace();
}
}

void initializeDB() throws SQLException {
conn = DriverManager.getConnection("jdbc:hsqldb:db/test", "sa", "");
stmt = conn.createStatement();
}

public void createTable() throws SQLException {
String table_name = "sample_table";
DatabaseMetaData dbM = conn.getMetaData();
ResultSet rs = dbM.getTables(null, null, "%", null);
boolean found = false;
while(rs.next()) {
String s = rs.getString(3);
//System.out.println(s);
if(s.equalsIgnoreCase(table_name)) {
found = true;
break;
}
}

if(!found) {
String s = "CREATE TABLE " + table_name + "(id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1000) PRIMARY KEY, " +
"category VARCHAR(40), name VARCHAR(40))";
stmt.execute("SET WRITE_DELAY FALSE;");
stmt.executeUpdate(s);
}
}

public void populateTable() throws SQLException {
stmt.executeUpdate("insert into SAMPLE_TABLE (category, name) values ('E0', 'Ben')");
}

public void displayRows() throws SQLException {
ResultSet rs = stmt.executeQuery("SELECT * FROM SAMPLE_TABLE");
int numCols = rs.getMetaData().getColumnCount();
while(rs.next()) {
for(int i=1; i<=numCols; i++) {
System.out.println(rs.getString(i) + ": " + rs.getString(i));
}
}
}

public static void main(String[] args) {
HSQLTest hTest = new HSQLTest();
}
}

Top Java Developers Offer Advice to Students

* Joshua Bloch: Write Lots of Code

* Tor Norbye: Learn to Use Your Tools

* Chet Haase: Don't Put Your Entire Application in One Method

* Ben Galbraith: Interact With an Expert

* Masood Mortazavi: Start Simple and Keep Learning

* Raghavan Srinivas: Don't Be Overwhelmed

* Cay Horstmann: First, Don't Panic

* Arun Gupta: Try Different IDEs

* Rick Cattell: Good Technology Is Only 10% of Success

* Chuk-Munn Lee: Choose an Area of Your Immediate Need

* Tom Ball: Programming Is Still a Craft
 
 

Why A Laptop Is Better Than A Girlfriend!

10- Your Laptop is cool with Whatever Plans you Have for the Night
 
9- A Laptop isn’t all Ticked Off at you Three Days a Month for no Reason
 
8- Your Laptop won’t ask you Why You’re Afraid of Commitment
 
7- You can turn your Laptop on with the Click of a Button
 
6- Your Laptop Doesn’t Get Jealous of your iPhone and your Xbox
 
5- Your Laptop doesn’t make you listen to Sucky Music/Watch Sucky Movies
 
4- Your Laptop Stays the Same Size she was when you got her
 
3- Your Laptop Doesn’t Mind if YOU Put on Some Weight
 
2- If you see your Laptop with Another Guy, you can call the Police
 
1- Your Laptop can run the Newest Games
 
 
(from http://www.geekwithlaptop.com/why-a-laptop-is-better-than-a-girlfriend/)

Friday, January 02, 2009

OOP Principles

In the process-oriented model, programs are written around "what is happening". This approach characterizes a program as a series of linear steps. This can be thought of as code acting on data.

But, object-oriented programming organizes a program around its data, i.e., objects, and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

Following are the three mechanisms that are required to implement the object-oriented model:

Encapsulation
  • It is the mechanism that binds together code and the data it manipulates
  • It keeps both code and data safe from outside interference and misuse
  • The basis of encapsulation is the class
  • A class defines the structure and behavior (of code and data) that will be shared by a set of objects
  • Each object of a given class contains the structure and behavior defined by the class
  • A class is a logical construct, whereas an object has physical reality
  • The purpose of a class is to encapsulate complexity
  • There are mechanisms for hiding the complexity of the implementation inside the class
  • Each method or variable in a class may be marked private or public
  • The public interface of a class represents everything that external users of the class need to know, or may know
  • The private methods and data can only be accessed by code that is a member of the class
  • Any other code that is not a member of the class cannot access a private method or variable

Ineritance
  • It is the process by which one object acquires the properties of another object
  • It supports the concept of hierarchical classification
  • Without the use of hierarchies, each object would need to define all of its characteristics explicitly
  • However, by use of inheritance, an object need only define those qualities that make it unique within its class
  • It can inherit its general attributes from its parent
  • It is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case
  • If a given class  encapsulates some attributes, then any subclass will have the same attributes plus any that it adds as part of its specialization
  • This lets object-oriented programs grow in complexity linearly rather than geometrically

Polymorphism
  • Polymorphism is a feature that allows one interface to be used for a general class of actions
  • The specific action is determined by the exact nature of the situation
  • It can be expressed by the phrase - one interface, multiple methods
  • It is possible to design a generic interface to a group of related activities
  • This helps reduce complexity by allowing the same interface to be used to specify a general class of action
  • It is the compiler's job to select the specific action as it applies to each situation
  • There are three distinct forms of polymorphism
    • Method overloading
    • Method overriding through inheritance
    • Method overriding through the Java interface
  • Which overloaded method to call is decided at compile time through the reference type passed
  • The other two forms are part of runtime polymorphism
  • With runtime polymorphism, the decision as to which version of a method will be executed is based on the actual type of object whose reference is stored in the reference variable, and not on the type of the reference variable on which the method is invoked
  • The decision as to which version of the method to invoke cannot be made at compile time
  • That decision must be deferred and made at runtime
  • This is sometimes referred to as late binding or dynamic method binding
Another essential element of object-oriented programming is abstraction.
  • A powerful way to manage abstraction is through the use of hierarchical classifications
  • This allows us to layer the semantics of complex systems, breaking them into more manageable pieces
  • The complicated implementation details are hidden from the user
  • The user is given a simple interface to interact with, whereas inside the actual implementation of the interface there may be many complicated details


(Compiled from Java 2: The Complete Reference)

Monday, December 29, 2008

What is Java?

  • Java generally refers to a combination of three things
    • the Java programming language
    • the Java Virtual machine
    • the Java platform
  • Java the language is a high-level OOP language, influenced in various ways by C, C++ and Smalltalk
  • Java has been around officially since 1996
  • Java has evolved tremendously all through these years and has spawned a number of technologies like
    • Servlet technology
    • component technology like JavaBeans
    • JavaServerFaces
    • and a whole host of other technologies and tools
  • Its syntax was designed to be familiar to those familiar with C-descended "curly brace" languages, but with stronger OO principiles than those found in C++
  • One of Java's more controversial aspects is its incomplete object-orientation - Java primitives such as int, char, boolean etc. are not objects
  • The inclusion of primitives increases Java performance, but at arguably expense of code clarity
  • Java 5.0 introduces an "autoboxing" scheme to eliminate many uses of the wrapper classes, but in some ways it obsures what is really going on
  • Java is a fail early language - because of its syntatic restrictions, many programming failures are simply not possible in Java
  • With no direct access to pointers, pointer-arithmetic errors are non-existent
  • Using an object as a different type than what it was originally declared to be requires an explicit cast, which gives the compiler an opportunity to reject illogical programming, like calling a String method on an Image
  • Java is generally understood to be the most popular general-purpose computing language in use today

  • Java is generally thought of in terms of three platforms
    • Standard Edition(SE)
    • Enterprise Edition (EE)
    • Micro Edition (ME)
  • Each describes the combination of a language version, a set of standard libraries, and a virtual machine to execute the code
  • EE is a superset of SE - any EE application can assume the existence of all of the SE libraries
  • EE's use of the language is identical to SE's
  • Because of the limitations of small devices like phones and set-top boxes, Java ME differs significantly from its siblings
  • It is not a subset of SE
  • ME eliminates some language features, such as the float primitive and Float class, reflecting the computing limitations of the platforms it runs on

Java Runtime Environment
  • Java Runtime Environment is a subset of JDK
  • It is an implementation of the JVM which actually executes Java programs
  • JRE is a plug-in needed for running Java programs
  • JRE includes JVM, core libraries and other additional components to run applications and applets written in Java


Java Virtual Machine
  • One of the strong points in favor of Java is "Write Once, Run Anywhere"
  • Java is platform-independent
  • Before Java, programmers would have to write the program for the Windows OS and again for the Mac OS
  • Java eliminates this problem with the use of JVM
  • Java Virtual Machine as its name suggests is a "virtual" computer that resides in the real computer as a software process
  • The JVM essentially runs between the computer and the Java program
  • JVM gives Java the flexibility of platform independence
  • At some point, Java source needs to become platform-native executable code
  • This typically requires a two step process - the developer compiles the source into Java bytecode, and then a JVM converts this into native code for the host platform
  • Java code is written in a ".java" file
  • This code contains one or more Java language attributes like Class, Methods, Variables, Objects etc.
  • Javac is used to compile this code and to generate a ".class" file
  • Class file is also known as byte code
  • java byte code is an input to JVM
  • JVM reads this code and interprets it and executes the program
  • JVM helps the JRE to run Java applications
  • JVM operates on Java bytecode, which is normally generated from Java source code
  • A JVM can also be used to implement programming languages other than Java
  • For example, Ada source code can be compiled to Java bytecode, which may then be executed by a JVM
  • JVMs can also be released by other companies besides Sun - JVMs using the "Java" trademark may be developed by other companies as long as they adhere to the JVM specification published by Sun



Components of JVM
  • JVM is divided into several components like the stack, the garbage-collected heap, the registers and the method area
  • Stack in JVM stores various method arguments as well as the local variables of any method
  • Stack also keeps track of each and every method invocation - called the Stack Frame
  • There are three registers that helps in stack manipulation - vars, frame and optop
  • These registers point to different parts of current stack
  • There are three sections in Java stack frame
    • Local Variables - contains all the local variables being used by the current method invocation. It is pointed to by the vars register
    • Execution Environment - used to maintain the operations of the stack itself. It is pointed to by the frame register
    • Operand Stack - used as a work space by bytecode instructions. It is here that the parameters for bytecode instructions are placed, and the results of bytecode instructions are found. The top of the operand stack is pointed to by the optop register
  • Method Area - is the area where bytecode resides
  • The program counter points to some byte in the method area
  • It always keeps track of the current instruction which is being executed
  • After execution of an instruction, the JVM sets the PC to next instruction
  • Method area is shared among all the threads of a process
  • If more than one thread is accessing any specific method or instruction, synchronization is required
  • Synchronization in JVM is achieved through Monitors
  • Garbage-Collected Heap - is where the objects in Java programs are stored
  • Whenever an object is created using the new operator, the heap comes into picture and memory is allocated from there
  • unlike C++, Java doesn't have free operator to free any previously allocated memory
  • Java does this automatically using Garbage collection mechanism
  • "Mark and Sweep" algorithm is used as garbage collection logic
  • The local object reference resides on Stack, but the actual object resides in Heap
  • Arrays in Java are objects, hence they also reside in Garbage-Collected Heap


(Compiled from http://viralpatel.net/blogs/2008/12/java-virtual-machine-an-inside-story.html, Beyond Java and Widipedia)

Learning Tactics

This article carries at its heart the purpose of helping you raise the level of your technical competence. It is about helping you make every second you spend learning something count; all using experience-grown tactics that prove their worth in practice.
 
With these tactics…
   1. You’ll learn more in less time
   2. You’ll remember more of what you learn
   3. You’ll gain better insights from problems and challenges you face
 
Tactic #1: Do Most of Your Learning By Example
Tactic #2: When Facing a Problem, Step Back and Reflect FIRST
Tactic #3: Learn More In Less Time By Condensing Your Understanding
Tactic #4: Learn Efficiently By Contrasting Close or Similar Concepts
Tactic #5: Avoid Learning Without Purpose
 

Friday, December 26, 2008

CHM Files

Microsoft Compiled HTML Help is a proprietary format for online help files, developed by Microsoft and first released in 1997 as a successor to the Microsoft WinHelp format. It was first introduced with Windows 98 release.
 
CHM files are a set of HTML files, which are indexed and bound together for easy readability. The files are compressed together with LZX compression.
 
On Windows computers, this help file can be compiled using hcc.exe.
 
To print all topics or a set of topics under a specific sub-topic in a CHM file - right click on a topic or sub-topic and select "Print this heading and all sub-topics".
 
CHM to HTML Conversion
 
A CHM file can be extracted to plain HTML with the command
 
    hh.exe -decompile sample_help sample_help.chm
 
On running the above command all files embedded in sample_help.chm will be extracted to a folder named sample_help.
 
 
How to copy images from a CHM file
 
On copy-pasting images from a CHM file to a word file we will get only an empty rectangle. To properly copy the image we must first paste the image to a image processing application like MS-Paint and then copy that image to Word.
 
Another method is to select "Paste Special" in Word and select the "Device Independent Bitmap" in the dialog that opens up, this will properly paste the image in the Word document.

An Introduction to SQLite

MIT's Introduction to Algorithms, Lecture 02

MIT's Introduction to Algorithms, Lecture 01

How to install Ubuntu Desktop 7.10 on VMware

Thursday, December 25, 2008

Tuesday, December 23, 2008

Reflecting on Annotations

          The easiest way to check for an annotation is by using the isAnnotationPresent() method

­          This lets us specify the annotation to check for, and get a true/false result

public void testAnnotnPresent(PrintStream out) throws Exception {

      Class c = Super.class;

boolean inProgr = c.isAnnotationPresent(InProgress.class);

if(inProgr) out.println(“Super is in progress”);

else out.println(“Super is not in progress”);

 

}

­          This also lets us take advantage of the Inherited annotation

­          Although the Sub is not marked as in progress, it inherits from Super, which is in progress

­          Once the method in question is located, that method can be queried for a specific annotation using getAnnotation()

Class c = AnnotationTester.class;

MethodElement element = c.getMethod(“calculateInterest”,

                                    float.class, float.class);

GroupTODO groupTodo = element.getAnnotation(GroutpTODO.class);

String assignedTo = groupTodo.assignedTo();

out.println(“TODO Item on Annotation Tester is assigned to: ” +

assignedTo);

­          We must have to know exactly what we’re looking for – this is one of the few drawbacks of getAnnotation()

­           

­          We can use getAnnotations(), if we’re trying to locate all annotations for a program element, or if we need to iterate through all annotations looking for a specific one

­          Following is a simple utility method that prints out all annotations for a supplied element

public void printAnnotations(AnnotatedElement e) {

      System.out.println(“Annotations for “ + e.toString());

      Annotation[] annotations = e.getAnnotations();

for(Annotation a : annotations) {

      System.out.println(a.annotationType().getName());

}

}

­          The getAnnotations() method prints both declared as well as inherited annotations

­          To get declared annotations alone, we need to use getDeclaredAnnotations() method

­          java.lang.reflect.AnnotatedElement is an interface that the reflection constructs like Method, Class etc. implement

­          It allows access to the annotation methods

­          The core reflection constructs all implement this interface –

o        Class

o        Constructor

o        Field

o        Method

o        Package

o        AccessibleObject

­          This allows all the above elements to be introspected for annotations

­          All these element types provide the following methods as a result of implementing AnnotatedType

o        public Annotation getAnnotation(Class annotationType)

o        public Annotation[] getAnnotations()

o        public Annotation[] getDeclaredAnnotations()

o        public boolean isAnnotationPresent(Class annotationType)

­          Since any Java program element can be treated as an AnnotatedType, we can always get at an element’s annotations using these methods

­           

­          Reflection on annotations only works for annotation types that have Runtime retention

­          Even if the annotation is retained at compilation, if the VM doesn’t load this retention at class-load time, then reflection can’t pick up the annotation

­          Deprecation does not have runtime retention – it has source retention

­          So it is undetectable through Java reflection

­           

Meta Annotations

­          As we can annotate classes, we can also annotate custom annotations

­          Meta-annotations or annotations on annotations are helpful in figuring out someone else’s intent for a customized annotations

­          There are four standard meta-annotations, all defined in the java.lang.annotation package

o        Target

Specifies which program elements can have annotations of the defined type

o        Retention

Indicates whether an annotation is tossed out by the compiler, or retained in the compiled class file

In cases where the annotation is retained, it also specifies whether it is read by the JVM at class load

o        Documented

Indicates that the defined annotation should be considered as part of the public API of the annotated program element

o        Inherited

It is intended for use on annotation types that are targeted as classes, indicating that the annotated type is an inherited one

­           

­          Target

­          It is used to specify which program elements are allowed as targets for the defined annotation

­          This prevents misuse of an annotation, and is a sanity check for an annotation

­          Target should be used in the lines directly preceding the annotation definition

@Target({ElementType.TYPE, ElementType.METHOD

   ElementType.CONSTRUCTOR, ElementType.ANNOTATION_TYPE})

public @interface TODO {

      ....

}

­          Target takes a single member whose type is an array of values, each of which should be an enumerated value from the java.lang.annotation.ElementType enum

­          This enum defines the various program elements allowed as targets of an annotation type

package java.lang.annotation;

 

public enum ElementType {

      TYPE,

      FIELD,

      METHOD,

      PARAMETER,

      CONSTRUCTIR,

      LOCAL_VARIABLE,

      ANNOTATION_TYPE,

      PACKAGE

}

­          To use Target we need to import both Target and ElementType

­          Following is the definition for the Target annotation

package java.lang.annotation;

 

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.ANNOTATION_TYPE)

public @interface Target {

      ElementType[] value();

}

­          As we can see in the above definition, Target meta-annotation is used on itself

­          In case of annotation types that work for all program elements, we don’t have to use Target at all

­           

­          Retention

­          The Retention meta-annotation defines how the Java compiler treats annotations

­          Annotations can be tossed out of a compiled class file by the compiler, or kept in the class file

­          Additionally, the JVM can ignore annotations – when they are retained in the class file, or read those annotations at the time a class is first loaded

­          All of these options are specified by Retention

­           

­          Like Target, we specify the retention of an annotation type just before the annotation definition

­          Also like Target, the argument to Retention must be a value from an enum support class – java.lang.annotation.RetentionPolicy

package java.lang.annotation;

 

public enum RetentionPolicy {

      SOURCE,  //annotation is discarded by compiler

      CLASS,   //stored in the class file, but ignored by the VM

      RUNTIME  //stored in the class file and read by the VM

}

­          The default retention policy, for all annotations, is RetentionPolicy.CLASS

­          This retains annotations, but doesn’t require the VM to read them when classes are loaded

­          A good example of using Retention occurs in the SuppressWarnings annotation

­          As that annotation type is purely used for compilation – ensuring warning of the specified type are suppressed, it does not need to be retained in a class’s byte code

@Retention(RetentionPolicy.SOURCE)

public @interface SuppressWarnings {

      ....

}

­           

­          Documented

­          Annotations are not normally visible in the codes’ Javadoc

­          This is where the Documented meta-annotation comes into play

­          We can use it to ensure that our annotations show up in generated Javadoc

­          We need to add a @Documented meta-annotation to any annotation type that we want to appear in Javadoc

import java.lang.annotation.Documented;

import java.lang.annotation.Retention ;

import java.lang.annotation.RetentionPolicy ;

 

@Documented

@Retention(RetentionPolicy.RUNTIME)

public @interface InProgress { }

­          Anytime we use the Documented annotation, we should pair it with a retention policy of RetentionPolicy.RUNTIME

­           

­          Inherited

­          Annotations applied to super class are not automatically inherited by the sub-class

­          For example in the following code, InProgress annotation is not inherited by the sub-class Sub

@InProgress

public class Super {

      ....

}

 

public class Sub extends Super {

      ....

}

­          We need to used Inherited in the definition of the InProgress annotation type to fix this problem

@Documented

@Inherited

@Retention(RetentionPolicy.RUNTIME)

public @interface InProgress { }

­          The above definition will make any sub-class of a class annotated with the InProgress annotation inherit the annotation

­          Annotations marked as Inherited only apply to sub-classes, so implementing a method with annotations will not result in the annotations being inherited

­          If we override a method from a super class, we don’t inherit that specific method’s annotations

­          Only the annotations on the super class itself are inherited, and those and those by the sub-class as a whole

­