April 29th, 2008

Easily Add PropertyChangeSupport to Beans in Eclipse

If you plan on using JFace Databinding in SWT you will have to implement Property Change Support on all your Java Beans, (barf). I wasn't able to find a plugin that would do this in one click to a class so I came up with two ways to do it.

Here's a code template you can use based on the cool trick I learned at Stuff That Happens

firePropertyChange("${enclosing_method_arguments}", this.${enclosing_method_arguments}, ${line_selection});

Just select the assignment part of your setter and use this template.

If you're really lazy you can use a regex find and replace (With the File Search Dialog)

Your Find string will be:
(this.+) = (\w+);

And your replace string will be:
firePropertyChange("$2", $1, $1 = $2);

Both of these solutions assume you use an Abstract BaseClass to set up your firePropertyChange stuff, then extend for each bean.

Mine looks like this:

package com.weheartcode;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public abstract class BaseEntity {
    private transient PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
            this);

    /**
     * Adds the property change listener.
     *
     * @param listener the listener
     */

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    /**
     * Adds the property change listener.
     *
     * @param propertyName the property name
     * @param listener the listener
     */

    public void addPropertyChangeListener(String propertyName,
            PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
    }

    /**
     * Removes the property change listener.
     *
     * @param listener the listener
     */

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

    /**
     * Removes the property change listener.
     *
     * @param propertyName the property name
     * @param listener the listener
     */

    public void removePropertyChangeListener(String propertyName,
            PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(propertyName,
                listener);
    }

    /**
     * Fire property change.
     *
     * @param propertyName the property name
     * @param oldValue the old value
     * @param newValue the new value
     */

    protected void firePropertyChange(String propertyName, Object oldValue,
            Object newValue) {
        propertyChangeSupport.firePropertyChange(propertyName, oldValue,
                newValue);
    }
}

April 11th, 2008

Automatically Add JavaDoc Comments in Eclipse

Recently while preparing to contribute some code to Eclipse I had to add a copyright comment to the top of every class. Enter JAutodoc it will go through and add Javadoc comments and other automated comments, the update site is:
http://jautodoc.sourceforge.net/update/

Screenshot:
JAutodoc Preferences

February 15th, 2008

Limiting log4j SMTPAppender

I wanted to set a maximum amount of e-mails that SMTPAppender would send after filling up a mailbox with 30,000 damn e-mails.

Turns out it was pretty damn easy, I set up my appender in a java class, and the SMTP appender has a method called setEvaluator that takes an instance of TriggeringEventEvaluator, so I just created a quick inner class like so.

class LimitingEvaluator implements TriggeringEventEvaluator
    {
        private int sentEvents = 0;
        private int MAX_EVENTS = 20;
        @Override
        public boolean isTriggeringEvent(LoggingEvent arg0) {
            sentEvents++;
            if(sentEvents>= MAX_EVENTS)
                return false;
            return true;
        }

    }

and when i set up my appender I do this

appender.setEvaluator(new LimitingEvaluator());

January 17th, 2008

Mass E-mailing, worth paying for a service

Most of us have written little mass e-mailing scripts in the past. No big deal, connect to SNMP, loop through our subscriber list, do our thang. But then the requirements come in: "

"Hey, I need to know what person is clicking on that link, and what time they opened it."

"How does it look in a hotmail account?"

"Does it pass every spam filter?"

Sure, we could code a little link pass through tool, encoded with the person's e-mail address we sent it to, we could create test accounts at all the major e-mail services, we can make all sorts of intricate unsubscribe reports. But why would you want to do that? That's Amateur Hour! You've got cool shit to build. The solution? CampaignMonitor.com. They charge $5 base fee for every "Campaign" you send, plus 1 cent per recipient. So to send to 45,000 people that costs you $50. Big woop.

Plus you get all sorts of intricate reports

Campaign Monitor Reports

They allow you to send full HTML with no size limit, you're not limited to their templates. You also get a nice list manager with unsubscribe and subscribe features built right in.

For a $10 fee you can preview your design in like 10 different e-mail clients & services as well as test that your e-mail passes spam filter (hint: don't put the word viagra in your e-mail).

CampaignMonitor also has relationships with major ISP's so you know your e-mail will not be denied and your servers won't be blacklisted. Plus the office/marketing drones love the reports and the flexibilitiy to send an e-mail campaign themselves.

So don't waste time re-inventing the wheel dummy, pony up your whopper money and do it the easy way.

And no -- they didn't pay me anything for this post, though they can if they want!

January 2nd, 2008

Postgres select replace with regular expression

Postgres seriously kicks ass, here's a quick way to do a substring based on a regular expression. A Co-worker wanted to get the first word out of a column that contained a sentence. If we were using something lame like oracle we'd have to do gymnastics to do that.

It's a one-liner in postgres.

SELECT substring('this is a sentence' FROM '^(.+?)\\s.+$')

So we're selecting out the group that is a series of characters at the start of a line (column) before a space. Epic win.

October 18th, 2007

Upgrade to Gutsy Gibbon Fast

Everyone is excited that Ubuntu 7.10 is finally out. (Have a look at the new feature tour here.)

But the servers are getting hammered, so most people are waiting on the upgrade (voluntarily or otherwise).

No need to wait! The more people who download from Bittorent, the faster your speeds! Grab it while it's hot!
Download a copy of the alternative i386 CD here via Bittorent.
Mac and 64 bit torrents can be obtained here.

Once you have the alternative CD, burn it, boot from it, select the upgrade option, and away you go.

Want to be environmentally friendly and save a CD? Try this:

  1. Mount the ISO to /cdrom:
    sudo mount -t iso9660 ubuntu-7.10-alternate-i386.iso /cdrom -o loop

    Using the full path and proper name for the ISO image.
  2. Open a terminal and type:
    sudo /cdrom/cdromupgrade

    Then the upgrade utility should launch and run from the CD.

Make sure you have the alternative CD and NOT the standard desktop CD.

Good luck and happy upgrading!

October 5th, 2007

Reading An Excel File With Ruby

This tutorial will cover how to read (or parse) an excel file with ruby. I had to write a script to unpivot some data for a co-worker that saved him hours of time, and I got to write a ruby script, so it was a win-win. Here's how you can do the same thing.

Keep reading →

September 18th, 2007

Easy XML Generation with Ruby and ERB

Ah, the bracket tax. XML-Situps, whatever you want to call them, if you write any code (especially if you use java) it should be your sworn enemy. The other day I had to create about 40 XML files for some Java Webstart configs. Instead of doing them by hand, I decided to check out the ERB class for easy "templating" that's built into Ruby. It makes doing code generation very easy!

Our Task

Create a custom XML file for each .jar file in a directory.

...more after the jump!
Keep reading →

September 17th, 2007

Killing a process by name in ubuntu

I have to kill mongrel alot because it's a flea-bitten mutt.

My usual method was to do a ps -aux | grep mongrel , find the pid and kill it!

Annoying and stupid!

Now I just use the nice pkill tool in ubuntu like so.

pkill mongrel

boom! All bad doggies killed! This probably works on other *nix flavors, but who knows if your stupid admin installed it.

September 14th, 2007

Capturing STDERR with ruby backticks

I was writing a ruby script today that ran a linux command for every line in a file. The problem was the backtick operator in ruby only captures stdout, here's a little trick to get stderr as well. (*nix only)

out = `ourlinuxcmd 2>&1`

the 2>&1 bit tells the shell to redirect stderr to stdout

September 10th, 2007

Running rails with mongrel for a specific sub directory

I've started using mongrel for running rails apps with apache2 and mod_proxy , it works like a charm and allows you to run multiple rails apps and mongrel instances on one server.

Your proxy setup looks like this in your httpd.conf or vhost.conf

<VirtualHost *:80>
    ServerName myapp.com
    ServerAlias www.myapp.com

    ProxyPass /myapp http://www.myapp.com:8000/
    ProxyPassReverse /myapp http://www.myapp.com:8000
    ProxyPreserveHost on
  </VirtualHost>

Then in your environment.rb add:

ActionController::AbstractRequest.relative_url_root = '/myapp'

This will make ActionController rewrite the proper URL for your rails application.

September 1st, 2007

♥ HTML Heart Code ♥

Here's how you make a heart in HTML,

&hearts;

Now, stop coming here for that! I'm sick of seeing you in my referral logs!

July 25th, 2007

Postgres Array Joins

Every once in a while you'll come across the need to create a temp table to perform a complicated select query. Not being a big fan of creating these temp tables, I came up with a better solution. Leveraging Postgresql's array structure, I wrote a function that converts a varchar[] to a record set.

CREATE OR REPLACE FUNCTION array_to_rows( character varying[])
RETURNS SETOF character varying AS
$BODY$
DECLARE
in_array alias FOR $1;

out_varchar varchar;
BEGIN
FOR i IN 1..array_upper(in_array,1) loop
RETURN next in_array[i];
end loop;

RETURN;
END
$BODY$
LANGUAGE 'plpgsql' STABLE;

This allows me to pass in an unknown amount of data and perform a LEFT OUTER JOIN on it without losing my orignal data.

SELECT

a.name, b.name, b.other_info

FROM

(SELECT array_to_rows AS name FROM array_to_rows(ARRAY['JOE', 'SCOTT', 'BOB']) a

LEFT OUTER JOIN names b ON a.name ilike '%' || b.name || '%'

Hope you find this useful!

July 22nd, 2007

Java App Empty Window under Compz-Fusion / Beryl

This weekend I was playing around with Ubuntu 7.04 and Compiz-Fusion, I didn't have any major problems until I tried to get Oracle SQL Developer and Aqua Data Studio to work, they would start up but no interface would be drawn.

Well the problem is that they were trying to figure out the Window Manager for themselves and failing.

To fix this add:

export AWT_TOOLKIT=MToolkit

to your bash profile/rc or just in the respective shell script of the app.

Now we can wobble our windows while we code :)

July 12th, 2007

Java Regular Expression Tester

This tool seriously rules, it allows you to test your java regex and automatically escapes it, saving tons of time. The only downside is it's an applet? Yea, an applet remember those?

Regular Expression Tester

cialis sublingual ambien carisoprodol celebrex didrex hydrocodone cialis levitra viagra vs phentermine no prescription fed-ex day tramadol concentrate getting valium out of your system generic ambien internet pharmacies cialis softtabs online fast shipping herbal viagra vs viagra cialis softtabs tramadol tramadol a a target blank no prescription phentermine shipped fed ex viagra for pulmonary disease keywords viagra mp3 ambien rape does viagra help raynauds viagra flowlan viagra lanuage what generic drg is viagra discount viagra offers generic viagra compare tadalafil viagra usage information cialis generic effectiveness valium and breastfeeding phentermine 37.5 without prescribtion over night phentermine cheapest tramadol cod cheap phentermine no prescription free shipping cheap cheap deal pill viagra viagra no membership discount valium ambien not for insomnia cheap phentermine no prescription order phentermine rx without cialis genuinerx net viagra viagra viagra ambien buy generic tramadol is prescribed for generic lunesta myonlinemedsbiz propecia viagra hypertension cialis and pulmonary href tramadol viagra makes you last longer viagra golf cialis fda approval date where to purchase ambien cr phentermine with prescription and facts bush buy porn viagra can't order phentermine anymore cialis pills free cialis pharmaceutical weight loss adipex phentermine viagra jerkoff counterfeit risk viagra viagra selges pharmacist viagra soft tabs phentermine aciphex aciphex aciphex aciphex imitrex cialis levitra viagra compare viagra online shop uk ambien rozerem herbal phentermine no caffeine phentermine without a prescriptions loss phentermine prescription weight phentermine 37.5mg x 90 tabs cheapest cialis onlinecom buy viagra removethis drg generic viagra order pfizer viagra with mastercard phentermine serotonin viagra norvasc drug interaction ambien withdrawl detox tramadol cause depression acupuncture oct ivf women viagra viagra san luis colorado 150 generic cialis softtabs tadalafil cialis vs viagra dose valium ambien dwu attorney orange county ca online fastin pharmacy phentermine cialis and levitra viagra soma tramadol fioricet phentermine online without perscription side effect viagra cialis phentermine hci ingredients ionamin phentermine ecureme com tramadol or lortab edinburgh uk viagra cfm moo tid about valium for anxiety add depression viagra for women pfizer overnight shipping ambien cialis comments cheap 10 mg valium ambien fedex overnight phentermine uk suppliers discount drug viagra inexpensive phentermine 180 tramadol cod phentermine pay by check cialis generic viagra viagra and cocaine overnight no prescription 30 day phentermine phentermine 90 $149 best generic cialis pills price tramadol 180 tablets free phentermine shipping ambien gms viagara cialis levitra comparison phentermine trexle com cheap us phentermine viagra no ejaculation is tramadol like oxycodone viagra gay stories phentermine onlien ambien trips discount drug phentermine valium cewa protocol legally purchase viagra interaction between ambien and celexa before ambien safe to take hydrocodone and ambien is generic cialis real sonota and ambien similair viagra spinal cord research ambien cr addiction cialis pill photo finding phentermine without prescription online viagra health risks tramadol and marjauna viagra contraindications ambien benzodiazapine love valium valium where to buy da vinci robotic surgery cialis viagra safe for dogs men taking cialis and ambien brand viagra without prescription description of viagra phentermine laws buying viagra over the internet ambien and eating interaction paxil and valium adipex p phentermine ecureme com phentermine phentermine hcl online health phentermine tablet buy phentermine viagra ebay dding buy viagra buy phentermine online with no prescription can i take valium with oxycontin tramadol halflife find buy cheap viagra search generic online and viagra soft tramadol classification ambien nightly long-term ambien use cheap viagra overnight delivery phentermine 20 2037.5 valium causes weight loss taking elavil and ambien generic ambien manufacturers cialis princiapl investigator discount phentermine without prescription ultracet amount of tramadol cialis levitra buy warnings for the elderly prescribing ambien valium abuse and effects ambien cr free trial offer phentermine quick site natures valium phentermine buy withc o d valium for stuttering in interview phentermine line cheap adipex phentermine big savings cheap discount viagra viagra pregnancy phentermine buy phentermine blue and white recommended doasage cialis tramadol liver difference between tramadol and ultracet information meridia phentermine xenical c o d phentermine buy on-line 800 ct tramadol cheap cod tramadol tramadol com cialis compare levitra performance viagra prescribed tramadol for taking tramadol and lortab together diflucan tramadol ambien online next day phentermine fastin without prescription viagra and dn or dn geral ambien and male infertility viagra espanol cheap phizer viagra bipolar ambien tramadol picture valium phenergan abuse ambien the dangers of cialis phentermine from georgia phentermine information mexican name disebsin myocarditis viagra difference viagra levitra cialis viagra propecia online gt ambien and restless leg syndrome phentermine not a rip off cialis dizziness generic cialis indian valium doseage side effects of taking viagra viagra for heart attack order phentermine online pay cod ambien and soma online drug interactions flomax viagra viagra cock cialis sex ambien as a date rape drug low cost authentic viagra buy phentermine in th uk ambien experiences ambien domain valium 48 11 is phentermine a amphentamine pictures of valium gg 258 xanax valium comparison cialis levitra better tramadol earnestly online generic valium 10mg look like 1low cost cialis tramadol injection half life actos phentermine pravachol phentermine 37.5mg generic tramadol pain medicine tramadol addiction treatment with methadone 5 citrate generic sildenafil viagra drug policy ambien valium discovered cialis soft tabs wilmington finance phentermine diet pill tramadol hcl 50mg tabs paxil and ambien order phentermine 375 cod generic viagra vega sildenafil citrate drug generic viagra phentermine diet pills shipped to kentucky get viagra dont visit a doctor real phentermine band mitra viagra falls cialis viagra viagra viagra viagra expiration dates phentermine hcl 30 mg canadas viagra commercial buy viagra inte phentermine without prescription online pharmacy emisi dan ambien tramadol acetaminophen pill identification cheap phentermine no prescription cod phentermine 37.5 c o d thailand ambien no overnight phentermine prescription paxil tramadol valium over the counter nexium cialis when will viagra go generic viagra side effects dangers cheap tramadol sales saturday delivery valium homeopathic taking phentermine and chantrex together cialis by fedex tramadol ship on saturday facts about valium ambien fun where can i find phentermine legal no prescription phentermine buy online viagra viagra fda ban on ambien gum viagra tramadol prescription online ambien and seizure valium vicodin original use of viagra buy viagra assist cheap cialis cellules sp cialis es pain tramadol oxycodone combined best deal on viagra looking for phentermine police videos field sobriety tests ambien marijuana and