Tuesday, August 29, 2006

Translating Cool Technology Into Revenue by Peter Varhol

Mainsoft has great technology that is tapping a market in enterprises.

Mainsoft, Inc. offers a unique technology that enables developers to write code in a .NET language using Visual Studio, then compile that code to Java bytecode and execute it on a Java virtual machine and application server. The product, Visual MainWin for J2EE, is a plug-in to Visual Studio that lets developers write applications in any .NET language, then dynamically convert the .NET IL into Java bytecode. The process of doing so is so seamless that you can even use the Visual Studio debugger on runtime Java code; Visual MainWin for J2EE converts the bytecode back to .NET IL to engage the debugger.
ADVERTISEMENT

While no techie at heart would doubt that Mainsoft has some of the most impressive technology around, a more hardheaded business person might ask what could possibly be the practical use of such a product.

In response, CEO Yaacov Cohen describes both a vision of computing and a journey that ended up in a somewhat different place than originally intended. "In 2001, we set out to create a technology that made sense from the standpoint of the emerging concepts of service-oriented architecture (SOA). We determined that programming languages were going to be less critical than the ability to tie together different application components, and we set about devising a way to enable that."

In particular, Cohen was focused on decoupling the development choice from the production choice. "Many enterprises didn't want to be locked in to choices made during development," he noted. This was a notion that would grow stronger as the direction toward SOA became more established.

The original goal was to build a "universal virtual machine," a runtime that could execute any application on any underlying platform, said Cohen. There would likely be some limitations in practice, but enterprises need the production flexibility of running on the platform with the best management tools and highest performance. These characteristics might not automatically correlate well with the platform with the best development tools.

This was clearly an ambitious undertaking, and Cohen and the Mainsoft engineering team worked on the problem for two years. As a part of the development effort, one of the engineers wrote a .NET Intermediate Language (IL)-to-bytecode compiler, or translator. Cohen took this piece around to show to customers and investors. It turned out that there was more interest in this piece than in the conceived solution as a whole. The company went back and put more development effort into the IL-to-bytecode compiler, turning it into something that could be positioned as a standalone product.

Getting Down to Business
Mainsoft released this product, Visual MainWin for J2EE, Enterprise Edition, shortly thereafter. But at this point Cohen had to face the hard realities of selling software in enterprises. For a small company with an unproven technology, it can be difficult to get the attention of enterprise IT managers. So the next step was to generate recognition and enthusiasm for this Mainsoft product.

The company went about doing this with a derivation of the original product, called Visual MainWin for J2EE, Developer Edition, or Grasshopper. Grasshopper is a product that you can freely download from the Mainsoft Web site. It includes the Apache Tomcat servlet engine and the open source Mono implementation of the .NET Framework, providing a foundation for ASP.NET, ADO.NET, XML, Web services, and .NET server-side runtime services. Developers can use .NET language and Visual Studio skills to develop, debug, and deploy server and Web applications from within the Visual Studio development environment, and run applications natively on the J2EE platform.

According to Cohen, there are now 15,000 registered users of Grasshopper, along with an active community of developers, many of whom act as advocates for expanded use of the technology. As a result, Grasshopper served to bring recognition to Mainsoft from the development community, and also provided success stories for use in enterprise sales and marketing situations. However, it had only limited success in extending the reach of the company into enterprise IT shops and providing access to IT executives. That required a significant enterprise-direct sales force and time to establish relationships within enterprises. Despite a successful company track record that included an initial product release in 1993, this was both expensive and time-consuming.

The second part of the company strategy was to find an avenue for faster and less-expensive access into enterprises. It did this through a partnership with IBM in which Mainsoft generates leads that can then be followed up on by IBM sales representatives, who in many cases might already be familiar with the customers and their needs. "Partnering with IBM gave us access," said Cohen. And it clearly supported IBM's Java direction, enabling the company to offer Microsoft shops the ability to use familiar development tools while deploying on Java.

Last, Mainsoft needed a strategy that would establish the company as a viable and growing standalone business. Cohen is pinning that goal on the Visual MainWin for J2EE, Portal Edition. The Portal Edition provides .NET extensions to IBM WebSphere Portal so IBM customers can run ASP.NET applications natively on WebSphere Portal.

This makes it possible for any enterprise looking for a portal solution to immediately translate existing ASP.NET Web applications to Java to run in the WebSphere Portal. Those enterprises can also continue writing Web applications in Visual Studio and deploying them to either Microsoft IIS or WebSphere Portal, depending on their needs and specific circumstances.

Developers find Mainsoft's .NET to Java compilation a unique and exciting technology. The message that you can use Microsoft development tools while deploying to Java is a powerful one. However, the challenge was to translate that excitement into revenue to create a profitable and growing company.

Yaacov Cohen and Mainsoft believe that they have found the path to do so, and results thus far are encouraging. Many small software companies find it difficult to make the jump from cool technology to a viable business, but Mainsoft might have found the formula.

Mainsoft, Inc.
226 Airport Parkway
Suite 250
San Jose, CA 95110
http://www.mainsoft.com

(http://www.ftponline.com/channels/business/2006_08/companyfocus/mainsoft/)

Monday, August 28, 2006

Players say eye tracking technology helps them feel immersed in their video-game.

Eye Tracking Technology Poised To Be Next Trend To Immerse Gamers

The growing yen of video game enthusiasts to leave the real world in favour of a virtual one is driving a market trend toward developing easier-to-use controls – like those that allow gamers to play through eye movement.


A Queen’s University study confirms that video-gamers feel more immersed and have more fun in virtual environments when they play with commercial eye tracking technology.

These “new controls” replace the mouse click as a means to allow players to interact more naturally with their digital environments.

"Eye tracking technology allows us to build interfaces that respond to users' intentions rather than just their actions. This makes computers feel more natural than ever before," says the study’s co-author David Smith a PhD candidate with Queen’s School of Computing.

First developed in the late 1960s the technology, already used by people with limited mobility, pilots, and market researchers, is increasingly attracting the interest of video-game companies.

This study, also authored by the School of Computing’s Associate Professor Nicholas Graham, showed that players enjoyed the way eye tracking enhanced their involvement in the role-playing game Neverwinter Nights. However, players still preferred to use the mouse to control games like Quake 2, a first-person shooter game, and Lunar Command, an action/arcade game.

Players overwhelmingly indicated an increased feeling of immersion in the gaming world when they played with the eye tracker – 83 percent of those playing Quake 2, 83 percent playing Neverwinter Nights, and 92 percent playing Lunar Command. Smith and Graham suggest this is due to an increased level of feedback, which is given even when the user makes subconscious eye movements.

The researchers integrated a Tobii 1750 desktop eye tracker with these commercial video games. Interacting with the virtual avatars in Neverwinter Nights proved to be the most satisfying use of this technology with 83 percent of the players preferring to play the game with their eyes and 67 percent reporting the experience felt “more natural” than playing the game with a mouse. One participant noted, “I could explore with sight freely and only clicked the mouse when needed”.

Ninety-two percent of Quake 2 players found the mouse easier to use than eye-tracking to rotate their view to visually hone-in on the monsters. The same percentage found the mouse easier to destroy missiles in Lunar Command. Smith and Graham attribute this preference to the “Midas Touch” problem still associated with eye tracking technology, in which the eye tends to “choose” items or directions inadvertently.

The study, a project of Queen’s EQUIS Group lead by Dr. Graham, was funded by NSERC and NECTAR, and was presented this June at the Association of Computing Machinery’s International Conference on Advances in Computer Entertainment Technology.

(
http://www.sciencedaily.com/releases/2006/08/060818005632.htm)

Wednesday, August 23, 2006

Finding Computer Files Hidden In Plain Sight

Keeping computer files private requires only the use of a simple encryption program. For criminals or terrorists wanting to conceal their activities, however, attaching an encrypted file to an e-mail message is sure to raise suspicion with law enforcement or government agents monitoring e-mail traffic.

But what if files could be hidden within the complex digital code of a photographic image? A family snapshot, for example, could contain secret information and even a trained eye wouldn’t know the difference.

That ability to hide files within another file, called steganography, is here thanks to a number of software programs now on the market. The emerging science of detecting such files – steganalysis – is getting a boost from the Midwest Forensics Resource Center at the U.S. Department of Energy’s Ames Laboratory and a pair of Iowa State University researchers.

Electronic images, such as jpeg files, provide the perfect “cover” because they’re very common – a single computer can contain thousands of jpeg images and they can be posted on Web sites or e-mailed anywhere. Steganographic, or stego, techniques allow users to embed a secret file, or payload, by shifting the color values just slightly to account for the “bits” of data being hidden. The payload files can be almost anything from illegal financial transactions and the proverbial off-shore account information to sleeper cell communications or child pornography.

“We’re taking very simple stego techniques and trying to find statistical measures that we can use to distinguish an innocent image from one that has hidden data,” said Clifford Bergman, ISU math professor and researcher on the project. “One of the reasons we’re focusing on images is there’s lots of ‘room’ within a digital image to hide data. You can fiddle with them quite a bit and visually a person can’t see the difference.”

“At the simplest level, consider a black and white photo – each pixel has a grayscale value between zero (black) and 255 (white),” said Jennifer Davidson, ISU math professor and the other investigator on the project. “So the data file for that photo is one long string of those grayscale numbers that represent each pixel.”

Encrypted payload files can be represented by a string of zeros and ones. To embed the payload file, the stego program compares the payload file’s string of zeros and ones to the string of pixel values in the image file. The stego program then changes the image’s pixel values so that an even pixel value represents a zero in the payload string and an odd pixel value represents a one. The person receiving the stego image then looks at the even-odd string of pixel values to reconstruct the payload’s data string of zeros and ones, which can then be decrypted to retrieve the secret file.

“Visually, you won’t see any difference between the before and after photo,” Davidson said, “because the shift in pixel value is so minor. However, it will change the statistical properties of the pixel values of the image and that’s what we’re studying.”

Given the vast number of potential images to review and the variety and complexity of the embedding algorithms used, developing a quick and easy technique to review and detect images that contain hidden files is vital. Bergman and Davidson are utilizing a pattern recognition system called an artificial neural net, or ANN, to distinguish between innocent images and stego images.

Training the ANN involved obtaining a database of 1,300 “clean” original images from a colleague, Ed Delp, at Purdue University. These images were then altered in eight different ways using different stego embedding techniques – involving sophisticated transfer techniques between the spatial and wavelet domains – to create a database of over 10,000 images.

Once trained, the ANN can then apply its rules to new candidate images and classify them as either innocent or stego images.

“The ANN establishes kind of a threshold value,” Bergman said. “If it falls above the threshold, it’s suspicious.
“If you can detect there’s something there, and better yet, what method was used to embed it, you could extract the encrypted data,” Bergman continued. “But then you’re faced with a whole new problem of decrypting the data … and there are ciphers out there that are essentially impossible to solve using current methods.”

In preliminary tests, the ANN was able to identify 92 percent of the stego images and flagged only 10 percent of the innocent images, and the researchers hope those results will get even better. An investigator with the Iowa Department of Criminal Investigation is currently field-testing the program to help evaluate its usefulness and a graphical user interface is being developed to make the program more user friendly.

“Hopefully we can come up with algorithms that are strong enough and the statistics are convincing enough for forensic scientists to use in a court of law,” Bergman said, “so they can say, ‘There’s clearly something suspicious here,’ similar to the way they use DNA evidence to establish a link between the defendant and the crime.”

The project is funded by the Midwest Forensics Resource Center. The MFRC, operated by Ames Laboratory, provides research and support services to crime laboratories and forensic scientists throughout the Midwest.

Ames Laboratory is operated for the Department of Energy by Iowa State University. The Lab conducts research into various areas of national concern, including energy resources, high-speed computer design, environmental cleanup and restoration, and the synthesis and study of new materials.

(http://www.sciencedaily.com/releases/2006/05/060524122456.htm)

Top 10 Excuses Made by Programmers

Good programmer's never re-invent the wheel, so even the excuses when something doesn't work or get done are pretty much the same across languages :) We have compiled the top 10 excuses you are likely to hear if you work with a programmer, the computer department or the tech support team.

10. "I haven't touched that module in weeks!"

9. "It must be a hardware problem."

8. "Somebody must have changed my code."

7. "Did you check for a virus on your system?"

6. "You must have the wrong version."

5. "That's weird..."

4. "There must be something wrong with your data"

3. "It's never done that before."

2. "It worked yesterday."

and the best one

1. "It works on my machine"


(http://www.geek24.com/g/top-10-excuses-made-by-programmers)

10 ways to give a bad presentation By Paul Glen

Takeaway:
If you'd rather not do presentations, just try these out and be assured that you'll never be invited back to speak again.


As IT professionals, eventually, we are all called upon to deliver presentations to clients, users, supervisors, or peers. It's not something that tends to come naturally to us. We'd much rather be writing code, doing project plans, or even writing documentation. Almost anything is better than getting up in front of a group of people. In fact, many consider public speaking to be one of life’s most frightening events.

Because presentations are so important to your careers, C2 Consulting is joining forces with two other companies, Hill Enterprises and Lee Inc. to jointly develop a hands-on training course specifically designed to help IT professionals develop these critical skills.

As a preview to this course, here are a few ideas to help you think about how to screw up your next presentation. If you’d rather not do presentations, just try these out and be assured that you’ll never be invited back to speak again.

1. Just wing it

Preparing for a presentation can be a real drag. Don’t bother. Your audience won’t notice. They enjoy listening to you deliver incoherent and incomplete ideas. Anyway, they know that your time is important, and they can’t expect you to spend your valuable time preparing. It’s better that you just waste all of the audience’s time.

2. Start out weak

An audience typically gives a speaker about 30 seconds before they judge whether to pay attention or not. If you start out weak and lose them, you’ll never get them back, no matter how good you are later. If you’ve followed rule #1 and under-prepared, this may be the best way to cover that up. Just mumble for a minute or two and they won’t be paying enough attention to find out whether you prepared or not.

3. It’s all about me...isn’t it?

Why pay attention to who the audience is and what they’re interested in learning. When you have to give a presentation, it’s all about what you want to tell them. Why be bothered with trying to figure out what they want? Once you’re in front of them, they’re captive and have to listen, right?

4. It’s all about my boss...isn’t it?

If being obsequious is your forte, this is another form of #3. Instead of focusing on your needs, focus on the needs of that one person you really want to impress. Just talk to the important person. Everyone else in the audience will understand and respect you for your focus.

5. Substitute opinions for facts

Here’s a sure fire way to lose credibility quickly. If you want to make sure that the audience won’t believe anything you say, make unsubstantiated claims, or better yet, just state your opinion as if it’s a fact. It makes you seem more important. You’re the ARBITER of TRUTH.

6. Meander

Personal stories, unrelated topics, musings, witticisms, and irrelevant facts all reinforce the message that you’re trying to communicate. Audiences love to hear things that start like, "I just have to tell you this" or "That reminds me of the time when I just a boy of twelve back in Zanadu and got caught stealing olives from Mr. McPruder’s tree."

7. Abandon your objective

Coherence and focus are overrated. Your audience doesn’t really care if you start out with one presentation purpose and seamlessly transition to another one. As long as you smoothly transition from one objective to the next to the next, the audience will follow along. If you do not clearly move from one to the next, you’re actually doing #6, meandering.

8. Ignore the environment

Whether you are the keynote speaker at an industry-wide conference or delivering a proposal to a group of two, presentations are all the same. Refusing to adapt is the sign of a powerful presenter. Bowing to the environment is a sign of weakness.

9. Declare your own time zone

Just start when you start and finish when you finish. Once you’ve got the microphone, you are in control of the audience’s time. Whatever schedule they set is irrelevant. Possession of the microphone gives you the right to dictate the time allocation of your audience.

10. Finish weak

Your conclusion is the last thing that your audience hears, so if you’ve managed to hold their attention even after following the other rules, it’s what they’ll remember most about your performance. A weak conclusion will help ensure that they lose sight of what your presentation was supposed to accomplish. It also helps them remember you in a positive light.

So if you are determined to deliver poor presentations, or to never be invited to do one ever again, following these rules should get you where you’re going.

Paul Glen is the author of the award-winning book "Leading Geeks: How to Manage and Lead People Who Deliver Technology" (Jossey Bass Pfeiffer, 2003) and Principal of C2 Consulting. C2 Consulting helps IT management solve people problems. Paul Glen regularly speaks for corporations and national associations across North America. For more information go to www.c2-consulting.com. He can be reached at info@c2-consulting.com.

(http://articles.techrepublic.com.com/5102-10881-6107629.html)

Wednesday, July 19, 2006

Secrets Of The Masters: Core Java Interview Questions

JDJ's Enterprise Editor, Yakov Fain (pictured) writes: If you are planning to hit the job market, you may need to refresh some of the Java basic terms and techniques to prepare yourself for a technical interview. Let me offer you some of the core Java questions that you might expect during the interviews.

For most questions I’ve provided only short answers to encourage further research. I have included only questions for mid (*) and senior level (**) Java developers. These sample questions could also become handy for people who need to interview Java developers (see also the article "Interviewing Enterprise Java Developers").
30 Java Interview Questions
* Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?

A. The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:


Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

* Q2. What's the difference between an interface and an abstract class?

A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

* Q3. Why would you use a synchronized block vs. synchronized method?

A. Synchronized blocks place locks for shorter periods than synchronized methods.

* Q4. Explain the usage of the keyword transient?

A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

* Q5. How can you force garbage collection?

A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

* Q6. How do you know if an explicit object casting is needed?

A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:


Object a; Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

* Q7. What's the difference between the methods sleep() and wait()

A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

* Q8. Can you write a Java class that could be used both as an applet as well as an application?

A. Yes. Add a main() method to the applet.

* Q9. What's the difference between constructors and other methods?

A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

* Q10. Can you call one constructor from another if a class has multiple constructors

A. Yes. Use this() syntax.

* Q11. Explain the usage of Java packages.

A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

* Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?

A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:


c:\>java com.xyz.hr.Employee

* Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?

A.There's no difference, Sun Microsystems just re-branded this version.

* Q14. What would you use to compare two String variables - the operator == or the method equals()?

A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

* Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

* Q16. Can an inner class declared inside of a method access local variables of this method?

A. It's possible if these variables are final.

* Q17. What can go wrong if you replace && with & in the following code:


String a=null; if (a!=null && a.length()>10) {...}


A. A single ampersand here would lead to a NullPointerException.

* Q18. What's the main difference between a Vector and an ArrayList

A. Java Vector class is internally synchronized and ArrayList is not.

* Q19. When should the method invokeLater()be used?

A. This method is used to ensure that Swing components are updated through the event-dispatching thread.


* Q20. How can a subclass call a method or a constructor defined in a superclass?

A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.


Questions for senior developer job positions follow on the next page...




For senior-level developers:

** Q21. What's the difference between a queue and a stack?

A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

** Q22. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

** Q23. What comes to mind when you hear about a young generation in Java?

A. Garbage collection.

** Q24. What comes to mind when someone mentions a shallow copy in Java?

A. Object cloning.

** Q25. If you're overriding the method equals() of an object, which other method you might also consider?

A. hashCode()

** Q26. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?

A. ArrayList

** Q27. How would you make a copy of an entire Java object with its state?

A. Have this class implement Cloneable interface and call its method clone().

** Q28. How can you minimize the need of garbage collection and make the memory use more effective?

A. Use object pooling and weak object references.

** Q29. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?

A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.

** Q30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?

A. You do not need to specify any access level, and Java will use a default package access level.

(http://it.sys-con.com/read/48839_p.htm)

What is Defensive Copying

I was wondering what to blog about and then I saw the term defensive copying. I have heard this term mentioned a few times but wasn't sure quite what it was. So I thought it was time for a bit of investigation.

So what is defensive copying, also sometime known as object copy.

Defensive copying is concerned with protecting mutable objects e.g. objects who's state can be modified by the user. If you were pass back the reference of an object any changes a user made to that copy of the object would effect your object because you are only passes a reference to the object and not the actual object itself. This is known as a shallow copy.

To avoid users being able to change the values of your object you can pass back a defensive copy. This means that instead of passing back a reference to your object it passes back a new object but with the same values. This means that any changes the user makes to that copy of the object doesn't change the value/state of your object.

It's an interesting idea but I can't think of a use for this at the moment but I'm sure one day this will come in useful.

Here are a couple of links to some probably better explanations with an example

http://www.javapractices.com/Topic15.cjp


http://en.wikipedia.org/wiki/Defensive_copy

The first site Java practices has lots of useful articles and well worth checking out

(http://hoskinator.blogspot.com/2006/07/what-is-defensive-copying.html)

Thursday, June 22, 2006

10 tips on writing reusable code

I have been trying to increase code reuse in the projects I have been doing recently. In my first few years of coding I hardly ever got to reuse any of my code because it was always too coupled together and dependant upon other parts of the code.

So recently I have been trying to write code which I can reuse. It has been interesting that since I have been doing this I have noticed that my library of code is starting to grow. I have started to create more Static Helper classes with useful methods in. I have also been removing the business logic away from any Struts actions or framework work.

To do this I have tried to do a number of things to help this and these are the sort of rules and things I do (in no order) to help me try and achieve this. They are a number of rules and tips I have picked up but can't remember where from

1. Keep the code DRY. Dry means Don't repeat yourself. This is one of the main changes I have tried to bring in. Always try to eradicate duplication and if you find any then move remove the duplication to a relevant place. Sometimes this has lead me to create Static Helper classes or sometimes move it to the class it makes most sense to have it.

2. Make a class/method do just one thing. This is along the lines of the advice of giving the class only one reason to change. This often means creating methods that other methods use but this helps to make the methods/classes simple and less coupled.

3. Write unit tests for your classes AND make it easy to test classes. Writing code that is easy to test is decoupled. If you write code and are thinking about writing a unit test for it then you tend to split up the code into smaller testable chunks.

4. Remove the business logic or main code away from any framework code. Following the rules above will help this. An example I have seen is code that is inside Struts Actions classes, this code is practically impossible to reuse because of all the Struts dependencies that it now linked with.

5. Try to think more abstractly and use Interfaces and Abstract classes. Try to hide dependencies of code behind a more Generic interface/abstract class. The benefit this gives the code is it creates a flexible point in the code where you can then hide future changes behind.

6. Code for extension. Write code that can easily be extended in the future. This is particularly true with the above point. If you write code that uses interfaces then you can extend that interface at a later point.

7. Don't write code that isn't needed. Do the simplest thing possible. Don't waste your time adding methods and classes that might be used in the future. Keep the code simple and focused on what you are trying to deliver. I think I read/heard Josh Bloch say once that "if in doubt, leave it out". Basically who wants to write code that no one (including yourself) is going to use again.

8. Try to reduce coupling. When writing code think about the links and coupling the code is creating, does it need to be linked to those other classes.

9. Be more Modular - make your code more modular, think modular, be modular.

10. Write code like your code is an External API. Imagine the code you are writing is a self contained component.

It wasn't going to be ten until I got to 8 and then thought no one writes 8 tips, lets add two more on. It isn't really a list but it's sort of aims and mental notes I try tell myself when writing code. They are more small bits of code I have written recently that has helped. I would like to hear people's comments and especially their tips on writing reusable code.

(http://cg.scs.carleton.ca/~morin/misc/sortalg/)

Unix: Ten Things Every Java Developer Should Know

One of the great things about Java is how multi-platform it really is. While cross platform glitches do occur, they are not really all that common. But since the law of unintended consequences is all pervasive, we now have the common sight of teams of developers building Java programs meant to run on Unix boxes on Windows.

Developing code meant for Unix on Windows does work reasonably well. The trouble is, many those coders slaving away in front of XP have a very limited understanding of their target platform. If that describes you, this following list is meant for you. Without further ado, here are the ten things you really need to know about Unix, in reverse David Letterman order:

10) You need to be special to use some ports

On Unix machines, programs run by ordinary mortals cannot use network ports less than 1024. Only the special root user can use these ports. If you do decide that you need to run your server as root, be very careful since a program running as root is all powerful on a Unix machine.

9) There is no magic file locking

Windows has this magic file locking mechanism that prevents people from removing a file while it is open. Thus, on a Windows box the call to delete() in the following code is pretty much sure to fail:

InputStream is = new FileInputStream("foo.txt");
(new File("foo.txt")).delete();
int ch;
while( (ch = is.read()) > 0 )
System.out.println( "char: " + (char)ch );
is.close();

The delete will fail because someone (our program in fact) has the file open. After we get done printing out its contents, foo.txt will still be there. The kicker is, the delete() will work just fine on any Unix box. Under Unix, the call to delete() will delete the entry for foo.txt out from the file system, but since someone (our program) still has the file open, the bytes will live on, to be read and printed out. Only when we close the stream will the contents of foo.txt follow its name into oblivion.

In exactly the same way, on a Unix box, someone can delete a program's current directory right out from underneath it.

8) Sometimes there is no GUI

People who are used to Windows are sometimes surprised to find their programs running on a Unix box that has no GUI at all. None. Zilch. Nada. In Unix, the GUI is an add on component and it is completely optional. The machine will run fine without it and servers commonly do. Be very careful making calls to those handy java.awt methods -- some of them will fail on a machine with no GUI.

While you are at it, you may want to rethink what you are writing out with System.out. Many severs not only lack a GUI, they are completely headless: no keyboard, no mouse, no screen. If you are deploying into this kind of environment, the log file is your friend, because your program's cries for help are unlikely to be heard anywhere else.

7) In Unix, there is no registry...

... but if there was, it would be a plain text file. Unix systems have no central place like the Windows registry for storing configuration information. Instead, Unix configuration is spread over a fair number of different files. Many of these files live in a directory called /etc : the list of users is in a file called /etc/passwd, while the name of the machine is typically found in /etc/host.

I guess if you are a Windows user that is the bad news. Here is the good news: most, if not all of the configuration files are plain text files. You can look at them with any old text editor. A further bit of good news is that all modern Unix like systems come with GUIs to edit the configuration files.

6) Forward slashes are your friend

This one is really more about Java on Windows than it is about Unix, but useful anyway. Just about everyone knows that Unix uses forward slashes to separate the bits of a path: /etc/passwd, while Windows uses backslashes: c:\Program Files\Windows. What a disturbing number of folks don't realize is that forward slashes work just fine on in Java on Windows too. On a Windows box, Java is smart enough to translate /a/b/c/foo.txt to something like C:\a\b\c\foo.txt.

Should you rely on this for production? No. If you are really coding cross platform Java, you need know about File.pathSeparator and the various File constructors. But if you are coding stuff that is only meant for Unix, and you just want to test it on your windows box, knowing that the forward slashes work in both places can save a lot of agony.

5) Our services are just programs

In Windows, system services are special programs, written to a particular service API. On Unix, services are provided by pretty ordinary programs that do service like things.

Typically, a Unix service consists of the useful program and a script which starts the program in the background when the system starts up and may shut it down again when the system is halting. Many Unix systems keep these scripts in the /etc/init.d directory.

4) Environment variables are hard to change

Windows programmers sometimes cook up little batch files that set the environment variables they want. Perhaps you need to roll back to an old version of Java and Ant. You might write a batch file that looks something like:

set JAVA_HOME=C:\java1.4.1_05
set ANT_HOME=C:\apache-ant-1.6.1

They can then run the batch file:

c:\> setenv.bat

and have the environment that you need. If you try to translate this directly into Unix-land, you get a script that looks not too different:

#!/bin/sh

JAVA_HOME=/usr/java1.4.1_05
export JAVA_HOME

ANT_HOME=/usr/apache-ant-1.6.1
export ANT_HOME

So you try out your new script...

$ setenv.sh

...and it does nothing. The trouble is that the Unix shell runs scripts by creating a copy of itself and running the script in the new shell. This new shell will read in the script, set all the environment variables and then exit, leaving the original shell and its environment unchanged. I hate when that happens. Changing directories works pretty much the same way: if you do a cd in an ordinary shell script, it will change the directory for that second shell, which may or may not be what you want.

If what you want is to change things in your current shell, you need to have the current shell read in the script directly, without starting a new shell to do the job. You can do this with by using the dot command:

. setenv.sh

Life will be good as your environment variables change.

I should mention that there are several different shells available in Unix. Which one you use is mostly a matter of taste, either yours or the person who set up your account. The commands above will work with many of the common Unix shells, but if you happen to be running the C shell (note the pun), then your little script will need to look something like:

setenv JAVA_HOME /usr/java1.4.1_05
setenv ANT_HOME /usr/apache-ant-1.6.1

You also need a different command to read the script in:

source setenv.csh

3) We don't like spaces in our file names

Okay, this one probably has more to do with Unix users and sys admins than the OS itself, but the fact is, we don't like spaces in our paths. Oh it is perfectly possibly to have spaces in Unix file names. In fact you can put darn near anything in a Unix file name: /tmp/:a,*b%c is actually the name of a directory on the system that I am using to write this.

But can and should are two different things. Unix users spend much of their time using the command line and Unix command line utilities are not crazy about paths with stars, question marks and especially spaces. The Unix guy can always find a way, but if you insist on putting strange characters like spaces in your file names, you are just finding a way to annoy your local Unix guy.

2) There is no carriage to return

If I had just one magic lighting bolt to hurl at one person, I think I would pick the guy who decided to use different line terminating characters on the two major OS's. I suspect we would have hyper intelligent computers by now were it not for all the time wasted trying to figure out why my file looks funny on your OS.

In a plain text file, Windows typically uses a carriage return followed by a newline character to mark the end of a line. Unix dispenses with the carriage return and makes due with the single newline character. Although the tools are getting better, Unix style files may show up as one long line in Windows -- not a single carriage return/newline pair in that file, must be a single line. Likewise, Windows style files will sometimes show up on Unix with garbage characters at the end of a line -- that extra carriage return is meaningless under the Unix convention.

This doesn't matter much for Java files -- it's all white space to the Java compiler. But some native Unix programs care passionately about those funny characters at the end of a line. In particular if you use a Windows based tool to edit a Unix script and your tool adds carriage returns to the script file, you have screwed it up. The script will no longer run. Worse, since many Unix editors do now handle the carriage returns, you could look at the broken script and see nothing wrong.

1) You need a Linux box

If you are doing significant development for Unix, you owe it to yourself and your customers to know something about Unix. If all else fails, get yourself an old PC and some of that free Linux. Or get yourself one of the many bootable Linux-on-a-CD distributions and try it out on any machine. Java is nearly platform independent, but not quite. It is up to you to make up the difference.

(http://www.javalobby.org/articles/10things-unix/)

Tuesday, June 13, 2006

New Robot Has Powerful Cling by Tracy Staedter

A novel, walling-climbing robot could cut thousands of dollars off building inspection fees and one day work to survey urban war zones, where corners, rooftops and building materials thwart otherwise capable robots.

The City Climber rover, being developed by Jizhong Xiao and his team at the City College of New York, uses a vacuum chamber to get vertical. The robot is part of a project that aims to automate mandatory building inspections.

"New York City mandates that the facades of buildings be inspected every five years," said Xiao. "But the current manual inspection is time-consuming and the cost is very high — about $5,000 for one day."

Xiao thinks his robot, which costs less than one day’s work, can do the job faster, cheaper, and more thoroughly than trained technicians, who typically perform their gravity-defying work from suspended scaffolding.

Robotic wall climbers typically employ more superhero-like methods: sticky feet, suction cups, claws, or magnets. But those grippers are only as good as the surface they make contact with.

Suction cups or sticky feet, for example, work best on smooth surfaces such as glass or marble, but not so well on brick. Clawed toes clamber well over rock and brick but slip on glass.

What’s more, such devices tend to move tentatively and cannot navigate over a variety of textured surfaces.

Getting a robot to both cling to a wall and maneuver effortlessly over it are among the two biggest challenges that face researchers focused on wall-climbing robots, said Ning Xi, director of the Laboratory of Robotics and Automation at Michigan State University.

"In both aspects, the City Climber is probably the best in the world right now," said Xi, who is not associated with the project.

The 1-kilogram device clings to the wall by way of a vacuum rotor located in the center of its underbelly. The rotor’s impeller draws air in from the center of the device and spews it out toward the edges.

The column of circulating air creates a region of low air pressure inside the vacuum chamber. Because the surrounding air pressure is higher, it pushes down on the device, keeping it tight to the wall.

Small wheels on the underbelly of the device drive the robot forward and back.

By linking two triangular-shaped modules with a hinged arm, the researchers were able to make the City Climber maneuver around 90-degree angle corners and transition from a wall to a roof — all with the strength to pull or carry a payload four times its weight.

"They have achieved one of the highest payloads reported in the literature," said

professor Nikos Papanikolopoulos of the University of Minnesota.

Xiao will be capitalizing on his rover’s payload capabilities this summer by equipping it with a high-resolution digital camera to conduct a mock building inspection.

(http://dsc.discovery.com/news/briefs/20060612/cityclimber_tec_print.html)

Friday, June 09, 2006

Computer 'Beings' Evolve as Society by Tracy Staedter

Millions of computer-generated entities that live and die by natural selection could reveal how our own culture and language evolve.

The software agents are part of a project called NEW TIES (New and Emergent World Models Through Individual, Evolutionary, and Social Learning), which draws on the expertise of five European research institutions to push computer simulation of artificial worlds further than ever before.

The joint computer project not only reproduces individual and evolutionary learning, but also social learning.

"Social learning is these guys telling each other what they learn on their own. One is learning about hot and cold and another is learning about soft and hard.

"They exchange knowledge and save effort," explained project coordinator Gusz Eiben, a professor of artificial intelligence at the Vrije University, Amsterdam.

Understanding gleaned from such a project could advance machine learning for a range of applications. The learning software could guide exploratory or search and rescue robots that must cooperate to accomplish tasks in unknown environments.

The simulation computer project could even allow policy makers to test out new laws before carrying them out in real life.

The team of computer scientists, sociologists and linguists are creating a population of millions of unique entities that have the ability to pass on life-prolonging tips to their community. In the process, they may evolve their own language.

Computers Create Unique Beings

Each agent is randomly generated by a computer to possess a gender and different variations of life expectancy, fertility, size, and metabolism. The randomness of their programs allows each one to behave differently even when faced with the same set of circumstances.

The outcome of their actions — moving around, talking with another entity, and giving birth — burns fuel that can be replenished by finding the right food source.

Those who lack the wherewithal to survive risk certain death and the inability to propagate their genes.

A simple vocabulary of five to tens words, such as "food," "near" and "agent" gives the entities the basics for communication.

Meanwhile, an algorithm enables two entities to agree on the meaning of new words and could allow the artificial beings to evolve a language.

The idea is to expose the agents to challenges and see how they adapt and develop their own world models.

Recently, Eiben and his team began running their first simulations using 1,000 to 3,000 agents to ask the question: Does individual learning compensate for bad genes? Eventually they plan to scale up to millions of agents.

The big challenge the team faces, said senior researcher Michele Sebag, an expert in artificial intelligence at the University of Paris-Sud, is tracking the behavior of each of the millions of agents.

"You can't look at every agent individually. You have to have new facilities in data mining to understand what is going on in your population," she said.

Following the rationale that "birds of feather stick together," Gusz will be pinpointing and profiling agents who cluster together as well as tracking the locations of each agent as it moves over time.

(http://dsc.discovery.com/news/briefs/20060605/computerculture_tec_print.html)

Thursday, June 08, 2006

java.lang.ThreadLocal

hadn't previously had a reason to use java.lang.ThreadLocal, but I used it recently to add multi-threaded capabilities to a previously single-threaded application...

The application I modified is a basic batch maintenance JDBC type of stand-alone application that reads a text file and updates a database. In order to speed things up, the application was parallelized (if that is a word).

The problem was that the DB2 java.sql.Connection object (which was being retrieved from a custom factory) was not thread-safe. So I opted to use an individual Connection per thread. But how to implement this strategy?

I could have used a connection pool (FOSS or rolled) to help out, but there were a bunch of reasons why I didn't, here's a sampling:

  • The app is small and lean. Adding 3rd party pooling would be considered bloat, writing one myself would be a waste of time.
  • No sharing benefit; one app runs per JVM. If the system were deployed on an app server, where multiple apps could benefit from the same pool, the centralized management might be worth it.

I chose to wrap the Connection in ThreadLocal instead. Then redirect all calls for a connection (in the factory) to ThreadLocal.get().

The class snippet below doesn't really work but it illustrates the point.

public static Connection getConnection() {
return (Connection) conn.get();
}

private static ThreadLocal conn = new ThreadLocal() {
public Object initialValue() {
String driverClass = "whatever";
try {
Class.forName(driverClass);
Connection con =
DriverManager.getConnection("connectionURL",
"user", "password");
con.setReadOnly(true);
con.setAutoCommit(false);
return con;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
};
It worked like a champ.. every thread that called getConnection() got a different Connection and the threads could do their work independently.

(http://mattfleming.com/node/118)