Shell / awk script to generate getter / setter stubs for .java file

I realize many IDEs do this, but I felt like writing a few lines of script to spit this out instead. This will grab every line marked “private”, whether method or member variable and generates a default getter/setter.

Note: it doesn’t insert the code for you or even capture to a file. Maybe next I’ll do a Javascript version.

	private Date businessDate;
	private String eventTypeCode;
	private String sourceCode;
 
// becomes the following
 
	public Date getBusinessDate(){ 
		return businessDate;
	}
	public void setBusinessDate(Date businessDate){ 
		this.businessDate = businessDate;
	}
	public String getEventTypeCode(){ 
		return eventTypeCode;
	}
	public void setEventTypeCode(String eventTypeCode){ 
		this.eventTypeCode = eventTypeCode;
	}
	public String getSourceCode(){ 
		return sourceCode;
	}
	public void setSourceCode(String sourceCode){ 
		this.sourceCode = sourceCode;
	}

Script source:

#!/bin/env sh
 
# takes a single filename of a .java file and generates a default getter/setter stub for each private variable
cat $1 | grep private | awk '{
	varName=substr($3, 1, length($3) - 1);
	print "	public " $2 " get" toupper(substr(varName,1,1)) substr(varName, 2) "(){ ";
	print "		return " varName ";";
	print "	}"
 
	print "	public void set" toupper(substr(varName,1,1)) substr(varName, 2) "(" $2 " " varName "){ ";
	print "		this." varName " = " varName ";";
	print "	}"
}'

Trying to Dig a Little More In-Depth With Maven

I’ve been reading Maven: The Definitive Guide (affiliate link) as a Kindle eBook and finally got to the point of trying the first example project. The book had mentioned that maven might be installed on Mac OS X already (due to usage with some versions of XCode). Magically, it’s there:

So far, I like the book’s approach to Maven.  It evangelizes maven as a tool, but puts the purpose of Maven in context, and explains, “Why Maven?” as well as explaining that “Maven or Ant?” is the wrong question.

If you’re looking to download the files to complete the example Maven projects, they’ve moved from the URLs in the Kindle version of the book because Maven: The Definitive Guide has been split into two books, Maven by Example and Maven: The Complete Reference.

All the project examples can still be downloaded from a single zip file from the Maven by Example book. However, the chapter numbers are not the same in the Maven by Example book, and the folders in the examples are named by a chap-{title} convention.

Within the zip file:

  • Chapter 4′s project (Simple Weather Application) (originally at http://www.sonatype.com/book/mvn-examples-1.0.zip or http://www.sonatype.com/book/mvn-examples-1.0.tar.gz) is now available in the zip file under:
    • ch-custom/simple-weather
  • Chapter 5′s project (Simple Web Application)
    • ch-simple-web/simple-webapp

 

 


Updated… Add Bookmarklets to Mobile Safari for iPhone / iPad

Today’s iPhone has a nice article on adding bookmarklets to mobile Safari:
TiPs & Tricks: Add bookmarklets to mobile Safari

However, with iOS5, I found that the steps are a little more convoluted:

  1. Add a dummy bookmark using the [->] button in the middle of Safari
  2. Copy the code for the bookmarklet
  3. Tap the Bookmark button (second from the right in Safari).
  4. Tap the [Edit] button
  5. Tap on the dummy bookmark you created
  6. (x) out the URL on the second line
  7. Paste the bookmarklet code on the second line.
  8. (x) out the title and name the bookmarklet appropriately
  9. Tap [Done] when finished.

UPDATED 01/27/2012 bufferapp has new code.

javascript:void(location.href='bufferapp://?u='+encodeURIComponent(location.href))

I also found that the Buffer code was missing, so I captured it and posted it below:

javascript:(function(){
var%20a=document.getElementsByTagName('head')[0],
b=document.createElement('script');
b.type='text/javascript';
b.src='http://bufferapp.com/js/bookmarklet.v1.js?'
+Math.floor(Math.random()*99999);
a.appendChild(b);
})();void%200


Getting an RSS feed of a user’s Twitter timeline

I like to keep a few Twitter feeds in my RSS reader, but can never remember how to get them from Twitter.

I found “Creating an RSS feed of a users Twitter timeline“…

However, I found there is a simpler method (for now)–replace USERNAME with the twitter name. This probably fails when a user changes names, but for stable usernames, this seems to work:

http://twitter.com/statuses/user_timeline/USERNAME.rss

perl script to generate a list of Julian day/day of year dates, given start and end.

I discovered myself on a unix system with a ‘date’ utility that only accepts the -u and + parameters, a fairly basic perl install, and lots of archives that are listed by the “Julian day” (day of year) date.

I put together a perl script using the functions I had at my disposal. The script below makes some allowance for a few different formats, but not nearly as much as Date::Manip would have given me. Feedback appreciated.

#!/usr/bin/perl
 
use Time::Local;
use Getopt::Long;
use strict;
 
 
 
sub getJJJFromParameter
{
	my $dateString = shift; 
	our $mm;
	our $dd;
	our $yyyy;
 
	if($dateString =~ m/\d{1,2}\/\d{1,2}\/\d{2,4}/) {
		($mm, $dd, $yyyy) = split(/\//, $dateString);
	} elsif ($dateString =~ m/\d{2,4}-\d{1,2}-\d{1,2}/) {
		($yyyy, $mm, $dd) = split(/-/, $dateString);
	} elsif ($dateString =~ m/\d{1,2}-\d{1,2}-\d{2,4}/) {
		($mm, $dd, $yyyy) = split(/-/, $dateString);
	}
	$yyyy %= 100;
	$yyyy += 100;
 
	my @dt = localtime(timelocal(0,0,0,$dd,$mm-1,$yyyy));
 
	return($dt[7]+1);
}
 
# main script
 
my $startDate='';
my $endDate='';
my $startJJJ = 0;
my $endJJJ = 0;
 
GetOptions('start=s' => \$startDate, 'end=s' => \$endDate);
 
if ($startDate == '') {
	exit;	
} else {
	$startJJJ = getJJJFromParameter($startDate); 
}
if ($endDate != '') {
	$endJJJ = getJJJFromParameter($endDate); 
} else {
	$endJJJ = $startJJJ;
}
 
my $jjj;
 
printf "%03d to %03d\n", $startJJJ, $endJJJ;
 
for ($jjj=$startJJJ; $jjj <= $endJJJ; $jjj++) {
	printf("%03d ", $jjj);
}

This kid knew enough to be dangerous.

Running this old code, which was probably not actually turned in for anything, through the gcc compiler alone showed that there was a glaring error that would have been exposed on the the first run.

Beyond the initial compiler warnings, there are the ALL CAPS variables, the while loops used as pure for loops…

 
#include "stdio.h"
main()
{
 
    int rows,columns,ROW, COLUMN;
    scanf("%d %d",ROW,COLUMN);
    rows = 0;
    columns = 0;
    while(columns++ < COLUMN)
        printf("\xdb");
    printf("\n");
    rows += 1;
    while(rows++ < (ROW - 2)){
        columns = 0;
        printf("\xdb");
        while(columns++ < (COLUMN - 2)){
            printf(" ");
            }
        printf("\xdb\n");
        }
    columns = 0;
    while(columns++ < COLUMN) {
        printf("\xdb");
        }
 
 
}

Searching for a String in Environmental Variables in Powershell

I’ve updated the post through feedback in the comments:
Regex compare on strings for Get-Variable is Where-Object -Match.

So, the closest parallel to the following bash code:

set | grep "Users"

is the following Powershell:

Get-Variable | Where-Object { $_.Value -Match "Users" }

or shortened:

gv | ? {$_.Value -Match "Users"}

Original Post, with Updates
I’m kind of dumbfounded how this:

Get-Variable | Select-String -Pattern "Users"

returns nothing.

Yet,

Get-Variable > gv.txt
Get-Content gv.txt | Select-String -Pattern "Users"

returns:

$                              Users
HOME                           C:\Users\Administrator
PWD                            C:\Users\Administrator

My initial thought was that maybe redirect captures standard output and standard error and the pipe doesn’t, but then, standard error should all come to the screen unfiltered if not captured by the pipe.

Added:
To add insult to injury, apparently

Get-Variable -Include "PS*"

or just

Get-Variable "PS*"

will do a wildcard search for variable names.

Updated, per the comment from @jburger

Get-Variable | Where-Object { $_.Value -ne $null } | Where-Object {$_.ToString().Contains("Users") }

or

gv | ? { $_.Value -ne $null } | ? {$_.Value.ToString().Contains(“Users”) }

Playing with the Where-Object syntax, I was able to reduce this to:

Get-Variable | Where-Object { $_.Value -ne $null -and $_.ToString().Contains("Users") }

or

gv | ? { $_.Value -ne $null  -and $_.Value.ToString().Contains(“Users”) }

Definitely, this does the trick. However, I’m disappointed that PowerShell doesn’t automatically cast the object output using a ToString() operation.

Entropy of iPhone headphone cables (an excuse to experiment with WP-LaTeX)

Why is it that iPhone earbuds seem to tangle with so many more hopeless tangles than any other cables?
\displaystyle \frac{dS_{iPhoneCable}}{dt} \gg  \frac{dS_{genericCables}}{dt}

Of course, this whole exercise was an excuse to play with LaTeX and the WP-LaTeX plugin.

I also managed to find a nice LaTeX cheat sheet in the process.

Using Escape Codes and Setting Window Title on PS1 for ksh (Korn Shell)

I set up the following in my ~/.profile for my ksh login:

export HOST=$(hostname)
 
export PS1=$(perl -e 'printf "\033]0;\${USER}@\${HOST}:\${PWD}\007\$"')

Unfortunately, ksh doesn’t understand escape codes, so perl or awk is necessary to pull this off–or you can enter them literally via your editor. I like the perl route just for ease of maintenance.

This was inspired by: Setting window title via escape sequences. Of course, the bash version is *much* simpler:

export PS1="\e]2;${USER}@${HOSTNAME}: ${PWD}\a"

Other links of interest:

Count Outlook Inbox Unread / Total From Ruby

Well, Track your unread items/total items count in Outlook on startup, except for the pesky Outlook Macro disabled security problem. Besides, I never restarted Outlook often enough for it to track much of anything.

Instead, I decided to create a Ruby script to track the count. I’ve left reference URLs and test notes in place in this script. Yes, I had to look up how to write a file in Ruby… It’s essentially my 4th programming language after C, Java, Perl, PHP… okay… let’s say it’s pretty deep on the list.

require 'win32ole'
outlook = WIN32OLE.new('Outlook.Application')
# http://rubyonwindows.blogspot.com/2007/07/automating-outlook-with-ruby-tasks.html
mapi = outlook.GetNameSpace('MAPI')
# http://msdn.microsoft.com/en-us/library/aa220100%28office.11%29.aspx
# olFolderCalendar
# olFolderContacts
# olFolderDeletedItems
# olFolderDrafts
# olFolderInbox
# olFolderJournal
# olFolderJunk
# olFolderNotes
# olFolderOutbox
# olFolderSentMail
# olFolderTasks
# olPublicFoldersAllPublicFolders
# olFolderConflicts
# olFolderLocalFailures
# olFolderServerFailures
# olFolderSyncIssues
 
# http://msdn.microsoft.com/en-us/library/aa210918%28v=office.11%29.aspx
# OLEObject.ole_methods
 
class OutlookConst
end
# http://rubyonwindows.blogspot.com/search/label/outlook
WIN32OLE.const_load(outlook, OutlookConst)
 
# p "OlFolderInbox = #{OutlookConst::OlFolderInbox}"
 
inbox = mapi.GetDefaultFolder(OutlookConst::OlFolderInbox)
 
new_messages = 0
total_messages = 0
 
inbox.Items.each {
	| msg |
	begin 
		if msg['UnRead']
			new_messages += 1
		end
		total_messages += 1
	rescue
		puts " Unable to open"
	end
}
puts "You have #{new_messages} new message(s)"
t = Time.now
 
line="#{t.strftime("%m/%d/%Y %I:%M:%S %p")},#{new_messages},#{total_messages}"
 
localname="#{ENV['USERPROFILE']}\\My Documents\\outlookunread.csv"
 
# http://snippets.dzone.com/posts/show/5051
File.open(localname, 'a') {|f| f.puts(line) }