Site Sponsors:
PHP EzLog? 
I am teaching a class on Advanced PHP today. Was surprised at how much we all enjoyed a simple logging demonstration:

* Just ezlog a message to a file.
* @author profnagy
class logfile {

var $defaultFile = 'default.log';

public function open($file) {
$rev = strrev($file);
if (strpos($rev, 'gol.') != 0)
$this->defaultFile = $file . '.log';
$this->defaultFile = $file;
$br = file_exists($this->defaultFile);
return $br;

public function write($message) {
$now = date('Y-m-d H:i:s', time());
$line = "$now\t$message\n";
$result = file_put_contents($this->defaultFile, $line, FILE_APPEND | LOCK_EX);
if ($result === false)
return false;
return true;

public function remove() {
return unlink($this->defaultFile);


The example succinctly demonstrates using PHP dates, time, file I/O, locking, strings... and a little bit more. (i.e If you ever went looking for a Java-Style "endsWith()" in PHP, then consider the fast & easy use of strrev() in the above. Can be logically the same as a "startsWith" in the C/C++/PHP/Standard Lib/PHP Core.)

So if you are just getting into the more advanced features of PHP (or, if you enjoy seeing the spirit of the Standard C Library in use!), then you might enjoy playing with the above PHP Class.

By way of a bonus, it looks and smells a lot like the RFC Log Date & Time format I used for my Open Source / Skype's C/C++ (.ezlog) Legacy.

Time-tested & ready for production.



[ view entry ] ( 10476 views )   |  permalink  |  related link
Dot-Bomb Developer Woes? 
Those of us who have been writing software for any length of time are becoming distressed by the army of - what seems to be increasingly - blissfully ignorant, if not implicitly arrogant - software maintainers.

Harsh Words?

Indeed, from completely alienating decade-long users from even wanting to touch things like the new Microsoft Word (ignorant - ever heard of Microsoft’s CUA guidelines?), to completely breaking our code & understanding of how a framework works (arrogant - do they think that the folks who originally designed it were stupid?), the prognosis for an egalitarian future looks about as short as the tenure that accompanies many of our maintenance woes.


Such were my thoughts as I set my hand toward updating my electronic book reader recently. Wanting to simply replace a JTextArea in favour of some owner-drawn text, we blissfully set about creating our own JPanel to do just that.

Sadly, as I tested my new JPanel, "OMG" was the polite version of what raced thru my mind. The Panel drew. Then it blanked & went fascinatingly stupid on me.

What could be the problem?

Dues, & Dues Not?

Of course, for those of us who have paid our dues in learning the way of the paint(), validate() and update() paradigm, the recommended way of doing things TODAY in Java is to instead use paintComponent(). No problems there. Lots of folks have blogged about it: The default super.paint() quite reasonably manages the draw, as well as paintChildren(etc). Nice design.


The problem is that, even after replacing paint() with paintComponent(), that the flippin' thing still blanks... and blanks... and draws & blanks. --So much so that folks who encounter the problem are being humiliated by folks who thought they knew how painting in Java works.

The Source is Strong with Us

Not to worry though, while only about .01% of the blogs are keeping up with the latest (or even dare date their articles!) Java lets us get to the source of the problem. By chasing the implementation down to the new PaintManager, it became obvious that double-buffering was the culprit. (Image was grabbed before my render - Blank!)

Know Thy Google...

Now that I knew what to 'google for, we came across a nice little post or two on the subject. Push comes to shove, it seems that most folks are okay with the fact that RepaintManager will work so as to ignore any traditional way of using a canvas, paint() or paintComponent() call. I, as well as many others, are not. Blanking our content by default is not cool. It is arrogant.


Sure, the point was made on posts cerca & since 2008 that "the comment on the paint manager has a warning", but the effect is to enforce behaviour on folks who might want to move their legacies forward without reading up on every framework & feature change. In short, things did not blank by default.

Who cares about that GrayRect fix for JDK 6 ... We assume that a company is using tenured resources. (Tenured software develops know their legacies.) We presume that companies know that the best software developer are SMEs on their products well before they are allowed to write a line of code.

Ass u me

I suppose we are now learning never to assume: In the battle between cost, quality, and time, quality takes a back seat. That has ever been the case?

Yet because anyone with a compiler-in-hand is allowed to "save" their companies a few dollars for-the-year, companies should not, therefore, mind as folks decide to abandon their flagship projects. Products like Mic.sos.oft Office. --Look at the savings hiring cheap developers brings!

But Frameworks like Swing impact millions of products. The way it operates should be sacred. Indeed, as I turn a jaundiced eye toward Java ballyhooing their embedded prowess this month, anyone with any tenure simply laughs up their sleeves. Why? Because we know that things like Hadoop are insanely busy re-writing the PERFORMANCE CRITICAL PARTS of their ENTERPRISE Map/Reduce TOOLING in C/C++. (Smile: Only those tiny players - like Facebook, Google, Yahoo, and the DoD, use Hadoop. There are only so many rooms full of servers one should be willing to host: Little wonder they have the need for speed!) (Amazon loves C/C++)

One Map / Reduce Process per JVM = lots of wasted processing power. Indeed, like everyone else, I have my OWN inane theory on one origin of black holes: I believe that, whenever the amount of idle oscillating processing power exceeds the ambient life-force energy (or something :) in any given solar system, that an inevitable implosion results when any rogue dark, strange, uncle (or aunty) -matter migrates there-to. --So the next time you ponder the Horsehead Nebula (or perhaps a stray asteroid ever-drifting nearer our orb?), whimsically imagine a logo in the midst of each perplexity, all body-snatchingly hissing & pointing our way, effectively declaring "Java / Intel Inside"? ;-)

The Way of the Farce

Java Everywhere, indeed? -You want to put Java in a pacemaker with 4K memory? Wow!

Anyone out there understand the very language an operating system is written in (C/C++) ... and why? BECAUSE C/C++ IS FASTER THAN JAVA, FOLKS! That, after all, is WHY we have JNI!

But does anyone c-a-r-e?

Of course not. It is all about marketing today - let the developer & user hang.

For shame!

O, say ... can you .. C?

But when it comes time for ME to look into OUR set-top box, operating system, interstellar probe, weapons system, or pacemaker (!), I, like every other tenured software developer, wants to see a sticker that effectively says "C/C++ Inside."

In the embedded marketplace, all we have to do is to witness how quickly innovations like the BASIC STAMP platform lost their market to AVR / Arduino (even Radio Shack now carries Arduino!) to see how much better C/C++ is ... ! Would anyone even laughingly consider writing an operating system in 100% pure Java?

So call me prejudiced. Call me evil. Call me a communist, liberal, or democrat... but we must believe that part of being a professional is to know the right tool, for the right job.

Conversely, part of being a neophyte is to do well to (1) learn how to use a hammer, but then to do poorly & try to (2) turn everything into a nail. That is just being lazy. (i.e. Be careful who you call "D-e-m-o-c-r-a-t"?! ;-)


Okay - I got that our of my system (pun intended?) Everyone knows I love Java. I also love the way Obama was allowed to destroy the financial future of our nation. I also cherish the fact that both Oracle & Obama still think that what they have done is right. (I voted for the other guy :) Smart is what smart does?

So while far from being the most efficient implementation, and completely for educational purposes, here is how I solved the blinking text (or anything else you might want to draw!) problem in Java:

public void paintComponent(Graphics gr) {
if (manager == null) {
manager = RepaintManager.currentManager(this);

Now it works the way it did before all of those wonderful developers at Sun (ahem) forced their RepaintManager on U.S.



[ view entry ] ( 4024 views )   |  permalink  |  related link
Database + Java + NetBeans = Cooler-er 
It is Sunday … time to take a moment & share a few techniques!


This time-round, someone may like to learn how to use a database under NetBeans?

In-the-past we have shown how to persist data using everything from XML POJO Encoders / Decoders, CSV, and Hibernate. Under NetBeans, we have discovered that it's support for Java Persistence API (JPA) capabilities are second to none... once you know how to avoid a few common-sense pitfalls.

Case Study: The Quote For Today

I discovered several of those pitfalls last week: While migrating my 250,000 events, 180,000 community recipes, 250,000 personal recipes, and 80,000 quotations to Derby for this years effort to support “The Quote For Today”, rather than using Eclipse I opted instead to bring the blog up-to-date by using a database under NetBeans. Once created, a database can be used anywhere.

Getting Started

Of course, the first problem with using a database under NetBeans has to do with location: After we create a project using “New | Java Project | Java Application” from the main NetBeans Menu, how the heck do we add a database?

To demonstrate, assume that we have created a project called “JPA_Demo.” To add a database to the project, all one need do is to select “Window | Services” from the main NetBeans Menu. The Services Tab will appear.

Right-Click Add-Driver

To add a new driver to NetBeans, underneath that Services Tab, right click on the “Drivers” Entry. Select “New Driver.”

Adding a new driver will display the “New JDBC Driver” Dialog Box. Once shown, merely click on that “Add” Button, then browse to wherever your “Derby.jar” file is located. Click “Okay”, then give your driver a snappy name (for the purposes of this demo, I named the driver “dbTQFTD”.)

Note that, by selecting “derby.jar” over the familiar “derbyclient.jar”, we told the driver that we were going to use an embedded database. The java-name for the driver will reflect that (pun intended.)

Right-Click Add-Database

Databases can be used anywhere. Hence now that we have a driver, if there is no database elsewhere, then we need to create one. Another right-click - this time on the Database line underneath that Services Tab, will do the trick:

Since our local database does not already exist, note that we added a “;create = true” suffix. -Also note how the JDBC URL contains the path to a local folder. Next, but certainly not least, do not forget to press that Test Connection Button – Don't do anything else until you can connect to your database a few times here. ...

Lastly, for that last creation-step, simply accept the default APP Schema. Press Finish and all will be well.

Note that after a new database is used (test creation does not count!), that the location encoded in that URL is where the new database will be created. (Windows folks should note that the '/' used above will resolve to '\' on any Microsoft OS.) -Be sure to add that database location to your backup plans?

Creating Database Tables (optional)

If you – like us – are creating a database from-scratch, then you – like me – will want to create a few tables in that locus.

Under NetBeans, the moment we touch our driver, the first thing to get used to is using a “Master Password.” -Working much like a password-key-chain super password, that Master Password is simply another way NetBeans attempts to secure the set of passwords that we probably want the Driver(s) to remember for us. --If you normally like to leave things like mega-passwords blank (not a option in the release I am using), then use use something like “password.”

Ever Users & Ever Passwords

Come to that, always having a default user & password is absolutely a best practice. -When it comes to using Derby, having both a default database user-ID and password are very next things to get used to!

Indeed, when using Derby, please, please, please note that not having both a user and a password is evil. --Not only will such omissions cause problems with the present version of the JPA Tooling, but to date I have traced many a teach-time-failure to students not using some type of default user AND password token.

Again, if you are the type of geek who does not like to use passwords, then defaulting to a user-id that matches the password (or vice versa ;) is not too bad of an idea (e.g. “password”, “admin”, “foo”, or “noneya” readily come to mind.)

Creating columns in a table are easy enough to do. Above, notice that I am obviously creating a table to store our quotations. When stored next to the DAYEVENTS Table, you might well guess where my weekend-work on is heading for 2013 … ?

Generating Java Objects

Now for the fun part: Getting NetBeans to pour-forth the Java!

While, in the past, mapping our objects to a database was a weekend task in-itself, through the miracle of modern ORM Tooling, the process is minuteladen. -By switching back from the current Sources Tab to that original Projects Tab, we can begin to enjoy some of that Java-creation goodness under NetBeans.

By right-clicking on our Project name (JP_Demo), we can select that “New | Other” interface from that pop-up menu. As shown above, once selected we have several Persistence chores to choose from.

The Persistence Unit

The first order of business is to create a new “Persistence Unit.” Invariably saved in our Project under the META-INF folder as “persistence.xml”, the PU is what the tooling uses to access our database:

When first created, the PU will not have any Entity Classes to show us. -Fortunately, any classes we generate will be automatically added to the persistence.xml definition.


Having used things like MyBATIS reminds us of the large gaps there can be between our legacy schema, and our Java Objects. Indeed, while tools like Hibernate & Microsoft's Entity Frameworks have traditionally focused upon what we are interested in doing next (i.e. creating Java Objects from a database table), the clear trend amongst all ORM tooling is to allow our objects to pick-and-choose from the columns amongst all of our database tables.

Trend noted however, for 100% of what we most often want to do with our OWN data, generating code to exactly-match a table is cool enough to be moving on with. Keeping that in mind therefore, yet again we right-click on the project name to activate that “New | Other | Persistence” View. Rather than creating another PU this time, we now want choose “Entity Classes From Database:”

Once we have defined our PU, the IDE is able to look-up each and every table entry in our database. Enjoyable enough to ponder in it's own right (yes, there is a way to do that ;), all we need do is to select the tables & package we want to use to hold the generated code. After that, feel free to select any additional options you may want to play with, press the buttons, and vola!: Your Java Code is ready, sir... -Would you like a controller with that?

The Driver: Our Ultimate Application?

The last step in our quest for database 'Nerdrvana is to do something useful with our PU, Entities, & Controllers. --Sadly, there is no magic tool for that.

Yet given my problem domain however (managing quotes), there is a nice example we can share. Deceptively simple, the example will none-the-less surely be of value to many, on many-a last-mile journey.


The first thing we need to do is to create + manage an EntityManagerFactory:

public class NojControl {

private static final String PUNIT_NAME = "JPA_DemoPU";
private static EntityManagerFactory factory = null;

public static EntityManagerFactory GetFactory() {
if (factory == null) {
factory = Persistence.createEntityManagerFactory(PUNIT_NAME);
return factory;

While of questionable value in the embedded environment (i.e. we can ONLY have a SINGLE Session to an embedded Derby Database!), note that the PUNIT_NAME is not the name of the file – it is the name of our PU in that XML Definition.

Note also that if you have not *also* included the derby.jar as part of your official set of project libraries, then we should do that, too.

(i.e Right-click on JPA_Demo to select "Properties." -Then click on the "Compile" Tab in the Dialog. Press "Add JAR/Folder" to select the derby.jar from the same location as used beneath that "Sources" Tab (described previously).)


Now we can perhaps let the code speak for itself:

public class mainLoader {
public static void main(String... args) {
EntityManagerFactory factory = NojControl.GetFactory();
EntityManager em = factory.createEntityManager();

// STEP: Create an entity in the database

Quote1 zq = new Quote1();
zq.setId((int) new Date().getTime());
zq.setAuthor("Mr. Test");
zq.setQuote("To be, or the heck with it.");;


// STEP: Read existing entities & to console
Query q = em.createQuery("SELECT q FROM Quote1 q");
List<Quote1> qlist = q.getResultList();
for (Quote1 ref : qlist) {
System.out.println("Entries: " + qlist.size());


Give it a try?
[EL Info]: 2012-12-30 12:12:51.342--ServerSession(1477356634)--EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
[EL Info]: 2012-12-30 12:12:53.415--ServerSession(1477356634)--file:/d_drive/USR/code/java/Examples/JPA_Demo/build/classes/_JPA_DemoPU login successful
com.TheQuoteForToday.Quote1[ id=-322090977 ]
Entries: 1
BUILD SUCCESSFUL (total time: 4 seconds)

Notes & Techniques

There are two items worthy of further discussion: Grab Files, and Creation Strategies.

Grab Files

After creating any table, be sure to create a “grab” file. Why? Because when it comes time to re-create a table (be it in another database, or while recovering from some unforeseeable R&D mishap (not so uncommon when dealing with Derby!), one can quickly re-create, rather than create, a table.

Note that "Edit table script" Button in the above animation - very handy!

Creation Strategies

Akin to the above, also note that the PU has some extremely handy database / table re-creation options, as well:

Given that populating data from other technologies can be an iterative process, the above database management features allow us to have the option to start-the-database-over – or not – as required.

Live the Profession!


[ view entry ] ( 12914 views )   |  permalink  |  related link

<<First <Back | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | Next> Last>>