Jason’s Ranting & Raving

Those who don’t read have no advantage over those who can’t.

Archive for the ‘Programming’ Category

Perl: Finding a Class in a Jar file.

Posted by jaystile on June 19, 2009

I was having some trouble finding which jar contained a class I needed. I wrote a perl script to find it.


#!/usr/bin/perl

use strict;

# flush print to the output after every write.
$| = 1;

##############################################################################
# Parse the parameters.
##############################################################################
if( (scalar @ARGV) ne 2) {

   print "Expected arguments: findClass.pl <ROOT_DIRECTORY> <CLASS_NAME>\n";
   exit;
}
print "findClass.pl\n";
my $dir = shift @ARGV;
my $targetClassName = shift @ARGV;
print "Using root directory: $dir\n";
print "Looking for class: $targetClassName\n";

##############################################################################
# Backup your current directory, go to working directory
##############################################################################
my $currDir = `pwd`;
chomp $currDir;
chdir $dir;

# work
searchDir();

##############################################################################
# Return to previous directory and exit.
##############################################################################
chdir $currDir;
exit;

##############################################################################
# Subroutines 
##############################################################################
sub searchDir {
   my @jarList = `find . -name "*.jar"`;
   my @classList;
   my @results = [];

   foreach my $jarName (@jarList) {
      print ".";
      @classList = `jar -tf $jarName`;
      foreach my $className (@classList) {
         if($className =~ /$targetClassName/) {
            print "*";
            chomp $jarName;
            chomp $className;
            push @results, "$jarName:$className";
         }
      }
   }

   foreach my $result (@results) {
      print "$result\n";
   }
}

Posted in Programming | Tagged: | 1 Comment »

Postgres 8.3, JDBC, JPA, and Hibernate example setup.

Posted by jaystile on April 1, 2009

I wanted to access my local postgresql database with JDBC and JPA in the J2SE environment. Refer to my previous post about setting up Postgres 8.3 on Ubuntu 8.04.

If you can’t tell, I’m using java. I’m compiling to java 5. I’m building my project with maven. Inside of a larger maven project which creates my ear file, I created a test project ‘runner’. This creates a jar.
runner/pom.xml

<project> <modelVersion>4.0.0</modelVersion> <groupId>org.myproject</groupId> <artifactId>runner</artifactId> <packaging>jar</packaging> <name>JAR Runner</name> <version>1.0</version> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </pluginManagement> </build> <dependencies> <dependency> <groupId>org.myproject</groupId> <artifactId>util</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>8.3-603.jdbc4</version> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>ejb3-persistence</artifactId> <version>1.0.2.GA</version> </dependency> <dependency> <!-- Note this added other dependencies - hibernate-commons-annotations-3.1.0.GA.jar - slf4j-api.1.4.2.jar - exclude this because it is bunk and causes exceptions. - hibernate-annotations-3.4.0.GA.jar - antlr-2.7.6.jar - commons-collections-3.1.jar - dom4j-1.6.1.jar - xml-apis-1.0.b2.jar - jta-1.1.jar - javassit-3.4.GA.jar --> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager </artifactId> <version>3.4.0.GA</version> <exclusions> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </exclusions> </dependency> <!-- The org.slf4j needed to be included because the one included in org.hibernate.ejb3-persistence did not work --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.5.6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.6</version> </dependency> </dependencies> </project>

runner/src/main/resources/META-INF/persistence.xml file
The core of JPA uses the persistence.xml file to set up the database and entity mappings. I tried using Sun’s example but I found it to hard to configure. I know that hibernate provides a JPA implementation so I used that instead of the glassfish example. It was easy to add because it exists in the maven 2 repository. This persistence.xml is configured to talk to the postgresql 8.3 database. It also contains a mapping for my Entity.

<?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="pu1" transaction-type="RESOURCE_LOCAL"> <class>org.myproject.runner.MapEntity</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <!-- <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/> --> <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/> <property name="hibernate.connection.username" value="myuser"/> <property name="hibernate.connection.password" value="mypassword"/> <property name="hibernate.connection.url" value="jdbc:postgresql://localhost/mydb"/> <property name="hibernate.max_fetch_depth" value="3"/> <!-- cache configuration --> <!-- This was blowing up -v <property name="hibernate.ejb.classcache.org.hibernate.ejb.test.Item" value="read-write"/> <property name="hibernate.ejb.collectioncache.org.hibernate.ejb.test.Item.distributors" value="read-write, RegionName"/> --> <!-- alternatively to <class> and <property> declarations, you can use a regular hibernate.cfg.xml file --> <!-- property name="hibernate.ejb.cfgfile" value="/org/hibernate/ejb/test/hibernate.cfg.xml"/ --> </properties> </persistence-unit> </persistence>

Our database is populated by some sql.

create table map ( pk_id int unique primary key, width int, height int, name varchar(256), last_updated timestamp ); GRANT ALL ON map TO PUBLIC; INSERT INTO map (pk_id, width, height, name, last_updated) VALUES (1, 100, 200, 'test_map', CURRENT_TIMESTAMP);

MapEntity.java
Next, we have an entity to use against our database. It only maps one field, but this was just for testing purposes.

package org.myproject.runner; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="MAP") public class MapEntity { private long id; @Id @Column(name="PK_ID") public long getId() { return id; } public void setId(long id) { this.id = id; } }

DatabaseAccess.java
Finally, we have a java class that can call the database via JDBC or JPA

package org.myproject.runner; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class DatabaseAccess { /**
  • @param args
  • /
public static void main(String[] args) { testJdbc(); testJpa(); } public static void testJdbc() { String url = "jdbc:postgresql://localhost/mydb"; Properties props = new Properties(); props.setProperty("user","myuser"); props.setProperty("password","mypassword"); Connection conn = null; try { conn = DriverManager.getConnection(url, props); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from map"); while(rs.next()) { long id = rs.getLong(1); System.out.println("ID:" + id); } } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void testJpa() { // Use persistence.xml configuration EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu1"); EntityManager em = emf.createEntityManager(); // Retrieve an application managed entity manager // Work with the EM MapEntity map = new MapEntity(); map.setId(5); EntityTransaction transaction = em.getTransaction(); transaction.begin(); em.persist(map); transaction.commit(); em.close(); emf.close(); //close at application end // Create EntityManagerFactory for persistent unit named "pu1" // to be used in this test } }

Posted in Programming | Tagged: , | 2 Comments »

Perl: Converting Decimal to Degrees Minutes Seconds (and vice-versa)

Posted by jaystile on February 21, 2009

Here is some code I playing with trying to get conversion from one coordinate system to another. There is some percision loss due to the floating point math in the conversions. So expect to see a loss of a few seconds when converting from decimal.


1 #!/usr/bin/perl
2
3 use strict;
4 use POSIX qw(ceil floor);
5
6 # flush print to the output after every write.
7 $| = 1;
8
9 testConvertDegMinSecToDecimal();
10 testConvertDecimalToDegMinSec();
11
12 ##### TEST ROUTINES
13 sub testConvertDegMinSecToDecimal {
14 my $result = convertDegMinSecToDecimal(121, 8, 6);
15 print "RESULT: $result\n";
16
17 my $result = convertDegMinSecToDecimal(121, 59, 59);
18 print "RESULT: $result\n";
19 }
20
21 sub testConvertDecimalToDegMinSec {
22 my $deg; my $min; my $sec;
23 ($deg, $min, $sec) = convertDecimalToDegMinSec(121.135);
24 print "RESULT - DEG: $deg MIN: $min SEC: $sec\n";
25
26 ($deg, $min, $sec) = convertDecimalToDegMinSec(121.99317);
27 print "RESULT - DEG: $deg MIN: $min SEC: $sec\n";
28 }
29
30 ##### SUB ROUTINES
31 sub convertDegMinSecToDecimal {
32 my $deg = $_[0];
33 my $min = $_[1];
34 my $sec = $_[2];
35
36 my $result = $deg + ($min/60) + (($sec/60) *(1/60));
37 $result = sprintf("%.5f", $result);
38 }
39
40 sub convertDecimalToDegMinSec {
41 my $input = $_[0];
42 my $deg = floor($input);
43
44 $input = $input - $deg;
45 $input = $input * 60;
46
47 my $min = floor($input);
48
49 $input = $input - $min;
50 $input = $input * 60;
51
52 my $sec = floor($input);
53
54 return ($deg, $min, $sec);
55 }

If you’re playing with degrees minutes seconds & decimal degree conversions you’re probably interested in calculating distance on the Earth. There are two common algorithms for calculating distance that are available as CPAN modules:

Posted in Programming | Tagged: , , | Leave a Comment »

Ubuntu: Howto Setup a Local Subversion Repository

Posted by jaystile on February 13, 2009

This Howto is targeted for Ubuntu 8.04, Hardy Heron. Specifically, this will go through a quick start to get subversion running on the file system. Which, by the way, is NOT the recommended way of setting it up. But if you’re doing some local (1-person) development it is the quickest. The documentation for subversion can be found at svnbook.red-bean.com

Get Subversion!
I used the Synaptec Package Manager to download the ’subversion’ package. You could probably done just as well using ‘apt-get’.

Create Repository!

svnadmin create /var/svnroot/

Import your code into the repository!
Where LocalDir is like /home/username/MyProject
and Where ProjectName is like MyProject

svn import LocalDir file:///var/svnroot/ProjectName

Check out your code from the repository!

svn checkout file:///var/svnroot/PorjectName

Your code is now under version control! (Don’t you feel all grown up now?)

Posted in Programming | Tagged: , | Leave a Comment »

Ubuntu: Howto Setup a Local PostgreSQL and pgAdmin

Posted by jaystile on February 13, 2009

I’m setting up a project for some prototyping web development I’ve been doing. I’m looking at configuring Ubuntu 8.04 Hardy Heron to use Postgresql 8.3. I’ve decided to document my steps (so I don’t forget them).

First off, I’m borrowing heavily from this site: www.ubuntugeek.com which configured Postgresql 8.2 for Ubuntu 7.10. Because I’ve found that Ubuntu, while very helpful in making installations easier, usually does not follow the default installation instructions. Of course you could always RTFM: PostgreSQL Documentation

Download the Postgres 8.3
I used Synaptec Package Manager tool to download the packages ‘postgresql’, ‘postresql-client’, and ‘pgadmin3′. I’m sure you could use the ‘apt-get’ instead.

Configure Postgres Login
Now we need to reset the password for the ‘postgres’ admin account for the server. If you’re going to expose this to the outside world replace ‘password’ with a strong password, like ‘I3!ABaie#9′.

sudo su postgres -c "psql template1"
template1=# ALTER USER postgres WITH PASSWORD ‘password’;
template1=# \q

That alters the password for within the database, now we need to do the same for the unix user ‘postgres’. Make sure you use the password you entered inside of psql.

sudo passwd -d postgres
sudo su postgres -c passwd

From here on in we can use both pgAdmin and command-line access (as the postgres user) to run the database server. Postgres 8.3 is configured to use local access only by default. If you want to open up PostgreSQL follow the link mentioned at the beginning of this article.

Restart the PostgreSQL server.

sudo /etc/init.d/postgresql-8.3 restart

Troubleshooting
I was having a hard time logging with pgadmin3. It turns out I was forgetting the ‘;’ semicolon in the ALTER USER statement.

Now What?
Now, that you have a database why don’t you do something with it? Like write a java application.

Posted in Programming | Tagged: | 1 Comment »