Transformatorhuis

September 2, 2009

Geronimo HTTPS, self signed keys and implementation in Java

Filed under: Coding, Configuration — Tags: , , , — cyberroadie @ 10:19 am

Geronimo

  • Create key in Geronimo (setup certificate)
  • CN needs to be the server name (e.g www.wordpress.com)
  • Create new Keystore (e.g wordpress)
  • In keystore create private key, again CN needs to be server name
  • Add Trust Certificate (copy paste it from the one you created before)
  • In Web Server edit the HTTPS listener and change the keystore file to the on you create before (e.g wordpress)
  • Optional: change address to fixed ip of server

Get certificate

In firefox got to https address -> Add exception -> Get Certificate -> View ->
Details -> Export: export certificate (PEM will do) (e.g. www.wordpress.com)

Shell

keytool -import -trustcacerts -storepass secretphrase -alias “Apache Geronimo Dev” -file www.wordpress.com.cer

The keystore is created in default location ${home}/.keystore

Java

System.setProperty("javax.net.ssl.trustStore", "/home/user/.keystore");
System.setProperty("javax.net.ssl.trustStorePassword","secretphrase");
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

PS Of course it shouldn’t be a static url (/home/user/.keystore), but this is for simplicities sake

August 30, 2009

Crafting Code with Test Driven Development

Filed under: Uncategorized — Tags: , , , , , — cyberroadie @ 6:57 pm

I just finished doing every exercise of Agile Java: Crafting Code with Test-Driven Development by Jeff Langr.

You can find the solutions to all the exercises in my Git Hub repository.

Install git (version control system) and use the following comand:
git clone git://github.com/cyberroadie/spikes.git
to check out the code.

The exercises are not indexed but I added tags (Lessonxx) for every chapter I finished. There are 3 main parts: The chess game, the exercises you can find at the end of every chapter and some exercises I did whilst reading the chapters.

Although Jeff did use JUnit 3 and Ant in the book, I used Maven and JUnit 4 instead.

Please feel free to use this code and I’m happy to receive any updates/patches/improvements :-)

Happy Coding :-)

Olivier

August 26, 2009

What and When with Multithreading

Filed under: Uncategorized — cyberroadie @ 9:15 pm

Stating the obvious: multi threading programming complicates the developing task by adding ‘when’ to the ‘what’ I want program task.

With Java safely doing this ‘when’ can be achieved by programming like this:

public void run() {
        while (alive) {
            synchronized(monitor) {
                monitor.wait(timeout);
            }
            doSomething();
        }
}

I personally find this ’synchronized’ a bolt on solution, it’s a bit like memory management in C++, you have to think about it whilst you put you program together, not necessarily a bad thing, but it would be nice if it was done for you, like garbage collection in Java.

Now I wondered if there is a language which has the added feature of dealing with the synchronization for you? And if a language like that exists would this generate an overhead during execution? What would the syntax (if any) be like?

Maybe time to look at Erlang which follows the Actor Model for it’s concurrency.

August 12, 2009

Contribution to maven-glassfish-plugin project

Filed under: Uncategorized — Tags: — cyberroadie @ 5:09 pm

Contributed to the maven-glassfish-plugin
Added a missing parameter (–force) for glassfish deployment, filed an issue and uploaded the diff: http://jira.ocean.net.au/browse/MGP-21

May 16, 2009

PostgreSQL custom UUID usertype

Filed under: Uncategorized — cyberroadie @ 10:30 am

Posted this on hibernate forums, asking for improvements


public class UuidUserType implements UserType, Serializable {

    private UUID uuid;

    public UuidUserType() {
        super();
    }

    public UuidUserType(UUID uuid) {
        this.uuid = uuid;
    }

    public void setUuid(UUID uuid) {
        this.uuid = uuid;
    }

    public UUID getUuid() {
        return uuid;
    }

    private static final String CAST_EXCEPTION_TEXT = " cannot be cast to a java.util.UUID.";

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#sqlTypes()
	 */
    public int[] sqlTypes() {
        return new int[]{Hibernate.BIG_DECIMAL.sqlType()};
    }

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#returnedClass()
	 */
    public Class returnedClass() {
        return UuidUserType.class;
    }

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#equals(java.lang.Object,
	 *      java.lang.Object)
	 */
    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == null && y == null) {
            return true;
        } else if (x == null || y == null) {
            return false;
        }
        if (!UuidUserType.class.isAssignableFrom(x.getClass())) {
            throw new HibernateException(x.getClass().toString() + CAST_EXCEPTION_TEXT);
        } else if (!UuidUserType.class.isAssignableFrom(y.getClass())) {
            throw new HibernateException(y.getClass().toString() + CAST_EXCEPTION_TEXT);
        }

        UUID a = ((UuidUserType) x).getUuid();
        UUID b = ((UuidUserType) y).getUuid();

        return a.equals(b);
    }

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#hashCode(java.lang.Object)
	 */
    public int hashCode(Object x) throws HibernateException {
        if (!UuidUserType.class.isAssignableFrom(x.getClass())) {
            throw new HibernateException(x.getClass().toString() + CAST_EXCEPTION_TEXT);
        }
        UUID uuid = ((UuidUserType) x).getUuid();
        return uuid.hashCode();
    }

    /*
    * (non-Javadoc)
    *
    * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet,
    *      java.lang.String[], java.lang.Object)
    */

    public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
        Object value = resultSet.getObject(names[0]);
        if (value == null) {
            return null;
        } else {
            UuidUserType retValue = new UuidUserType();
            PGobject pgObject = (PGobject) value;
            retValue.setUuid(UUID.fromString(pgObject.getValue()));
            return retValue;
        }
    }

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement,
	 *      java.lang.Object, int)
	 */
    public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
        if (value == null) {
            preparedStatement.setNull(index, Types.NULL);
            return;
        }

        if (!UuidUserType.class.isAssignableFrom(value.getClass())) {
            throw new HibernateException(value.getClass().toString() + CAST_EXCEPTION_TEXT);
        }

        UUID uuidValue = ((UuidUserType) value).getUuid();
        String uuidStringValue = uuidValue.toString();

        preparedStatement.setObject(index, uuidValue, Types.OTHER);

    }

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#deepCopy(java.lang.Object)
	 */
    public Object deepCopy(Object value) throws HibernateException {
        return (UuidUserType) value;
    }

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#isMutable()
	 */
    public boolean isMutable() {
        return false;
    }

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#disassemble(java.lang.Object)
	 */
    public Serializable disassemble(Object value) throws HibernateException {
        return (Serializable) value;
    }

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#assemble(java.io.Serializable,
	 *      java.lang.Object)
	 */
    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return cached;
    }

    /*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.usertype.UserType#replace(java.lang.Object,
	 *      java.lang.Object, java.lang.Object)
	 */
    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return original;
    }

    /**
     * Returns the least significant 64 bits of this UUID's 128 bit value.
     *
     * @return
     */
    @XmlElement
    public long getLeastSignificantBits() {
        return uuid.getLeastSignificantBits();
    }

    /**
     * Returns the most significant 64 bits of this UUID's 128 bit value.
     *
     * @return
     */
    public long getMostSignificantBits() {
        return uuid.getMostSignificantBits();
    }

    public static UuidUserType fromString(String uuidString) {
        return new UuidUserType(UUID.fromString(uuidString));
    }

}

Generator:

public class UuidGenerator implements IdentifierGenerator {

    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
        return new UuidUserType(UUID.randomUUID());
    }
}

January 27, 2009

Customizing hbm2java (Freemarker & Maven)

Filed under: Coding, Configuration — cyberroadie @ 4:24 pm

Copy the freemarker templates out the the hibernate-tools.jar into you maven directory tree (${basedir}).
In maven:

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<componentProperties>
    ...
    <templatepath>${basedir}/templates</templatepath>
    <template>${basedir}/templates/pojo/Pojo.ftl</template>
</componentProperties>
</plugin>

The template needs to refer to the parent template, the rest is included automaticly.

Howto customize the freemarker templates

Example:
To pick up from a hibernate template (*.hbm.xml):

<property column="TestField" type="integer" name="testField">
    <meta attribute="annotation">@XmlElement</meta>
</property>

And generate:

@XmlElement
private Integer testField;

Add this in PojoFields.ftl:

<#if pojo.hasMetaAttribute(field, "annotation")>
${c2j.getMetaAsString(field, "annotation","\n")}
</#if>
${pojo.getFieldModifiers(field)} ${pojo.getJavaTypeName(field, jdk5)} ${field.name}<#if pojo.hasFieldInitializor(field, jdk5)> = ${pojo.getFieldInitialization(field, jdk5)}</#if>;
</#if>

July 14, 2008

Converting from Latin to UTF-8 and back in your code

Filed under: Uncategorized — Tags: — cyberroadie @ 5:50 am

Linux: iconv -f ISO-8859-1 -t UTF-8 filename.txt

Good overview per OS

June 30, 2008

Persistent Screens Unix Command

Filed under: Uncategorized — Tags: , , — cyberroadie @ 5:50 am

First time:


$ ssh mymachine
$ screen
$ CTRL-a-c
$ CTRL-a-1
$ CRTL-a-d
$ exit

Future times:

$ ssh mymachine
$ screen -r
$ CTRL-a-2
$ CTRL-a-d
$ exit

May 16, 2008

Oracle 11G install problems

Filed under: Uncategorized — Tags: , , — cyberroadie @ 12:12 pm

100% CPU usage problem: http://forums.oracle.com/forums/thread.jspa?threadID=588715&tstart=0

Solve with:

emctl stop dbconsole (or stop the OracleDBConsoleSID Windows service)

In SQLPlus:
create table mgmt_job_bad as select * from sysman.mgmt_job where job_name = ‘PROVISIONING DAEMON’;
delete from sysman.mgmt_job where job_name = ‘PROVISIONING DAEMON’;
commit;

emctl start dbconsole (or start the service)

Startup database:

Start listener: lsnrctl start

Start web console: emctl start dbconsole

Startup database in web console: https://localhost:1158/em/console/

Usefull tools:

netca (listener configuration)

dbca (database configuration), particulary usefull after changing domain name

May 5, 2008

Adding dependecies to Cargo Maven plugin

Filed under: Configuration — cyberroadie @ 9:40 am
Documented here (on the Cargo wiki)

This was to resolve a dependency clash between an old Sax parser implementation introduced via the CeWolf library.
CeWolf used crimson which doesn't support XML schema parser. For some reason the whole maven framework (cargo included) started to use this parser as the
default one instead of using the 'new' Xerces one, generating the following error:

javax.xml.parsers.ParserConfigurationException: Unable to validate
using XSD: Your JAXP provider[org.apache.xerces.jaxp.DocumentBuilderFactoryImpl@ 302e67] does not
support XML Schema. Are you running on Java 1.4 or below with Apache
Crimson? Upgrade to Apache Xerces (or Java 1.5) for full XSD support.


So to circumvent this I had to add the 'new' dependencies to the pom.xml in two places; the normal dependency place and in the cargo-maven plugin)

(the correct version of the libraries is taken from the dependencies elsewhere in the pom.xml
<plugin>
                        <groupId>org.codehaus.cargo</groupId>
                        <artifactId>cargo-maven2-plugin</artifactId>
                        <version>0.3</version>
                        <configuration>
                            <wait>${cargo.wait}</wait>
                            <container>
                                <containerId>${cargo.container}</containerId>
                                <home>${cargo.container.home}</home>
                                <dependencies>
                                    <dependency>
                                        <groupId>xerces</groupId>
                                        <artifactId>xercesImpl</artifactId>
                                    </dependency>
                                    <dependency>
                                        <groupId>xalan</groupId>
                                        <artifactId>xalan</artifactId>
                                    </dependency>
                                </dependencies>
                                <systemProperties>
                                    <javax.xml.parsers.DocumentBuilderFactory>
                                        org.apache.xerces.jaxp.DocumentBuilderFactoryImpl
                                    </javax.xml.parsers.DocumentBuilderFactory>
                                    <javax.xml.parsers.SAXParserFactory>
                                        org.apache.xerces.jaxp.SAXParserFactoryImpl
                                    </javax.xml.parsers.SAXParserFactory>
                                </systemProperties>
                                <zipUrlInstaller>
                                    <url>${cargo.container.url}</url>
                                    <installDir>${installDir}</installDir>
                                </zipUrlInstaller>
                            </container>
                            <configuration>
                                <home>${project.build.directory}/${cargo.container}/container</home>
                                <properties>
                                    <cargo.hostname>${cargo.host}</cargo.hostname>
                                    <cargo.servlet.port>${cargo.port}</cargo.servlet.port>
                                </properties>
                            </configuration>
                        </configuration>
Older Posts »

Blog at WordPress.com.